Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): make Community startup cache-first (#830)

Gener093cafa1dbd9
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a8c996591..fad893137 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -340,6 +340,12 @@ importers:
'@tanstack/query-async-storage-persister':
specifier: 5.103.1
version: 5.103.1
+ '@tanstack/query-db-collection':
+ specifier: 1.2.15
+ version: 1.2.15(@tanstack/[email protected])([email protected])
+ '@tanstack/react-db':
+ specifier: 0.4.1
'@tanstack/react-query':
specifier: 5.103.1
version: 5.103.1([email protected])
@@ -3658,22 +3664,47 @@ packages:
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-vpNIY6QnvFiVGPwdMVnh1OAZyFLioFkM5gQAqefghvgDhCMmWUPjYka2gw6w+2TBy742zsGPtLnpxBzUKXo9Jw==}
+ peerDependencies:
+ typescript: '>=4.7'
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-jeyKbppXwjPNHe0GEVIvsvtirDCxjbPR2xphQaNjgteR15Y+Qnm+6IQNcd3zJ+98uJZ3ot9nagV3UNI+ckVRhQ==}
+ peerDependencies:
+ typescript: '>=4.7'
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-Wo1iKt2b9OT7d+YGhvEPD3DXvPv2etTusIMhMUoG7fbhmxcXCtIjJDEygy91Y2JFlwGyjqiBPRozme7UD8hoqg==}
engines: {node: '>=12'}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-eQ1MyLKCHyXiH7NbdmB80W77OhiMgGBUb+qDx/8WMGbwg5Lf/NlfD0TfNYAqY77i8V3AxoDoYdICrQE5ADw4Yw==}
+ engines: {node: '>=18'}
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-IUwvhe4GEqGYJdiexWHyhZN85BIdmg6F0Vhnvry14Ijm6cNlH9FrBhX+PsUy2sewT0xZyDeB5ZYzeVcZPoTw9A==}
'@tanstack/[email protected]':
resolution: {integrity: sha512-rms8HqTGp6zA00dM+cUQ2eBcgzNJefuu5CAMB37i/6MiGT1zulPOytCFu2a0qjLqVR2n1jENPj9woqFQNuCzWA==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-02d2haENejJObceIFuxCBY/YbyH1t5+Bw6VEl1vev8pX6CkXnkF1cAwxKPTQgHyj34dfWJ5RLo9bB3BgwuQz5Q==}
+ peerDependencies:
+ '@tanstack/query-core': ^5.0.0
+ typescript: '>=4.7'
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-xMOcnULRPEjww0A/0RnweNmcZ5hesLjTekqf8SHxf+BJH729qz6sUu5TsOWFo7J4fu3OR50MeuJUsM3BN78Kfw==}
'@tanstack/[email protected]':
resolution: {integrity: sha512-ybirgB/kkFeMDk97W1ZTH09Wy5zageg6bC1LkxKFUCRFRbsGD+nm9+WVFVllce34O6aKWR3XDBBk2G04bpJYYg==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-mA/a3TAufm0/AZUHmfyKKYfJnEH0XEzJ1Cymt5ZOLqR90MzzDK9KyaDh/JScYHYEipoRkKeRcmedAnHksP6yrg==}
+ peerDependencies:
+ react: '>=16.8.0'
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-l6OzwPbDCnuim8w9McFs3dC/rdXTMZBIBFMVrXzNuhUEzWheldubOu+nKRDtPf+1nLRuwavb3We+nNJq/0vV6w==}
peerDependencies:
@@ -6196,6 +6227,10 @@ packages:
resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-8J3glhz2rrpKG6KmI7wmJo3zH1VjeOpN+vTJSw1fOyO+Viqq3zX6/5NGh6oaZB2qIAYdOYuu5Dz9xp4faOO0Pg==}
+ engines: {node: ^14.13.1 || >=16.0.0}
+
resolution: {integrity: sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==}
engines: {node: '>= 0.6'}
@@ -8667,6 +8702,9 @@ packages:
'@types/react':
optional: true
+ resolution: {integrity: sha512-395+XIP+wqNn3USkFSrNz7G3Ss/MXlZEqesxvzCRFwL14h6e8LukDHdLBePn5pwbm5OQ9vGu8mDyz2lLDIqamQ==}
+
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
@@ -12652,10 +12690,25 @@ snapshots:
postcss: 8.5.22
tailwindcss: 4.3.3
+ dependencies:
+ fractional-indexing: 3.4.0
+ sorted-btree: 1.8.1
+ typescript: 6.0.3
+
+ dependencies:
+ '@standard-schema/spec': 1.1.0
+ '@tanstack/db-ivm': 0.1.22([email protected])
+ '@tanstack/pacer-lite': 0.2.2
+ typescript: 6.0.3
+
'@tanstack/[email protected]':
dependencies:
remove-accents: 0.5.0
+ '@tanstack/[email protected]': {}
+
'@tanstack/[email protected]':
dependencies:
'@tanstack/query-core': 5.103.1
@@ -12663,6 +12716,13 @@ snapshots:
'@tanstack/[email protected]': {}
+ dependencies:
+ '@standard-schema/spec': 1.1.0
+ '@tanstack/db': 0.9.2([email protected])
+ '@tanstack/query-core': 5.103.1
+ typescript: 6.0.3
+
dependencies:
'@kobalte/core': 0.13.14([email protected])
@@ -12683,6 +12743,14 @@ snapshots:
dependencies:
'@tanstack/query-core': 5.103.1
+ dependencies:
+ '@tanstack/db': 0.9.2([email protected])
+ react: 19.3.0
+ use-sync-external-store: 1.6.0([email protected])
+ transitivePeerDependencies:
+ - typescript
+
dependencies:
'@tanstack/query-devtools': 5.103.1([email protected])
@@ -13450,7 +13518,7 @@ snapshots:
magicast: 0.5.4
obug: 2.1.4
tinyrainbow: 3.1.1
transitivePeerDependencies:
- supports-color
@@ -13466,7 +13534,7 @@ snapshots:
obug: 2.1.4
std-env: 4.2.0
tinyrainbow: 3.1.1
'@vitest/[email protected]':
dependencies:
@@ -14930,8 +14998,8 @@ snapshots:
'@next/eslint-plugin-next': 16.3.5([email protected]([email protected]))
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
+ eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -14953,7 +15021,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -14964,21 +15032,21 @@ snapshots:
tinyglobby: 0.2.17
unrs-resolver: 1.12.2
optionalDependencies:
+ eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.2.0
@@ -14989,7 +15057,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.4
is-core-module: 2.17.0
is-glob: 4.0.3
@@ -15476,6 +15544,8 @@ snapshots:
+
@@ -18865,6 +18935,8 @@ snapshots:
optionalDependencies:
'@types/react': 19.3.0
+
diff --git a/scripts/ci/d1-dynamic-bind-contract.ts b/scripts/ci/d1-dynamic-bind-contract.ts
index 64af52188..83efe7e75 100644
--- a/scripts/ci/d1-dynamic-bind-contract.ts
+++ b/scripts/ci/d1-dynamic-bind-contract.ts
@@ -163,5 +163,9 @@ export function scanDynamicBindSites(root: string, sourceOverride?: { file: stri
visit(parsed)
}
- return sites.sort((left, right) => left.key.localeCompare(right.key))
+ // Match the manifest contract's code-unit ordering. localeCompare can order
+ // a lowercase continuation before an uppercase one (for example,
+ // listUnreadMentions before listUnreadMentionScopes), which makes two
+ // otherwise identical key sets compare unequal.
+ return sites.sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0)
}
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
index d0edf1cd1..ca76e1c6f 100644
--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json
+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
@@ -699,6 +699,11 @@
"strategy": "exact-chunk",
"fixedParams": 10
},
+ {
+ "key": "src/shared/src/db/queries/community/mention.ts:listUnreadMentionScopes:inArray:1",
+ "strategy": "exact-chunk",
+ "fixedParams": 10
+ },
{
"key": "src/shared/src/db/queries/community/mention.ts:markChannelMentionsReadBuilder:inArray:1",
"strategy": "subquery"
diff --git a/scripts/ci/verify-changed-patch-coverage.mjs b/scripts/ci/verify-changed-patch-coverage.mjs
new file mode 100644
index 000000000..c24a7f0be
--- /dev/null
+++ b/scripts/ci/verify-changed-patch-coverage.mjs
@@ -0,0 +1,212 @@
+import { readFileSync, writeFileSync } from "node:fs"
+import { execFileSync } from "node:child_process"
+import { isAbsolute, relative, resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+
+const ROOT = resolve(fileURLToPath(new URL("../..", import.meta.url)))
+const REPOSITORY_ROUTING_GIT_ENV = [
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
+ "GIT_COMMON_DIR",
+ "GIT_DIR",
+ "GIT_INDEX_FILE",
+ "GIT_OBJECT_DIRECTORY",
+ "GIT_PREFIX",
+ "GIT_QUARANTINE_PATH",
+ "GIT_WORK_TREE",
+]
+
+export function isolatedRepositoryGitEnvironment(source = process.env) {
+ const env = { ...source }
+ for (const name of REPOSITORY_ROUTING_GIT_ENV) delete env[name]
+ return env
+}
+
+function repositoryGit(root, args) {
+ return execFileSync("git", args, {
+ cwd: root,
+ encoding: "utf8",
+ env: isolatedRepositoryGitEnvironment(),
+ })
+}
+
+function normalizedPath(path) {
+ return path.replaceAll("\\", "/").replace(/^\.\//, "")
+}
+
+export function parseAddedLines(diff) {
+ const changed = new Map()
+ let path = null
+ for (const line of diff.split("\n")) {
+ if (line.startsWith("+++ ")) {
+ path = line === "+++ /dev/null" ? null : normalizedPath(line.slice(4).replace(/^b\//, ""))
+ continue
+ }
+ const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/)
+ if (!path || !hunk) continue
+ const start = Number(hunk[1])
+ const count = hunk[2] === undefined ? 1 : Number(hunk[2])
+ if (count === 0) continue
+ const lines = changed.get(path) ?? new Set()
+ for (let offset = 0; offset < count; offset += 1) lines.add(start + offset)
+ changed.set(path, lines)
+ }
+ return changed
+}
+
+function reportPathForChangedFile(path, changedPaths, root) {
+ const normalized = normalizedPath(path)
+ const relativePath = isAbsolute(path) ? normalizedPath(relative(root, path)) : normalized
+ if (changedPaths.has(relativePath)) return relativePath
+ const matches = [...changedPaths].filter((candidate) => normalized.endsWith(`/${candidate}`))
+ if (matches.length === 1) return matches[0]
+ return null
+}
+
+function addCounter(lines, line, counter) {
+ if (!Number.isInteger(line) || line < 1) return
+ const entries = lines.get(line) ?? []
+ entries.push(counter)
+ lines.set(line, entries)
+}
+
+export function executableLineCounters(file) {
+ const lines = new Map()
+ for (const [id, location] of Object.entries(file.statementMap ?? {})) {
+ addCounter(lines, location.start?.line, {
+ kind: "statement",
+ id,
+ count: Number(file.s?.[id] ?? 0),
+ })
+ }
+ for (const [id, fn] of Object.entries(file.fnMap ?? {})) {
+ addCounter(lines, fn.loc?.start?.line, {
+ kind: "function",
+ id,
+ count: Number(file.f?.[id] ?? 0),
+ })
+ }
+ for (const [id, branch] of Object.entries(file.branchMap ?? {})) {
+ branch.locations.forEach((location, arm) => {
+ addCounter(lines, location.start?.line, {
+ kind: "branch",
+ id,
+ arm,
+ branchType: branch.type,
+ count: Number(file.b?.[id]?.[arm] ?? 0),
+ })
+ })
+ }
+ return lines
+}
+
+export function collectChangedPatchCoverage(changedLines, report, options = {}) {
+ const root = options.root ?? ROOT
+ const changedPaths = new Set(changedLines.keys())
+ const files = new Map()
+
+ for (const [key, file] of Object.entries(report)) {
+ const path = reportPathForChangedFile(file.path ?? key, changedPaths, root)
+ if (!path) continue
+ const changed = changedLines.get(path)
+ const counters = executableLineCounters(file)
+ const lines = files.get(path) ?? new Map()
+ for (const line of changed) {
+ const entries = counters.get(line)
+ if (!entries) continue
+ const current = lines.get(line) ?? []
+ current.push(...entries)
+ lines.set(line, current)
+ }
+ files.set(path, lines)
+ }
+
+ const fileResults = [...files]
+ .map(([path, lines]) => {
+ const details = [...lines]
+ .sort(([left], [right]) => left - right)
+ .map(([line, entries]) => ({
+ line,
+ covered: entries.some((entry) => entry.count > 0),
+ entries,
+ }))
+ const missedLines = details.filter((detail) => !detail.covered).map((detail) => detail.line)
+ return {
+ path,
+ covered: details.length - missedLines.length,
+ missed: missedLines.length,
+ total: details.length,
+ missed_lines: missedLines,
+ lines: details,
+ }
+ })
+ .filter((file) => file.total > 0)
+ .sort((left, right) => left.path.localeCompare(right.path))
+
+ const totals = fileResults.reduce((sum, file) => ({
+ covered: sum.covered + file.covered,
+ missed: sum.missed + file.missed,
+ total: sum.total + file.total,
+ }), { covered: 0, missed: 0, total: 0 })
+
+ return {
+ covered_lines: totals.covered,
+ missed_lines: totals.missed,
+ total_lines: totals.total,
+ percent: totals.total === 0 ? 100 : (totals.covered / totals.total) * 100,
+ files: fileResults,
+ }
+}
+
+function untrackedAddedLinesDiff(root) {
+ const paths = repositoryGit(root, ["ls-files", "--others", "--exclude-standard", "-z"])
+ return paths.split("\0").filter(Boolean).map((path) => {
+ const lineCount = readFileSync(resolve(root, path), "utf8").split("\n").length
+ return [
+ "--- /dev/null",
+ `+++ b/${normalizedPath(path)}`,
+ `@@ -0,0 +1,${lineCount} @@`,
+ ].join("\n")
+ }).join("\n")
+}
+
+function parseArgs(argv) {
+ const args = {}
+ for (let index = 0; index < argv.length; index += 1) {
+ const key = argv[index].replace(/^--/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
+ args[key] = argv[++index]
+ }
+ return args
+}
+
+export function runCli(argv) {
+ const args = parseArgs(argv)
+ if (!args.base || !args.report) throw new Error("--base and --report are required")
+ const root = resolve(args.root ?? ROOT)
+ const head = args.head ?? "WORKTREE"
+ const revisions = head === "WORKTREE" ? [args.base] : [args.base, head]
+ const trackedDiff = repositoryGit(root, ["diff", "--unified=0", ...revisions, "--"])
+ const diff = [
+ trackedDiff,
+ head === "WORKTREE" ? untrackedAddedLinesDiff(root) : "",
+ ].filter(Boolean).join("\n")
+ const report = JSON.parse(readFileSync(resolve(args.report), "utf8"))
+ const result = collectChangedPatchCoverage(parseAddedLines(diff), report, { root })
+ const output = `${JSON.stringify(result, null, 2)}\n`
+ if (args.output) writeFileSync(resolve(args.output), output)
+ process.stdout.write(
+ `Changed patch coverage: ${result.covered_lines}/${result.total_lines} lines (${result.percent.toFixed(6)}%); ${result.missed_lines} missed.\n`,
+ )
+ for (const file of result.files.filter((entry) => entry.missed > 0)) {
+ process.stdout.write(`${file.path}: ${file.missed_lines.join(", ")}\n`)
+ }
+ if (result.missed_lines > 0) {
+ throw new Error(`changed patch has ${result.missed_lines} uncovered executable lines`)
+ }
+ return result
+}
+
+export function runIfMain(metaUrl, argvPath = process.argv[1], argv = process.argv.slice(2)) {
+ if (argvPath === fileURLToPath(metaUrl)) runCli(argv)
+}
+
+runIfMain(import.meta.url)
diff --git a/scripts/ci/verify-changed-patch-coverage.test.ts b/scripts/ci/verify-changed-patch-coverage.test.ts
new file mode 100644
index 000000000..ad81b9737
--- /dev/null
+++ b/scripts/ci/verify-changed-patch-coverage.test.ts
@@ -0,0 +1,292 @@
+import { execFileSync } from "node:child_process"
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { describe, expect, it, vi } from "vitest"
+import {
+ collectChangedPatchCoverage,
+ executableLineCounters,
+ isolatedRepositoryGitEnvironment,
+ parseAddedLines,
+ runCli,
+} from "./verify-changed-patch-coverage.mjs"
+
+function location(line: number) {
+ return { start: { line, column: 0 }, end: { line, column: 1 } }
+}
+
+function git(root: string, ...args: string[]) {
+ return execFileSync("git", args, {
+ cwd: root,
+ encoding: "utf8",
+ env: isolatedRepositoryGitEnvironment(),
+ }).trim()
+}
+
+function fixtureRepository() {
+ const root = mkdtempSync(join(tmpdir(), "changed-patch-coverage-"))
+ git(root, "init", "--quiet")
+ const hooksPath = join(root, ".git", "fixture-hooks")
+ mkdirSync(hooksPath)
+ git(root, "config", "core.hooksPath", hooksPath)
+ git(root, "config", "user.email", "[email protected]")
+ git(root, "config", "user.name", "Coverage Test")
+ mkdirSync(join(root, "src"))
+ writeFileSync(join(root, "src/base.mjs"), "export const base = 1\n")
+ git(root, "add", "src/base.mjs")
+ git(root, "commit", "--quiet", "-m", "base")
+ return root
+}
+
+function poisonParentGitEnvironment() {
+ const parent = mkdtempSync(join(tmpdir(), "changed-patch-parent-"))
+ git(parent, "init", "--quiet")
+ git(parent, "config", "user.email", "[email protected]")
+ git(parent, "config", "user.name", "Parent Test")
+ writeFileSync(join(parent, "parent.mjs"), "export const parent = true\n")
+ git(parent, "add", "parent.mjs")
+ git(parent, "commit", "--quiet", "-m", "parent")
+
+ const parentGitDir = join(parent, ".git")
+ const parentIndex = join(parentGitDir, "index")
+ const parentIndexBefore = readFileSync(parentIndex)
+ const parentHookMarker = join(parent, "parent-hook-ran")
+ const parentHooksPath = join(parentGitDir, "parent-hooks")
+ mkdirSync(parentHooksPath)
+ const parentHook = join(parentHooksPath, "pre-commit")
+ writeFileSync(parentHook, [
+ "#!/bin/sh",
+ `touch '${parentHookMarker}'`,
+ "exit 1",
+ "",
+ ].join("\n"))
+ chmodSync(parentHook, 0o755)
+ git(parent, "config", "core.hooksPath", parentHooksPath)
+
+ const previousGitEnv = new Map<string, string | undefined>()
+ const poisonedGitEnv = {
+ GIT_ALTERNATE_OBJECT_DIRECTORIES: join(parentGitDir, "objects"),
+ GIT_COMMON_DIR: parentGitDir,
+ GIT_DIR: parentGitDir,
+ GIT_INDEX_FILE: parentIndex,
+ GIT_OBJECT_DIRECTORY: join(parentGitDir, "objects"),
+ GIT_PREFIX: "poisoned/",
+ GIT_QUARANTINE_PATH: join(parentGitDir, "objects"),
+ GIT_WORK_TREE: parent,
+ }
+ for (const [name, value] of Object.entries(poisonedGitEnv)) {
+ previousGitEnv.set(name, process.env[name])
+ process.env[name] = value
+ }
+
+ return {
+ expectUnchanged() {
+ expect(readFileSync(parentIndex)).toEqual(parentIndexBefore)
+ expect(existsSync(parentHookMarker)).toBe(false)
+ },
+ restore() {
+ for (const [name, value] of previousGitEnv) {
+ if (value === undefined) delete process.env[name]
+ else process.env[name] = value
+ }
+ rmSync(parent, { recursive: true, force: true })
+ },
+ }
+}
+
+function writeReport(root: string, path: string, count: number) {
+ const reportPath = join(root, "report.json")
+ writeFileSync(reportPath, JSON.stringify({
+ [join(root, path)]: {
+ path: join(root, path),
+ statementMap: { "0": location(1) },
+ s: { "0": count },
+ fnMap: {},
+ f: {},
+ branchMap: {},
+ b: {},
+ },
+ }))
+ return reportPath
+}
+
+describe("changed patch coverage", () => {
+ it("parses added and replaced head lines without counting deletions", () => {
+ const changed = parseAddedLines([
+ "diff --git a/src/a.ts b/src/a.ts",
+ "--- a/src/a.ts",
+ "+++ b/src/a.ts",
+ "@@ -1,2 +1,3 @@",
+ "@@ -8,2 +9,0 @@",
+ "diff --git a/src/deleted.ts b/src/deleted.ts",
+ "--- a/src/deleted.ts",
+ "+++ /dev/null",
+ "@@ -1 +0,0 @@",
+ ].join("\n"))
+
+ expect([...changed.get("src/a.ts")!]).toEqual([1, 2, 3])
+ expect(changed.has("src/deleted.ts")).toBe(false)
+ })
+
+ it("uses statement starts, function body starts, and every branch-arm start", () => {
+ const report = {
+ "/host/work/repo/src/a.ts": {
+ path: "/host/work/repo/src/a.ts",
+ statementMap: {
+ "0": location(2),
+ "1": location(6),
+ "2": location(7),
+ },
+ s: { "0": 3, "1": 0, "2": 2 },
+ fnMap: {
+ "0": { name: "run", decl: location(1), loc: location(3) },
+ },
+ f: { "0": 1 },
+ branchMap: {
+ "0": { type: "cond-expr", locations: [location(4), location(5)] },
+ "1": { type: "binary-expr", locations: [location(7)] },
+ },
+ b: { "0": [0, 2], "1": [0] },
+ },
+ }
+ const changed = new Map([["src/a.ts", new Set([1, 2, 3, 4, 5, 6, 7])]])
+
+ const result = collectChangedPatchCoverage(changed, report, { root: "/repo" })
+
+ expect(result).toMatchObject({
+ covered_lines: 4,
+ missed_lines: 2,
+ total_lines: 6,
+ files: [{ path: "src/a.ts", missed_lines: [4, 6] }],
+ })
+ expect(result.files[0]!.lines.map(({ line }) => line)).not.toContain(1)
+ expect(result.files[0]!.lines.find(({ line }) => line === 7)).toMatchObject({ covered: true })
+ })
+
+ it("merges counters for the same line across coverage sessions", () => {
+ const file = {
+ statementMap: { "0": location(8) },
+ s: { "0": 0 },
+ fnMap: {},
+ f: {},
+ branchMap: { "0": { type: "binary-expr", locations: [location(8)] } },
+ b: { "0": [4] },
+ }
+
+ expect(executableLineCounters(file).get(8)).toEqual([
+ { kind: "statement", id: "0", count: 0 },
+ { kind: "branch", id: "0", arm: 0, branchType: "binary-expr", count: 4 },
+ ])
+ })
+
+ it("ignores report paths that cannot be mapped to exactly one changed file", () => {
+ const changed = new Map([
+ ["one/src/a.ts", new Set([1])],
+ ["two/src/a.ts", new Set([1])],
+ ])
+ const report = {
+ "/host/src/a.ts": {
+ path: "/host/src/a.ts",
+ statementMap: { "0": location(1) },
+ s: { "0": 1 },
+ },
+ }
+
+ expect(collectChangedPatchCoverage(changed, report, { root: "/repo" }))
+ .toMatchObject({ total_lines: 0, percent: 100, files: [] })
+ })
+
+ it("sorts covered changed files by repository path", () => {
+ const changed = new Map([
+ ["src/z.ts", new Set([1])],
+ ["src/a.ts", new Set([1])],
+ ])
+ const coveredFile = (path: string) => ({
+ path,
+ statementMap: { "0": location(1) },
+ s: { "0": 1 },
+ fnMap: {},
+ f: {},
+ branchMap: {},
+ b: {},
+ })
+
+ const result = collectChangedPatchCoverage(changed, {
+ "/repo/src/z.ts": coveredFile("/repo/src/z.ts"),
+ "/repo/src/a.ts": coveredFile("/repo/src/a.ts"),
+ }, { root: "/repo" })
+
+ expect(result.files.map((file) => file.path)).toEqual(["src/a.ts", "src/z.ts"])
+ })
+
+ it("includes untracked worktree source and writes a successful CLI report", () => {
+ const parent = poisonParentGitEnvironment()
+ let root: string | undefined
+ const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true)
+ try {
+ root = fixtureRepository()
+ expect(git(root, "rev-parse", "HEAD")).toMatch(/^[0-9a-f]{40}$/)
+ writeFileSync(join(root, "src/new.mjs"), "export const added = true\n")
+ const reportPath = writeReport(root, "src/new.mjs", 1)
+ const outputPath = join(root, "result.json")
+
+ const result = runCli([
+ "--base", "HEAD",
+ "--report", reportPath,
+ "--root", root,
+ "--head", "WORKTREE",
+ "--output", outputPath,
+ "--unused-option", "covered",
+ ])
+
+ expect(result).toMatchObject({ covered_lines: 1, missed_lines: 0, total_lines: 1 })
+ expect(JSON.parse(readFileSync(outputPath, "utf8"))).toMatchObject({ percent: 100 })
+ expect(stdout).toHaveBeenCalledWith(expect.stringContaining("1/1 lines"))
+ parent.expectUnchanged()
+ } finally {
+ stdout.mockRestore()
+ parent.restore()
+ if (root) rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it("supports an explicit head and reports every missed file before failing", () => {
+ const parent = poisonParentGitEnvironment()
+ let root: string | undefined
+ const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true)
+ try {
+ root = fixtureRepository()
+ const base = git(root, "rev-parse", "HEAD")
+ writeFileSync(join(root, "src/base.mjs"), "export const base = 2\n")
+ git(root, "add", "src/base.mjs")
+ git(root, "commit", "--quiet", "-m", "head")
+ const reportPath = writeReport(root, "src/base.mjs", 0)
+
+ expect(() => runCli([
+ "--base", base,
+ "--head", "HEAD",
+ "--report", reportPath,
+ "--root", root,
+ ])).toThrow("changed patch has 1 uncovered executable lines")
+ expect(stdout).toHaveBeenCalledWith(expect.stringContaining("0/1 lines"))
+ expect(stdout).toHaveBeenCalledWith("src/base.mjs: 1\n")
+ parent.expectUnchanged()
+ } finally {
+ stdout.mockRestore()
+ parent.restore()
+ if (root) rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it("requires the CLI inputs before invoking git", () => {
+ expect(() => runCli([])).toThrow("--base and --report")
+ })
+})
diff --git a/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
index 794e2b57c..56e5c6151 100644
--- a/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/normalizer.test.ts
@@ -441,7 +441,7 @@ describe("ClaudeEventNormalizer.normalizeLine", () => {
// managerRuntime buffers the `error`'s message on the way past, then reads
// it out when the trailing `turn_end` arrives to stamp `endReason:"errored"`.
// That handoff only works if error precedes turn_end in the SAME batch.
- // See plans/daemon-runtime-error-rewake.md B1.
+ // The resulting turn_end must therefore carry the preceding runtime error.
const out = new ClaudeEventNormalizer().normalizeLine(
J({ type: "result", is_error: true, result: "boom", session_id: "s1" }),
);
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.ts b/src/daemon/agent-driver/src/adapters/codex/index.ts
index 9c918eefa..8973634f5 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts
@@ -5,7 +5,7 @@
* Claude, a `turn/steer` sent while a tool call / compaction / review is in
* flight can race the app-server's own turn-state handling, so busy delivery
* is `gated` — held until a safe boundary by the manager-level mechanism in
- * `manager/managerPolicy.ts` (see plans/wire-gated-busy-steering-daemon.md). A
+ * `manager/managerPolicy.ts`. A
* busy message becomes a `turn/steer` RPC against the active turn, while an
* idle message becomes a fresh `turn/start` — the encoding itself is
* unaffected by gating, only WHEN the manager calls it.
@@ -136,8 +136,8 @@ export class CodexDriver implements BackendAdapter {
async probe(command?: string) {
// probeCliRuntime spawns `--version` — a missing vendored binary (npm
// package resolves but the aarch64 blob is absent) fails there even
- // though resolveCommandOnPath returned a JS wrapper. See
- // plans/community-machine-presence-fix.md.
+ // though resolveCommandOnPath returned a JS wrapper; probing the resolved
+ // command keeps runtime health tied to what can actually execute.
const result = await probeCliRuntime("codex", {}, command);
if (result.status !== "healthy") return result;
return {
diff --git a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
index c12b143b1..f8de4ac1c 100644
--- a/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/normalizer.test.ts
@@ -1,6 +1,6 @@
/**
* Tests for `CodexEventNormalizer` — in particular the tool_call/tool_output
- * symmetry fix from plans/wire-gated-busy-steering-daemon.md (§9c): before
+ * tool-call/tool-output symmetry fix: before
* this fix, `handleItemCompleted` had no case for `fileChange`, `webSearch`,
* or `collabAgentToolCall`, so `outstandingToolUses` (tracked by the manager
* via these `AdapterEvent`s) would permanently increment on the first such
diff --git a/src/daemon/agent-driver/src/controller/process-host.test.ts b/src/daemon/agent-driver/src/controller/process-host.test.ts
index abf2d20b5..205117eae 100644
--- a/src/daemon/agent-driver/src/controller/process-host.test.ts
+++ b/src/daemon/agent-driver/src/controller/process-host.test.ts
@@ -14,7 +14,7 @@ vi.mock("../internal/killTree.js", async (importOriginal) => ({
}));
/*
- * Red-line-5(b) of plans/daemon-trace-completeness-charter.md (T1): the synthetic
+ * Trace-completeness invariant: the synthetic
* `session.fire("exit", {...})` tests in managerRuntime.test.ts prove the daemon
* THREADS exitCode/exitSignal/abnormal into the FSM/trace. They do NOT prove the
* SOURCE is real — that a genuinely killed subprocess actually fills `info.code`
diff --git a/src/daemon/agent-driver/src/controller/sdk-host.test.ts b/src/daemon/agent-driver/src/controller/sdk-host.test.ts
index f4cd94b1b..0cd5f69d0 100644
--- a/src/daemon/agent-driver/src/controller/sdk-host.test.ts
+++ b/src/daemon/agent-driver/src/controller/sdk-host.test.ts
@@ -3,7 +3,7 @@ import { SdkLane } from "./sdk-host.js";
import type { VendorSessionHandle } from "../internal/adapter.js";
/**
- * See plans/sdk-runtime-session-live-isstreaming-guard.md — `send()`'s idle
+ * `send()`'s idle
* path is a second, independent line of defense against "Agent is already
* processing": it re-checks the vendor SDK's live `isStreaming` at the
* moment of delivery instead of trusting the caller's `mode: "idle"` at face
diff --git a/src/daemon/agent-driver/src/internal/killTree.test.ts b/src/daemon/agent-driver/src/internal/killTree.test.ts
index 0add3512c..89fcd1722 100644
--- a/src/daemon/agent-driver/src/internal/killTree.test.ts
+++ b/src/daemon/agent-driver/src/internal/killTree.test.ts
@@ -9,7 +9,7 @@ import { spawnAgentProcess, killProcessTree, isAlive } from "./killTree.js";
/**
* These tests spawn real child processes rather than mocking
* `child_process` — the bug this file guards against (silent no-op kill on
- * a non-detached child, see plans/fix-daemon-agent-process-kill.md) is a
+ * a non-detached child) is a
* real OS process-group interaction that a mock would trivially hide.
*/
diff --git a/src/daemon/agent-driver/src/internal/probe.test.ts b/src/daemon/agent-driver/src/internal/probe.test.ts
index 1cf3cc289..1bf564272 100644
--- a/src/daemon/agent-driver/src/internal/probe.test.ts
+++ b/src/daemon/agent-driver/src/internal/probe.test.ts
@@ -17,7 +17,7 @@ vi.mock("child_process", () => ({ execFileSync: vi.fn() }));
* `resolveSpawnSpec` is what makes Cursor/OpenCode/Codex spawnable on Windows
* when the CLI resolves to a
* `.cmd`/`.bat` shim, which `child_process.spawn` can only exec through a
- * shell. See plans/other-drivers-audit-fixes.md finding #2.
+ * shell.
*/
describe("resolveSpawnSpec", () => {
it("sets shell: true on win32 when the resolved binary is a .cmd shim", () => {
diff --git a/src/daemon/eslint.config.ts b/src/daemon/eslint.config.ts
index 488b41e7f..6db09117b 100644
--- a/src/daemon/eslint.config.ts
+++ b/src/daemon/eslint.config.ts
@@ -14,7 +14,7 @@ const eslintConfig = defineConfig([
{
// Drivers must spawn agent CLIs through `spawnAgentProcess` (src/runtime/killTree.ts)
// so the detached-process-group contract killProcessTree relies on can't be
- // silently skipped by a new/edited driver — see plans/fix-daemon-agent-process-kill.md.
+ // silently skipped by a new or edited driver.
files: ["src/drivers/**/*.ts"],
ignores: ["src/drivers/**/*.test.ts"],
rules: {
diff --git a/src/daemon/src/cli/daemonList.test.ts b/src/daemon/src/cli/daemonList.test.ts
index 583a39acb..7bd717d71 100644
--- a/src/daemon/src/cli/daemonList.test.ts
+++ b/src/daemon/src/cli/daemonList.test.ts
@@ -6,7 +6,7 @@ import { daemonList } from "./daemonStart";
import { renderDaemonList } from "./index";
/*
- * C3 (plans/daemon-cli-humanize-charter.md): `daemon list` returns an addressing
+ * `daemon list` returns an addressing
* `id` (= pidfile name, what `daemon stop <id>` eats) + agents/lastActive from
* status.json + pid/alive — and NO machine-key/credential. The renderer prints a
* human table, not JSON, with the machine key nowhere in sight (red line 2).
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index b6c9e389c..17730dff8 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -68,8 +68,7 @@ function daemonsDir(baseDir: string): string {
* machineId), so hashing the CLI key drifted the directory on every reconnect —
* orphan subdirs + a double-start guard that never fired. machineId is stable
* across reconnects (activate reuses the same machine row) and is what
- * `daemon list` shows / `daemon stop <id>` takes. See
- * plans/daemon-c01-machineid-anchor.md.
+ * `daemon list` shows / `daemon stop <id>` takes.
*/
export function daemonDirById(baseDir: string, id: string): string {
return path.join(daemonsDir(baseDir), validateDaemonId(id));
@@ -716,7 +715,7 @@ export interface DaemonStopOpts {
* Core stop: SIGTERM → wait for the daemon's own ordered shutdown (stopAll
* agent children, close channel/proxy, remove pidfile) → escalate to SIGKILL
* only if it overruns the grace window. This kill/teardown semantic is
- * UNCHANGED by stop-by-id (plans/daemon-cli-humanize-charter.md red line 3) —
+ * unchanged by stop-by-id —
* only HOW the daemon is addressed changed (its list id, not a machine key).
*/
async function stopExactPid(pid: number): Promise<void> {
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index bab16edb4..7e90eaa67 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -291,14 +291,14 @@ export interface CreateDaemonOptions {
* (`<fsmTraceDir>/fsm-trace.jsonl`, size-capped/rotating — batch E1). When
* omitted the default trace is off (test stubs). `ALOOK_FSM_TRACE=<path>`
* overrides BOTH: it takes precedence and uses an unbounded single-file
- * append (deep-investigation mode). See plans/daemon-fsm-desync.md batch E.
+ * append for deep investigations.
*/
fsmTraceDir?: string;
/**
* Absolute path for the periodic `daemon status` snapshot file (batch E2).
* The running daemon writes a slim per-agent FSM projection here (atomic
* tmp→rename) on a timer; the `daemon status` CLI reads it. Omit for test
- * stubs → no snapshot writing. See plans/daemon-fsm-desync.md batch E2.
+ * stubs → no snapshot writing.
*/
statusFilePath?: string;
/**
@@ -1042,7 +1042,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
onRuntimeRawLine,
// FSM transition trace → file. One JSON line per reduce so a wedge that
// logs nothing else is reconstructable from its FSM history (the "no log
- // when it breaks" fix, plans/daemon-fsm-desync.md). Two modes:
+ // when it breaks" fix). Two modes:
// - DEFAULT ON (batch E1): a bounded, size-capped/rotating sink at
// `<fsmTraceDir>/fsm-trace.jsonl` — so we're never blind to the last
// wedge without pre-setting an env, and it can't fill the disk.
diff --git a/src/daemon/src/discovery.ts b/src/daemon/src/discovery.ts
index c3610ea80..6a8369b3a 100644
--- a/src/daemon/src/discovery.ts
+++ b/src/daemon/src/discovery.ts
@@ -107,8 +107,7 @@ export interface RuntimeInfo {
/**
* Probe all registered drivers and return which runtimes are available.
* capabilities to the server. Runtime health after startup is mutated live
- * by `AgentRouter.markRuntimeUnhealthy` / `markRuntimeHealthy` — see
- * plans/community-machine-presence-fix.md.
+ * by `AgentRouter.markRuntimeUnhealthy` / `markRuntimeHealthy`.
*/
export async function detectRuntimes(): Promise<RuntimeInfo[]> {
const ids = listRuntimeIds();
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index 08d00a7c6..11e2e49a5 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -190,7 +190,7 @@ export class AgentRouter {
* Mutable per-runtime health map. Seeded from the startup snapshot passed
* on construction; mutated live by `markRuntimeUnhealthy` / `markRuntimeHealthy`
* so the router owns the single source of truth for /community's picker
- * gating. See plans/community-machine-presence-fix.md.
+ * gating.
*
* Insertion order preserves the runtime ordering the daemon reported at
* startup — Map iterates in insertion order — so the ready frame lists
@@ -473,8 +473,7 @@ export class AgentRouter {
// Capture pre-transition FSM status + tracker state BEFORE
// register/deliver so we can decide whether the FSM's
// `onAgentActivity` callback owns the first typing frame or this
- // router does — see "First-ever wake ordering" in
- // plans/bot-typing-indicator.md. The FSM path OWNS the first frame
+ // router does. The FSM path OWNS the first frame
// whenever a transition into a running-family state fires; the
// router emits only on a true mid-turn wake (`beforeStatus ===
// "running"` AND `wasActive`) where no FSM edge would leave the
@@ -504,8 +503,7 @@ export class AgentRouter {
seq: cmd.unreadNotice.latestSeq,
text,
});
- // Honest-ack diagnostic (plans/daemon-fsm-desync.md batch B, narrowed
- // in batch A): a wake that produced NO executable effect was only
+ // Honest-ack diagnostic: a wake that produced NO executable effect was only
// coalesced into the inbox. Coalescing is BENIGN and routine for the
// queue-and-drain states (starting/stopping/reset-window/per-turn) —
// logging those is just noise on a busy-spawning agent. The
@@ -614,7 +612,7 @@ export class AgentRouter {
// one failure never aborts the rest of the batch. Sequential await keeps
// the restart orchestration (stop→forget→respawn) from interleaving
// across agents. One frame, not fan-out (owner-triggered "reset this
- // machine"). See plans/daemon-batch-reset.md.
+ // machine").
for (const r of cmd.resets) {
await this.runRestartCommand(r.agentId, r.launchId, "agent:reset", () =>
this.opts.manager.resetSession(r.agentId, {
diff --git a/src/daemon/src/manager/managerPolicy.test.ts b/src/daemon/src/manager/managerPolicy.test.ts
index ba83b7396..d52d2887c 100644
--- a/src/daemon/src/manager/managerPolicy.test.ts
+++ b/src/daemon/src/manager/managerPolicy.test.ts
@@ -868,7 +868,7 @@ describe("reduceManager — tick: stall + idle hibernation", () => {
});
});
-// Batch A (plans/daemon-fsm-desync.md): the suspected-deaf detector catches the
+// The suspected-deaf detector catches the
// gated-no-further-turn_end permanent orphan that slips BOTH existing tick
// predicates. Reproduces Olivia's wedge: a gated agent turn-ends idle, a later
// wake drain-sends (stamping lastDeliverAt, re-arming turnActive), then the
@@ -948,8 +948,8 @@ describe("reduceManager — admission timeout", () => {
});
});
-// Batch D (plans/daemon-fsm-desync.md): the reset-stuck reconcile. The reset
-// window (`resetting`) closes only via `enterStable` at a stable running/idle
+// The reset-stuck reconciliation closes the reset window (`resetting`) only
+// via `enterStable` at a stable running/idle
// state; if the converging event never arrives the agent wedges in `starting`
// with `resetting` stuck true — invisible to the three running-keyed onTick
// predicates. This watchdog is the ONLY thing that catches it.
@@ -1033,7 +1033,7 @@ describe("reduceManager — tick: reset-stuck reconcile (batch D)", () => {
});
});
-// Batch L3 (plans/daemon-fsm-desync.md): the stopping-wedge black hole. A
+// The stopping-wedge guard covers the case where a
// stop/terminate set status=stopping expecting an `exit` that never arrived
// (no-op stop / kill didn't take). No other predicate keys on `stopping`, and
// onWake only queues there → permanent wedge (observed live: Olivia 2026-07-31,
diff --git a/src/daemon/src/manager/managerRuntime.test.ts b/src/daemon/src/manager/managerRuntime.test.ts
index 01f7be7fb..3eb59ee8e 100644
--- a/src/daemon/src/manager/managerRuntime.test.ts
+++ b/src/daemon/src/manager/managerRuntime.test.ts
@@ -1790,7 +1790,7 @@ describe("AgentProcessManager — launchId threading", () => {
// `baseContextFor` returned (almost always undefined, since no host wires
// it there) instead of the launchId tracked from the latest agent:wake —
// every real spawn's voucher silently collided on cliTransport's "default"
- // fallback path (see plans/fix-credential-proxy-connection-leak.md).
+ // fallback path, causing unrelated launches to share one credential proxy.
it("passes the latest agent:wake's launchId into the spawned driver's LaunchContext", async () => {
let capturedCtx: LaunchContext | undefined;
const factory: SessionFactory = (hooks) => {
@@ -3703,7 +3703,7 @@ describe("onBotAuditEvent — integration through onRuntimeEvent (T9/T10)", () =
});
});
-// FSM transition trace (plans/daemon-fsm-desync.md): pure-observability hook
+// FSM transition trace: pure-observability hook
// used to make a wedge that logs nothing else reconstructable. Two guarantees:
// it fires per dispatch with the fields the wedge-triage needs, and it does NOT
// change behavior (effects identical whether or not the hook is wired).
@@ -3895,7 +3895,7 @@ describe("AgentProcessManager — onFsmTransition trace (observability, zero beh
}
});
- // ---- B1: crashed-turn tag (plans/daemon-runtime-error-rewake.md) ----------
+ // ---- B1: crashed-turn tag -----------------------------------------------
// The trailing turn_end after a mid-turn `error` carries `endReason:"errored"`
// + `errorDetail` into the trace, so a crashed turn is externally
// distinguishable from a clean nap/idle (red line 7). B1 only RECORDS it —
diff --git a/src/daemon/src/runtimeConfig.ts b/src/daemon/src/runtimeConfig.ts
index cef606c1a..d940fddb9 100644
--- a/src/daemon/src/runtimeConfig.ts
+++ b/src/daemon/src/runtimeConfig.ts
@@ -5,8 +5,7 @@
* `@alook/shared/runtime-config` (lifted there so the `src/web` wake producer
* and `src/queue-worker` consumer, neither of which can depend on this
* CLI/daemon package, can construct the `config` field of an `agent:wake`
- * `HostCommand` — see `plans/community-agent-cli-bridge.md` §1 and
- * `plans/minimal-wake-queue-unread-notice.md`). Re-exported here so existing
+ * `HostCommand`. Re-exported here so existing
* daemon call sites keep importing from `./runtimeConfig.js` unchanged.
*
* The daemon only translates the shared wire shape into the public agent-driver
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index b9f0c838e..e748aaa19 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -4,8 +4,7 @@
* This file is now a thin re-export shim. The canonical definitions live in
* `@alook/shared`'s `community-cli-contract.ts` (lifted there so the real
* server routes and the wake producer/consumer can share the exact same
- * types this CLI/production server pair implements against — see
- * `plans/community-agent-cli-bridge.md` §1). Keep importing from
+ * types this CLI/production server pair implements against. Keep importing from
* `./contract.js` at existing daemon call sites; nothing else changes.
*/
export type {
diff --git a/src/daemon/src/util/rotatingFileSink.ts b/src/daemon/src/util/rotatingFileSink.ts
index 55e2f996b..ad2ed3aea 100644
--- a/src/daemon/src/util/rotatingFileSink.ts
+++ b/src/daemon/src/util/rotatingFileSink.ts
@@ -1,6 +1,6 @@
/**
* A tiny size-capped, rotating append sink — the bounded backing for the
- * default-on FSM transition trace (plans/daemon-fsm-desync.md batch E1).
+ * default-on FSM transition trace.
*
* WHY net-new: the daemon has no rotation utility (recon-confirmed), and the
* raw `appendFileSync` sink the trace shipped with (createDaemon.ts) is
diff --git a/src/daemon/src/util/statusFile.ts b/src/daemon/src/util/statusFile.ts
index 6a1ef0089..3ebfecdc3 100644
--- a/src/daemon/src/util/statusFile.ts
+++ b/src/daemon/src/util/statusFile.ts
@@ -9,7 +9,7 @@
* `<baseDir>/status.json`, which multiple daemons clobbered) and the
* `daemon status` CLI reads that file (Cecilia's ruling (a): snapshot-file,
* not a control listener — zero new network/attack surface, crash-safe: if the
- * daemon dies the last frame is still readable). See plans/daemon-fsm-desync.md.
+ * daemon dies the last frame is still readable).
*
* ATOMIC: write to `<path>.tmp` then `rename` over `<path>`, so a concurrent
* `daemon status` read never sees a half-written file (rename is atomic on the
diff --git a/src/daemon/src/util/traceSampler.test.ts b/src/daemon/src/util/traceSampler.test.ts
index 1c836915f..6a5173794 100644
--- a/src/daemon/src/util/traceSampler.test.ts
+++ b/src/daemon/src/util/traceSampler.test.ts
@@ -3,7 +3,7 @@ import { createTraceSampler, DEFAULT_TRACE_SAMPLE_MS } from "./traceSampler.js";
import * as traceSamplerModule from "./traceSampler.js";
/*
- * T4 (plans/daemon-trace-completeness-charter.md) — heartbeat sampler.
+ * Heartbeat-sampler trace completeness.
* Two acceptance conditions (Claudette 架构#421):
* ① retention: folding the unchanged-tick / progress / runtime_signal noise
* bounds each agent's sampleable streams; the B1 fleet-budget test below
diff --git a/src/daemon/src/util/traceSampler.ts b/src/daemon/src/util/traceSampler.ts
index 8026e185a..00bb2f166 100644
--- a/src/daemon/src/util/traceSampler.ts
+++ b/src/daemon/src/util/traceSampler.ts
@@ -1,7 +1,6 @@
/**
* FSM-trace sampler — heartbeat throttling so the bounded trace retains a
- * useful HISTORY WINDOW instead of being flushed by routine noise
- * (plans/daemon-trace-completeness-charter.md T4).
+ * useful HISTORY WINDOW instead of being flushed by routine noise.
*
* WHY: the default trace is capped at 32 MiB per generation (64 MiB for active
* + `.1`, rotatingFileSink). At the executable N=8 operational envelope, the
diff --git a/src/queue-worker/src/index.ts b/src/queue-worker/src/index.ts
index eb0ef6365..e6642a064 100644
--- a/src/queue-worker/src/index.ts
+++ b/src/queue-worker/src/index.ts
@@ -104,8 +104,8 @@ export default {
/**
* Dev-only HTTP stand-in for the local Cloudflare Queue. Local Queues
- * simulation cannot bridge separate `wrangler dev`/`next dev` processes
- * (plans/minimal-wake-queue-unread-notice.md), so `src/web`'s
+ * simulation cannot bridge separate `wrangler dev`/`next dev` processes,
+ * so `src/web`'s
* `queue-transport.ts` calls this route (via the `QUEUE_WORKER` service
* binding, `NODE_ENV === "development"` only) instead of
* `TASK_QUEUE.sendBatch(...)`. Body is a JSON array of accepted legacy or
diff --git a/src/shared/src/community-attention.test.ts b/src/shared/src/community-attention.test.ts
new file mode 100644
index 000000000..710e3a5fe
--- /dev/null
+++ b/src/shared/src/community-attention.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest"
+import {
+ AccountAttentionSnapshotSchema,
+ AttentionItemSchema,
+} from "./community-attention"
+
+const scope = {
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 7,
+ lastAttentionSeq: 7,
+ attentionCount: 1,
+}
+
+const item = {
+ id: "mention:a1",
+ kind: "mention" as const,
+ sourceId: "a1",
+ scopeId: "c1",
+ messageId: "m7",
+ actorUserId: "u2",
+ createdAt: "2026-09-27T00:00:00.000Z",
+}
+
+describe("account attention wire schemas", () => {
+ it("rejects invalid attention-item reference shapes", () => {
+ expect(AttentionItemSchema.safeParse({
+ ...item,
+ kind: "friend_request",
+ }).success).toBe(false)
+ expect(AttentionItemSchema.safeParse({
+ ...item,
+ scopeId: null,
+ messageId: null,
+ }).success).toBe(false)
+ })
+
+ it("accepts ref-only snapshots and the existing reply kind", () => {
+ expect(AccountAttentionSnapshotSchema.parse({
+ scopes: [scope],
+ items: [item, { ...item, id: "mention:a2", sourceId: "a2", kind: "reply" }],
+ limit: 100,
+ truncated: false,
+ }).items).toHaveLength(2)
+ })
+
+ it("rejects display identity and message content inside fact rows", () => {
+ expect(AccountAttentionSnapshotSchema.safeParse({
+ scopes: [{ ...scope, channelName: "general" }],
+ items: [{ ...item, actorName: "Alice", content: "hello" }],
+ limit: 100,
+ truncated: false,
+ }).success).toBe(false)
+ })
+
+ it("rejects duplicate ids and dangling scope references", () => {
+ expect(AccountAttentionSnapshotSchema.safeParse({
+ scopes: [scope, scope],
+ items: [item, item],
+ limit: 100,
+ truncated: false,
+ }).success).toBe(false)
+ expect(AccountAttentionSnapshotSchema.safeParse({
+ scopes: [],
+ items: [item],
+ limit: 100,
+ truncated: false,
+ }).success).toBe(false)
+ })
+})
diff --git a/src/shared/src/community-attention.ts b/src/shared/src/community-attention.ts
new file mode 100644
index 000000000..e4a538fa8
--- /dev/null
+++ b/src/shared/src/community-attention.ts
@@ -0,0 +1,69 @@
+import { z } from "zod"
+
+const id = z.string().min(1)
+
+export const AttentionScopeSchema = z.strictObject({
+ scopeId: id,
+ channelId: id,
+ serverId: id.nullable().optional(),
+ parentChannelId: id.nullable().optional(),
+ ordinaryUnread: z.boolean(),
+ lastUnreadSeq: z.number().int().nonnegative(),
+ lastAttentionSeq: z.number().int().nonnegative().nullable().optional(),
+ attentionCount: z.number().int().nonnegative(),
+})
+
+export const AttentionItemSchema = z.strictObject({
+ id,
+ kind: z.enum(["mention", "reply", "friend_request"]),
+ sourceId: id,
+ scopeId: id.nullable().optional(),
+ messageId: id.nullable().optional(),
+ actorUserId: id,
+ createdAt: z.string(),
+}).superRefine((item, ctx) => {
+ if (item.kind === "friend_request") {
+ if (item.scopeId != null || item.messageId != null) {
+ ctx.addIssue({ code: "custom", message: "friend request cannot reference a scope or message" })
+ }
+ return
+ }
+ if (!item.scopeId || !item.messageId) {
+ ctx.addIssue({ code: "custom", message: "message attention requires scope and message refs" })
+ }
+})
+
+export const AttentionIncludedSchema = z.strictObject({
+ profiles: z.array(z.unknown()).optional(),
+ messages: z.array(z.unknown()).optional(),
+})
+
+export const AccountAttentionSnapshotSchema = z.strictObject({
+ scopes: z.array(AttentionScopeSchema),
+ items: z.array(AttentionItemSchema),
+ limit: z.number().int().positive(),
+ truncated: z.boolean(),
+ included: AttentionIncludedSchema.optional(),
+}).superRefine((snapshot, ctx) => {
+ const scopeIds = new Set<string>()
+ for (const scope of snapshot.scopes) {
+ if (scopeIds.has(scope.scopeId)) {
+ ctx.addIssue({ code: "custom", message: `duplicate attention scope: ${scope.scopeId}` })
+ }
+ scopeIds.add(scope.scopeId)
+ }
+ const itemIds = new Set<string>()
+ for (const item of snapshot.items) {
+ if (itemIds.has(item.id)) {
+ ctx.addIssue({ code: "custom", message: `duplicate attention item: ${item.id}` })
+ }
+ itemIds.add(item.id)
+ if (item.scopeId && !scopeIds.has(item.scopeId)) {
+ ctx.addIssue({ code: "custom", message: `attention item references missing scope: ${item.scopeId}` })
+ }
+ }
+})
+
+export type AttentionScope = z.infer<typeof AttentionScopeSchema>
+export type AttentionItem = z.infer<typeof AttentionItemSchema>
+export type AccountAttentionSnapshot = z.infer<typeof AccountAttentionSnapshotSchema>
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 673a69103..c5ba68e90 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -847,7 +847,7 @@ export type HostCommand =
* the reconnect transient + closes the pre-existing "register+spawn any
* agentId" hole). Routed by machineId to the single daemon that owns it (one
* live credential per machineId). See the `machine:reset_all` case in
- * `agentRouter` and plans/daemon-batch-reset.md.
+ * `agentRouter`.
*/
| { type: "machine:reset_all"; resets: Array<{ agentId: AgentId; config: RuntimeConfig; launchId: string }> }
| { type: "machine:update" }
@@ -981,7 +981,7 @@ export type BotAuditEventPayload =
// the daemon only after its local six-hour reset barrier commits. `trigger`
// distinguishes the entry-point so my-bots can read "was reset" vs "slept";
// `actorId` never travels — it is the bot owner, resolved server-side at the
- // landing (reset is owner-only). See plans/reset-nap-completion-rehome.md.
+ // landing because reset is owner-only.
| { kind: "session_reset"; payload: { trigger: "single" | "reset_all" | "idle_timeout" } }
| { kind: "nap"; payload: { trigger: "nap" } };
@@ -1463,7 +1463,7 @@ export function formatSeq(seq: Seq): string {
// (drizzle, queries) into the daemon bundle. The lockstep guard below also only
// compiles here, where the `HostCommand` type is in scope.
//
-// SHALLOW by design (CTO ruling — plans/daemon-downlink-zod.md): validate the
+// SHALLOW by design: validate the
// discriminant `type` + each arm's REQUIRED top-level scalars, and enumerate
// EVERY top-level field per arm (including optional load-bearing ones like
// `wake.sessionId`) so zod's default strip drops nothing real. The nested typed
diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.ts
index 0b521fb5c..669b6cd1f 100644
--- a/src/shared/src/community/wake-dispatch.ts
+++ b/src/shared/src/community/wake-dispatch.ts
@@ -232,8 +232,7 @@ export async function buildUnreadWakeCommand(
// Audit trail (best-effort) — commit that this wake fired for a specific
// trigger message. MUST NOT block or fail the wake: on retry (D1 blip) a
- // second row is preferable to a silently-lost wake. See "Audit write
- // failure policy" in plans/agent-unread-visibility-unify.md.
+ // second row is preferable to a silently lost wake.
try {
await writeWakeTriggerAudit(db, env, {
botUserId: input.botUserId,
diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.ts
index 00e489b75..bf5920907 100644
--- a/src/shared/src/db/community-machine-schema.ts
+++ b/src/shared/src/db/community-machine-schema.ts
@@ -195,7 +195,7 @@ export const communityMachine = sqliteTable(
.default([]),
// status is the source of truth for machine presence — written by the
// WsDurableObject on accept / webSocketClose / alarm. Not derived from
- // last_seen_at anymore (see plans/community-machine-presence-fix.md).
+ // last_seen_at anymore.
status: text("status").notNull().default("offline"),
lastSeenAt: text("last_seen_at"),
createdAt: text("created_at")
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index d28f5017c..787758d4f 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -196,8 +196,8 @@ export const communityMessage = sqliteTable(
);
// 6. community_message_seq — atomic per-channel sequence counter.
-// See plans/community-agent-cli-bridge.md design §3. `nextSeq` holds the most
-// recently issued value (not "the next value to hand out" despite the name).
+// `nextSeq` holds the most recently issued value, not "the next value to hand
+// out" despite the name.
// Because DMs are channels now, the PK is the channel id directly.
export const communityMessageSeq = sqliteTable("community_message_seq", {
channelId: text("channel_id")
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 32709bc23..82c7cd49c 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -61,6 +61,7 @@ export * as communityNotificationTarget from "./queries/community/notification-t
export * as communityServerFolder from "./queries/community/server-folder";
export * as communityServerRail from "./queries/community/server-rail";
export * as communityInbox from "./queries/community/inbox";
+export * as communityAttention from "./queries/community/attention";
export * as communityMachine from "./queries/community/machine";
export * as communityMachineSession from "./queries/community/machine-session-epoch";
export * as communityBot from "./queries/community/bot";
diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.ts
index 0b8f401a1..6f4c2eaae 100644
--- a/src/shared/src/db/queries/community/agent-inbox.ts
+++ b/src/shared/src/db/queries/community/agent-inbox.ts
@@ -280,7 +280,7 @@ export async function toAgentMessages(
if (!scope) throw new Error("Channel identity unavailable");
const channel = scope.ref;
const author = userById.get(r.authorId);
- const sender = author ? `@${formatHandle(author.name, author.discriminator)}` : "Unknown user";
+ const sender = author ? `@${formatHandle(author.name, author.discriminator)}` : "Deleted user";
// Absent (not empty array) when a message has no attachments — smaller
// wire payload; documented invariant in the plan.
const atts = attachmentsByMessageId?.get(r.id);
@@ -897,7 +897,7 @@ export async function getInboxSnapshotForAgent(
pendingCount: r.pendingCount,
firstPendingSeq: r.firstPendingSeq,
latestSeq: r.latestSeq,
- latestSender: sender ? `@${formatHandle(sender.name, sender.discriminator)}` : "Unknown user",
+ latestSender: sender ? `@${formatHandle(sender.name, sender.discriminator)}` : "Deleted user",
hasMention: r.mentionCount > 0,
};
});
diff --git a/src/shared/src/db/queries/community/attention.test.ts b/src/shared/src/db/queries/community/attention.test.ts
new file mode 100644
index 000000000..9ac03996b
--- /dev/null
+++ b/src/shared/src/db/queries/community/attention.test.ts
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ listVisibleChannelIdsForUser: vi.fn(),
+ listEligibleUnreadChannels: vi.fn(),
+ listEligibleUnreadDms: vi.fn(),
+ listActionableIncomingRequests: vi.fn(),
+ listUnreadMentionScopes: vi.fn(),
+ listUnreadMentions: vi.fn(),
+}))
+
+vi.mock("./channel", () => ({ listVisibleChannelIdsForUser: mocks.listVisibleChannelIdsForUser }))
+vi.mock("./inbox", () => ({
+ listEligibleUnreadChannels: mocks.listEligibleUnreadChannels,
+ listEligibleUnreadDms: mocks.listEligibleUnreadDms,
+}))
+vi.mock("./friendship", () => ({
+ listActionableIncomingRequests: mocks.listActionableIncomingRequests,
+}))
+vi.mock("./mention", () => ({
+ listUnreadMentionScopes: mocks.listUnreadMentionScopes,
+ listUnreadMentions: mocks.listUnreadMentions,
+}))
+
+import { DEFAULT_ATTENTION_ITEM_LIMIT, getAccountAttentionSnapshot } from "./attention"
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.listVisibleChannelIdsForUser.mockResolvedValue([])
+ mocks.listEligibleUnreadChannels.mockResolvedValue([])
+ mocks.listEligibleUnreadDms.mockResolvedValue([{ channelId: "dm_1", lastUnreadSeq: 4 }])
+ mocks.listActionableIncomingRequests.mockResolvedValue([])
+ mocks.listUnreadMentionScopes.mockResolvedValue([])
+ mocks.listUnreadMentions.mockResolvedValue([])
+})
+
+describe("getAccountAttentionSnapshot", () => {
+ it("uses the default limit and projects ordinary DM unread scopes", async () => {
+ const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")
+
+ expect(snapshot.limit).toBe(DEFAULT_ATTENTION_ITEM_LIMIT)
+ expect(snapshot.scopes).toEqual([{
+ scopeId: "dm_1",
+ channelId: "dm_1",
+ serverId: null,
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }])
+ })
+})
diff --git a/src/shared/src/db/queries/community/attention.ts b/src/shared/src/db/queries/community/attention.ts
new file mode 100644
index 000000000..c0ad79bcb
--- /dev/null
+++ b/src/shared/src/db/queries/community/attention.ts
@@ -0,0 +1,154 @@
+import type {
+ AccountAttentionSnapshot,
+ AttentionItem,
+ AttentionScope,
+} from "../../../community-attention"
+import type { Database } from "../../index"
+import { listVisibleChannelIdsForUser } from "./channel"
+import { listEligibleUnreadChannels, listEligibleUnreadDms } from "./inbox"
+import { listUnreadMentions, listUnreadMentionScopes } from "./mention"
+import { listActionableIncomingRequests } from "./friendship"
+
+export const DEFAULT_ATTENTION_ITEM_LIMIT = 100
+export const MAX_ATTENTION_ITEM_LIMIT = 200
+
+/**
+ * Stateless account-attention projection over the existing inbox facts.
+ * The item cap applies only to mention/reply rows; actionable friend requests
+ * stay complete so every consumer can derive an exact badge from this result.
+ */
+export async function getAccountAttentionSnapshot(
+ db: Database,
+ userId: string,
+ requestedLimit = DEFAULT_ATTENTION_ITEM_LIMIT,
+): Promise<AccountAttentionSnapshot> {
+ const limit = Math.max(1, Math.min(requestedLimit, MAX_ATTENTION_ITEM_LIMIT))
+ const visibleChannelIds = await listVisibleChannelIdsForUser(db, userId)
+ const [channelRows, dmRows, friendRows, mentionScopeRows, allMentionRows] = await Promise.all([
+ listEligibleUnreadChannels(db, userId, visibleChannelIds),
+ listEligibleUnreadDms(db, userId),
+ listActionableIncomingRequests(db, userId),
+ listUnreadMentionScopes(db, userId, visibleChannelIds),
+ listUnreadMentions(db, userId, {
+ limit: limit + 1,
+ visibleChannelIds,
+ }),
+ ])
+
+ const attentionByScope = new Map(mentionScopeRows.map((row) => [row.channelId, row]))
+ const scopesById = new Map<string, AttentionScope>()
+ for (const row of channelRows) {
+ const attention = attentionByScope.get(row.channelId)
+ scopesById.set(row.channelId, {
+ scopeId: row.channelId,
+ channelId: row.channelId,
+ serverId: row.serverId,
+ parentChannelId: row.parentChannelId,
+ ordinaryUnread: true,
+ lastUnreadSeq: row.lastUnreadSeq,
+ lastAttentionSeq: attention?.lastAttentionSeq ?? null,
+ attentionCount: attention?.attentionCount ?? 0,
+ })
+ }
+ for (const row of dmRows) {
+ scopesById.set(row.channelId, {
+ scopeId: row.channelId,
+ channelId: row.channelId,
+ serverId: null,
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: row.lastUnreadSeq,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ })
+ }
+ for (const row of mentionScopeRows) {
+ if (scopesById.has(row.channelId)) continue
+ scopesById.set(row.channelId, {
+ scopeId: row.channelId,
+ channelId: row.channelId,
+ serverId: row.serverId,
+ parentChannelId: row.parentChannelId,
+ ordinaryUnread: false,
+ lastUnreadSeq: row.lastAttentionSeq,
+ lastAttentionSeq: row.lastAttentionSeq,
+ attentionCount: row.attentionCount,
+ })
+ }
+ const scopes = [...scopesById.values()]
+
+ // The aggregate and bounded item reads are independent primary statements.
+ // A mention may be created/deleted between them, so fence the composed
+ // result against the aggregate-owned scope set before validating the wire
+ // snapshot. A reverse race may leave a scope with no item until reconcile,
+ // which remains schema-valid and preserves its exact aggregate count.
+ const eligibleMentionRows = allMentionRows.filter((row) => (
+ Boolean(row.message.channelId && scopesById.has(row.message.channelId))
+ ))
+ const displayedMentionRows = eligibleMentionRows.slice(0, limit)
+ const exactMentionCount = mentionScopeRows.reduce(
+ (total, row) => total + row.attentionCount,
+ 0,
+ )
+ const mentionItems: AttentionItem[] = displayedMentionRows.map((row) => ({
+ id: `mention:${row.mention.id}`,
+ kind: row.mention.kind === "reply" ? "reply" : "mention",
+ sourceId: row.mention.id,
+ scopeId: row.message.channelId,
+ messageId: row.message.id,
+ actorUserId: row.author.id,
+ createdAt: row.message.createdAt,
+ }))
+ const friendItems: AttentionItem[] = friendRows.map((row) => ({
+ id: `friend_request:${row.id}`,
+ kind: "friend_request",
+ sourceId: row.id,
+ scopeId: null,
+ messageId: null,
+ actorUserId: row.userId,
+ createdAt: row.createdAt,
+ }))
+ const items = [...mentionItems, ...friendItems]
+ .sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id))
+
+ const includedProfiles = new Map<string, Record<string, unknown>>()
+ for (const row of friendRows) {
+ includedProfiles.set(row.userId, {
+ userId: row.userId,
+ name: row.name,
+ discriminator: row.discriminator,
+ avatar: row.image ?? "",
+ avatarVersion: row.avatarVersion,
+ })
+ }
+ for (const row of displayedMentionRows) {
+ includedProfiles.set(row.author.id, {
+ userId: row.author.id,
+ name: row.author.name,
+ discriminator: row.author.discriminator,
+ avatar: row.author.image ?? "",
+ avatarVersion: row.author.avatarVersion,
+ })
+ }
+ const includedMessages = displayedMentionRows.map((row) => ({
+ id: row.message.id,
+ channelId: row.message.channelId!,
+ type: row.message.type === "system" ? "system" : "chat",
+ authorId: row.author.id,
+ authorName: row.author.name,
+ seq: row.message.seq,
+ createdAt: row.message.createdAt,
+ content: row.message.content ?? "",
+ }))
+
+ return {
+ scopes,
+ items,
+ limit,
+ truncated: exactMentionCount > limit,
+ included: {
+ profiles: [...includedProfiles.values()],
+ messages: includedMessages,
+ },
+ }
+}
diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.ts
index 4ce354986..9c0e09ae4 100644
--- a/src/shared/src/db/queries/community/bot-audit-log.ts
+++ b/src/shared/src/db/queries/community/bot-audit-log.ts
@@ -276,8 +276,7 @@ export async function insertBotAuditSessionReset(
* `"nap"` so my-bots reads "slept" vs a "was reset". Written when the reborn
* agent's `agent_session` lands (completion), NOT at dispatch — so a nap that
* dispatches but whose cold-start fails writes no row (the DO evicts the
- * pending map entry on the failure frame instead). See
- * plans/reset-nap-completion-rehome.md.
+ * pending map entry on the failure frame instead).
*/
export async function insertBotAuditNap(
db: Database,
diff --git a/src/shared/src/db/queries/community/category.ts b/src/shared/src/db/queries/community/category.ts
index 322902720..b51035239 100644
--- a/src/shared/src/db/queries/community/category.ts
+++ b/src/shared/src/db/queries/community/category.ts
@@ -82,8 +82,7 @@ export async function deleteCategory(db: Database, categoryId: string) {
/**
* Whether a category still contains any channel. Gates the private/public
* toggle and category delete (both blocked when non-empty to prevent a
- * privacy-class flip / `set null` widening). See
- * plans/channel-category-role-permissions.md.
+ * privacy-class flip / `set null` widening).
*/
export async function hasChannels(db: Database, categoryId: string): Promise<boolean> {
const rows = await db
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index 6f2902f89..f63436c72 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -586,8 +586,7 @@ export async function getDirectChildThreadsByIds(
}
// ---------------------------------------------------------------------------
-// Private-channel membership + visibility
-// (plans/channel-category-role-permissions.md)
+// Private-channel membership and visibility.
// ---------------------------------------------------------------------------
/**
@@ -1004,16 +1003,25 @@ export type ChannelRefDirectoryRow = {
serverId: string;
channelId: string;
channelName: string;
+ channelType: "text" | "forum";
};
export function groupChannelRefDirectoryRows(
servers: Array<{ id: string; name: string; discriminator: string }>,
channels: ChannelRefDirectoryRow[]
) {
- const channelsByServer = new Map<string, Array<{ id: string; name: string }>>();
+ const channelsByServer = new Map<string, Array<{
+ id: string;
+ name: string;
+ type: "text" | "forum";
+ }>>();
for (const channel of channels) {
const current = channelsByServer.get(channel.serverId) ?? [];
- current.push({ id: channel.channelId, name: channel.channelName });
+ current.push({
+ id: channel.channelId,
+ name: channel.channelName,
+ type: channel.channelType,
+ });
channelsByServer.set(channel.serverId, current);
}
return servers.map((server) => ({
@@ -1046,6 +1054,7 @@ export async function listChannelRefDirectoryForUser(db: Database, userId: strin
serverId: communityChannel.serverId,
channelId: communityChannel.id,
channelName: communityChannel.name,
+ channelType: communityChannel.type,
})
.from(communityChannel)
.innerJoin(
diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.ts
index 1d50111eb..9544a0f3e 100644
--- a/src/shared/src/db/queries/community/friendship.ts
+++ b/src/shared/src/db/queries/community/friendship.ts
@@ -283,7 +283,7 @@ export type SendRequestOutcome =
/**
* Send a friend request — the single entry point for the human route AND the
* agent route. Supersede-before-write lives here so every caller gets it
- * uniformly. See plans/agent-friendship-approval-gate.md §sendRequest.
+ * uniformly.
*
* Throws `Error("blocked")` if a blocked row exists between the pair.
* Throws `Error("already friends")` / `Error("friend request already sent")`
@@ -777,7 +777,7 @@ export async function listFriends(db: Database, userId: string) {
* these rows here (to match `listFriends`' "no join" cost-saving, not
* realizing that trimmed the whole reason a bot's owner needs to be in this
* list) — that's what caused a bot's owner to never learn about its own
- * presence, see plans/community-account-debt-fixes.md Fix 3 hotfix.
+ * presence.
*/
export async function getFriendUserIds(db: Database, userId: string): Promise<string[]> {
const [rows, selfBotRows] = await Promise.all([
@@ -960,7 +960,7 @@ export async function listBlocked(db: Database, userId: string) {
* The friend page's pending buckets for a human viewer. Direction-aware, one
* row shape everywhere (no `source` tag). Every row carries
* `needsOwnerApproval` so the UI can branch (actionable vs "Waiting on <owner>"
- * chip). See plans/agent-friendship-approval-gate.md §Read model.
+ * chip).
*
* - incoming: act-on-me rows — `addresseeId=viewer AND status=pending AND
* needsOwnerApproval IS NULL`. A bot→human request only surfaces here once
@@ -1054,6 +1054,7 @@ export async function listActionableIncomingRequests(db: Database, userId: strin
id: communityFriendship.id,
userId: user.id,
name: user.name,
+ discriminator: user.discriminator,
image: user.image,
avatarVersion: user.avatarVersion,
createdAt: communityFriendship.createdAt,
@@ -1078,8 +1079,7 @@ export type OwnerDecisionResult =
/**
* The bot owner approves or denies a gated friendship row via a DM card.
- * One function, all four cases (deny + three approve sub-cases). See
- * plans/agent-friendship-approval-gate.md §ownerDecideOnRow.
+ * One function owns all four cases: deny plus the three approval sub-cases.
*
* Auth: `actorId` must equal the row's current `needsOwnerApproval` (else
* forbidden). Compare-and-set on `status='pending' AND needsOwnerApproval=?`
@@ -1312,7 +1312,7 @@ export type EnsureSiblingResult =
/**
* Direction-agnostic, idempotent accepted-friendship between two sibling bots
- * (same owner). See plans/agent-friendship-approval-gate.md §ensureSiblingBotFriendship.
+ * that share one owner.
*
* Precondition (programmer-error guard, throws): both users are bots sharing an
* owner. Then: SELECT any existing row; blocked → sentinel; accepted → return
diff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.ts
index df123f88b..fe8a0b85f 100644
--- a/src/shared/src/db/queries/community/machine.ts
+++ b/src/shared/src/db/queries/community/machine.ts
@@ -290,7 +290,7 @@ export async function listMachineBackendQuotasForUser(
}
// ---------------------------------------------------------------------------
-// Bot activity telemetry — see plans/community-bot-status-telemetry.md.
+// Bot activity telemetry.
//
// Bot activity is stored on `community_user_profile.status_emoji`/`status_text`,
// the same fields humans set via `StatusEditor`. This is deliberate: consumers
@@ -597,8 +597,7 @@ export async function revokeRunnerKeysForMachine(
* atomically with the user-flag and member-row updates.
*
* Uses a subquery on `user.ownerUserId` rather than a plain `agentId = :id`
- * predicate — the batch must be a no-op against a cross-owner bot id, per
- * §Ownership scoping invariant in plans/community-bots.md.
+ * predicate: the batch must be a no-op against a cross-owner bot id.
*/
export function revokeRunnerKeysForAgentStatement(
db: Database,
diff --git a/src/shared/src/db/queries/community/mention.test.ts b/src/shared/src/db/queries/community/mention.test.ts
new file mode 100644
index 000000000..71ac2fc51
--- /dev/null
+++ b/src/shared/src/db/queries/community/mention.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it, vi } from "vitest"
+import { listUnreadMentionScopes } from "./mention"
+
+describe("listUnreadMentionScopes", () => {
+ it("short-circuits an empty visibility scope and queries a non-empty scope", async () => {
+ const rows = [{
+ channelId: "channel_1",
+ serverId: "server_1",
+ parentChannelId: null,
+ attentionCount: 2,
+ lastAttentionSeq: 8,
+ }]
+ const chain: Record<string, ReturnType<typeof vi.fn>> = {}
+ chain.from = vi.fn(() => chain)
+ chain.innerJoin = vi.fn(() => chain)
+ chain.where = vi.fn(() => chain)
+ chain.groupBy = vi.fn().mockResolvedValue(rows)
+ const db = { select: vi.fn(() => chain) }
+
+ await expect(listUnreadMentionScopes(db as never, "user_1", [])).resolves.toEqual([])
+ await expect(listUnreadMentionScopes(db as never, "user_1", ["channel_1"])).resolves.toEqual(rows)
+ expect(db.select).toHaveBeenCalledOnce()
+ expect(chain.groupBy).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/shared/src/db/queries/community/mention.ts b/src/shared/src/db/queries/community/mention.ts
index 8416efc6f..0d25f3ded 100644
--- a/src/shared/src/db/queries/community/mention.ts
+++ b/src/shared/src/db/queries/community/mention.ts
@@ -1,5 +1,5 @@
import { eq, and, inArray, desc, exists, lte, sql, type SQL } from "drizzle-orm";
-import { communityMention, communityMessage } from "../../community-schema";
+import { communityChannel, communityMention, communityMessage } from "../../community-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
import { chunk, maxRowsPerInsert, D1_MAX_IN_PARAMS } from "../_chunk";
@@ -142,6 +142,43 @@ export async function listUnreadMentions(
return opts.limit !== undefined ? merged.slice(0, opts.limit) : merged;
}
+export async function listUnreadMentionScopes(
+ db: Database,
+ userId: string,
+ visibleChannelIds: string[],
+) {
+ if (visibleChannelIds.length === 0) return [];
+ return (
+ await Promise.all(
+ chunk(visibleChannelIds, D1_MAX_IN_PARAMS).map((ids) =>
+ db
+ .select({
+ channelId: communityChannel.id,
+ serverId: communityChannel.serverId,
+ parentChannelId: communityChannel.parentChannelId,
+ attentionCount: sql<number>`COUNT(*)`.mapWith(Number),
+ lastAttentionSeq: sql<number>`MAX(${communityMessage.seq})`.mapWith(Number),
+ })
+ .from(communityMention)
+ .innerJoin(
+ communityMessage,
+ eq(communityMention.messageId, communityMessage.id),
+ )
+ .innerJoin(
+ communityChannel,
+ eq(communityMessage.channelId, communityChannel.id),
+ )
+ .where(and(
+ eq(communityMention.userId, userId),
+ eq(communityMention.read, 0),
+ inArray(communityChannel.id, ids),
+ ))
+ .groupBy(communityChannel.id)
+ )
+ )
+ ).flat();
+}
+
export async function markAllMentionsRead(db: Database, userId: string) {
await db
.update(communityMention)
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 91f9bea6c..5bbe45e64 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -156,7 +156,7 @@ export type CreateMessageData = {
};
/**
- * `createMessage` overloads (plans/fix-agent-send-race-condition.md design §2):
+ * `createMessage` overloads:
* callers that never pass `expectedSeq` keep today's non-nullable return
* type — no pointless null-checks forced onto direct callers such as message
* send, bot provisioning, and friend request, which never opt into the CAS
@@ -717,7 +717,7 @@ export async function listMessages(
* and "jump to reply" flows. Returns the older half (strictly before the
* anchor, DESC) and the newer half (INCLUSIVE of the anchor, ASC) separately
* so the caller can encode `hasMoreOlder` / `hasMoreNewer` without re-deriving
- * boundary math. See plans/community-message-scroll-v2.md §A1.
+ * boundary math.
*
* The two halves are fetched in parallel (`Promise.all`) — they share no state
* beyond the anchor tuple. Each half fetches one extra row past the requested
@@ -816,7 +816,7 @@ export async function listMessagesAround(
/**
* Rows strictly newer than `since`, in chronological ASC order. Used by the
* client's cache-hydration and WS-reconnect catch-up flows to top-off a stale
- * cache without re-fetching everything. See plans/community-message-scroll-v2.md §A1.
+ * cache without re-fetching everything.
*
* Returns `limit + 1` rows when more exist; the caller trims to `limit` and
* sets `hasMoreNewer`.
@@ -881,7 +881,7 @@ export async function listRecentMessagesForDuplicateCheck(db: Database, channelI
* The largest `seq` value in a channel or DM scope, or `0` for an empty
* scope. Consumed by the message-list envelope so the client can compute
* `↓ N` (unread count vs. `latestSeq`) and drive `?since` catch-up without a
- * second round-trip. See plans/community-message-scroll-v2.md §A1.
+ * second round-trip.
*/
export async function getLatestMessageSeq(
db: Database,
diff --git a/src/shared/src/db/queries/community/server-folder.test.ts b/src/shared/src/db/queries/community/server-folder.test.ts
new file mode 100644
index 000000000..ea29ef1b1
--- /dev/null
+++ b/src/shared/src/db/queries/community/server-folder.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from "vitest"
+import { listFolders } from "./server-folder"
+
+describe("listFolders", () => {
+ it("keeps an unavailable server reference renderable", async () => {
+ const folderChain: Record<string, ReturnType<typeof vi.fn>> = {}
+ folderChain.from = vi.fn(() => folderChain)
+ folderChain.where = vi.fn(() => folderChain)
+ folderChain.orderBy = vi.fn().mockResolvedValue([{ id: "folder_1", name: "Saved", position: 0 }])
+
+ const itemChain: Record<string, ReturnType<typeof vi.fn>> = {}
+ itemChain.from = vi.fn(() => itemChain)
+ itemChain.leftJoin = vi.fn(() => itemChain)
+ itemChain.where = vi.fn(() => itemChain)
+ itemChain.orderBy = vi.fn().mockResolvedValue([{
+ serverId: "server_missing",
+ position: 0,
+ serverName: null,
+ serverIcon: null,
+ }])
+
+ const db = {
+ select: vi.fn()
+ .mockReturnValueOnce(folderChain)
+ .mockReturnValueOnce(itemChain),
+ }
+
+ await expect(listFolders(db as never, "user_1")).resolves.toEqual([{
+ id: "folder_1",
+ name: "Saved",
+ position: 0,
+ servers: [{ id: "server_missing", name: "Server unavailable", icon: null }],
+ }])
+ })
+})
diff --git a/src/shared/src/db/queries/community/server-folder.ts b/src/shared/src/db/queries/community/server-folder.ts
index 3272863a5..cb60962e4 100644
--- a/src/shared/src/db/queries/community/server-folder.ts
+++ b/src/shared/src/db/queries/community/server-folder.ts
@@ -157,7 +157,7 @@ export async function listFolders(db: Database, userId: string) {
position: folder.position ?? 0,
servers: items.map((item) => ({
id: item.serverId,
- name: item.serverName ?? "Unknown",
+ name: item.serverName ?? "Server unavailable",
icon: item.serverIcon ?? null,
})),
};
diff --git a/src/shared/src/db/resilience-testing.ts b/src/shared/src/db/resilience-testing.ts
index 30cd57ee0..f372856e4 100644
--- a/src/shared/src/db/resilience-testing.ts
+++ b/src/shared/src/db/resilience-testing.ts
@@ -21,8 +21,8 @@ export function makeD1Error(signature: ErrorSignature = "internal_error"): Drizz
* Test-fixture: returns an async fn that throws a DrizzleQueryError-shaped
* error for the first `n` invocations, then resolves with `value`.
*
- * Every integration test in `plans/d1-critical-path-resilience-v2.md` uses
- * this helper — DO NOT replace with `withD1Retry: vi.fn((fn) => fn())`
+ * Every D1 resilience integration test uses this helper; do not replace it
+ * with `withD1Retry: vi.fn((fn) => fn())`
* passthrough mocks. The passthrough pattern used by daemon-plane tests is
* fine there (they DON'T test retry semantics); this plan's new tests DO,
* so they need the real retry path, injected at the query-fn level.
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index e75c254b9..b91dfd8af 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -70,6 +70,7 @@ export type {
// Diagnostic report contract (neutral schemas/constants shared by HTTP, WS,
// daemon, and the D1 query layer).
export * from "./diagnostics-contract";
+export * from "./community-attention";
export { compareAsciiSqliteBinary } from "./lib/sqlite-binary";
export {
isUserWsConnectionPing,
diff --git a/src/shared/src/lib/community-name.ts b/src/shared/src/lib/community-name.ts
index 47ac01f7a..e4ec9ad87 100644
--- a/src/shared/src/lib/community-name.ts
+++ b/src/shared/src/lib/community-name.ts
@@ -5,8 +5,7 @@ import { MAX_PROFILE_NAME_LENGTH } from "../constants/community";
// trailing `#dddd` as an unambiguous terminator and everything before it as the
// name (spaces included), the name itself must never contain `#`, `@`, or a
// line break — any of those would let a name masquerade as (or break) the tag
-// grammar and resolve a mention to the wrong user. See
-// plans/mandatory-mention-discriminator.md.
+// grammar and resolve a mention to the wrong user.
//
// The forbidden set: `#`, `@`, and any C0/C1 control char (covers `\n`, `\r`,
// `\t`, DEL). Everything else — spaces, unicode letters, hyphens, underscores —
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 4bca81438..fe9610288 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1065,8 +1065,7 @@ export type AgentTypingStopMessage = z.infer<typeof AgentTypingStopMessageSchema
* launch that produced it. This is the completion signal the reset/nap
* audit+awake re-home hangs on: the DO correlates `launchId` back to the
* pending (launchId → trigger) map it recorded at dispatch, writes the audit +
- * awake stamp exactly once, then drops the map entry. See
- * plans/reset-nap-completion-rehome.md.
+ * awake stamp exactly once, then drops the map entry.
*/
export const AgentSessionMessageSchema = z.object({
type: z.literal("agent_session"),
@@ -1154,8 +1153,7 @@ export const CommunityDaemonEnrollAgentResponseSchema = z.object({
export type CommunityDaemonEnrollAgentResponse = z.infer<typeof CommunityDaemonEnrollAgentResponseSchema>;
// ---------------------------------------------------------------------------
-// Community bots — first-class community identities owned by users. See
-// plans/community-bots.md for the invariants.
+// Community bots are first-class community identities owned by users.
// ---------------------------------------------------------------------------
import {
@@ -1174,7 +1172,7 @@ const isMentionSafeName = (name: string): boolean => validateCommunityName(name)
const MENTION_SAFE_NAME_MSG = "name cannot contain #, @, or line breaks";
// Accepts an https URL, the exact bot-avatar route shape
-// (`/api/community/bots/{id}/avatar` — see plans/icon-range-selector.md), or
+// (`/api/community/bots/{id}/avatar`), or
// the in-house `avatar:` serialized config produced by `serializeAvatarConfig`
// in the web avatar picker. This gates client-supplied input on the plain
// create/patch endpoints, so it must NOT accept an arbitrary leading-`/`
@@ -1533,8 +1531,7 @@ export type AuditLogTurnInterruptPayload = z.infer<typeof AuditLogTurnInterruptP
* audit row is preferable to a silently-lost wake, so audit-before-delivery
* is the safer trade-off. Callers reading the audit log should treat rows as
* "we tried this" not "the daemon received this" — the daemon-facing
- * delivery is best-effort. See "Audit write failure policy" in
- * plans/agent-unread-visibility-unify.md. The `messageId` is the trigger;
+ * delivery is best-effort. The `messageId` is the trigger;
* `channel`/`seq` are denormalized for click-to-jump so the owner UI can
* render without a second D1 fetch. `senderHandle` is frozen at wake time
* (renaming after the fact does NOT rewrite past rows).
diff --git a/src/shared/src/utils/community-mentions.ts b/src/shared/src/utils/community-mentions.ts
index f79ae3dad..76923e6e4 100644
--- a/src/shared/src/utils/community-mentions.ts
+++ b/src/shared/src/utils/community-mentions.ts
@@ -3,7 +3,7 @@
* given a roster of candidate members. Only fully-tagged handles resolve — a
* hand-typed bare `@Name` (no discriminator) is NOT a mention, matching the
* display parser in `chat-syntax-plugin.ts` so the pill and the notification
- * fan-out never disagree (see plans/mandatory-mention-discriminator.md).
+ * fan-out never disagree.
*
* A handle match must:
* - be preceded by start-of-string or a non-identifier character
@@ -54,8 +54,7 @@ export function extractMentionedUserIds(
// Only exact `@Name#0042` handles resolve — the bare-name fallback was
// removed so the send side agrees with the display parser: a hand-typed bare
- // `@Alice` is NOT a mention on either surface (see
- // plans/mandatory-mention-discriminator.md). Handles are tried longest-first
+ // `@Alice` is NOT a mention on either surface. Handles are tried longest-first
// and built from ALL candidates (a handle is already unambiguous per user;
// two same-name "Alex"es both keep their distinct handle). A candidate with
// no discriminator can't be mentioned and is dropped here.
diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.ts
index e2b8d973e..99fefefe3 100644
--- a/src/shared/test/queries/community-agent-inbox.test.ts
+++ b/src/shared/test/queries/community-agent-inbox.test.ts
@@ -246,7 +246,7 @@ describe("toAgentMessages", () => {
[{ id: "srv_1", name: "studio", discriminator: "0042" }],
]);
const [msg] = await agentInbox.toAgentMessages(db, [rawMsg({ authorId: "u_ghost" })], "viewer_1");
- expect(msg!.sender).toBe("Unknown user");
+ expect(msg!.sender).toBe("Deleted user");
expect(JSON.stringify(msg)).not.toContain("u_ghost");
});
@@ -274,7 +274,7 @@ describe("toAgentMessages", () => {
expect(out.map((m) => m.seq)).toEqual(Array.from({ length: 101 }, (_, i) => `#${i + 1}`));
expect(out[0]).toMatchObject({ sender: "@User0#0000", content: { text: "body_0" } });
expect(out[100]).toMatchObject({
- sender: "Unknown user",
+ sender: "Deleted user",
content: { text: "body_100", attachments: [{ id: "att_1", filename: "proof.txt" }] },
});
expect(JSON.stringify(out)).not.toContain("u_100");
@@ -761,7 +761,7 @@ describe("getInboxSnapshotForAgent", () => {
expect(out.map((r) => r.channelId)).toEqual(channels.map((c) => c.id));
expect(out[0]).toMatchObject({ latestSender: "@Sender0#0000", pendingCount: 1, latestSeq: 3 });
expect(out[100]).toMatchObject({
- latestSender: "Unknown user", pendingCount: 101, firstPendingSeq: 102, latestSeq: 103,
+ latestSender: "Deleted user", pendingCount: 101, firstPendingSeq: 102, latestSeq: 103,
});
expect(JSON.stringify(out)).not.toContain("sender_100");
});
@@ -819,7 +819,7 @@ describe("getInboxSnapshotForAgent", () => {
pendingCount: 1,
firstPendingSeq: 9,
latestSeq: 9,
- latestSender: "Unknown user",
+ latestSender: "Deleted user",
hasMention: false,
},
]);
diff --git a/src/shared/test/queries/community-attention.test.ts b/src/shared/test/queries/community-attention.test.ts
new file mode 100644
index 000000000..0764b314a
--- /dev/null
+++ b/src/shared/test/queries/community-attention.test.ts
@@ -0,0 +1,157 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ visible: vi.fn(),
+ channels: vi.fn(),
+ dms: vi.fn(),
+ mentions: vi.fn(),
+ mentionScopes: vi.fn(),
+ friends: vi.fn(),
+}))
+
+vi.mock("../../src/db/queries/community/channel", () => ({
+ listVisibleChannelIdsForUser: (...args: unknown[]) => mocks.visible(...args),
+}))
+vi.mock("../../src/db/queries/community/inbox", () => ({
+ listEligibleUnreadChannels: (...args: unknown[]) => mocks.channels(...args),
+ listEligibleUnreadDms: (...args: unknown[]) => mocks.dms(...args),
+}))
+vi.mock("../../src/db/queries/community/mention", () => ({
+ listUnreadMentions: (...args: unknown[]) => mocks.mentions(...args),
+ listUnreadMentionScopes: (...args: unknown[]) => mocks.mentionScopes(...args),
+}))
+vi.mock("../../src/db/queries/community/friendship", () => ({
+ listActionableIncomingRequests: (...args: unknown[]) => mocks.friends(...args),
+}))
+
+import { getAccountAttentionSnapshot } from "../../src/db/queries/community/attention"
+import { AccountAttentionSnapshotSchema } from "../../src/community-attention"
+
+describe("account attention snapshot", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.visible.mockResolvedValue(["c1"])
+ mocks.channels.mockResolvedValue([{
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ lastUnreadSeq: 9,
+ lastAttentionSeq: 9,
+ mentionCount: 9,
+ }])
+ mocks.dms.mockResolvedValue([])
+ mocks.mentionScopes.mockResolvedValue([{
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ attentionCount: 9,
+ lastAttentionSeq: 9,
+ }])
+ mocks.mentions.mockResolvedValue(Array.from({ length: 3 }, (_, index) => ({
+ mention: { id: `men${index}`, kind: "mention" },
+ message: {
+ id: `m${index}`,
+ channelId: "c1",
+ type: "chat",
+ seq: 9 - index,
+ createdAt: `2026-09-27T00:00:0${index}.000Z`,
+ content: `message ${index}`,
+ },
+ author: {
+ id: `u${index}`,
+ name: `User ${index}`,
+ discriminator: `000${index}`,
+ image: null,
+ avatarVersion: 1,
+ },
+ })))
+ mocks.friends.mockResolvedValue(Array.from({ length: 3 }, (_, index) => ({
+ id: `f${index}`,
+ userId: `friend${index}`,
+ name: `Friend ${index}`,
+ discriminator: `100${index}`,
+ image: null,
+ avatarVersion: 1,
+ createdAt: `2026-09-27T00:01:0${index}.000Z`,
+ })))
+ })
+
+ it("caps only mention rows while keeping exact scope counts and every friend request", async () => {
+ const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+
+ expect(snapshot.truncated).toBe(true)
+ expect(snapshot.scopes[0]?.attentionCount).toBe(9)
+ expect(snapshot.items.filter((item) => item.kind !== "friend_request")).toHaveLength(2)
+ expect(snapshot.items.filter((item) => item.kind === "friend_request")).toHaveLength(3)
+ expect(snapshot.included?.profiles).toHaveLength(5)
+ expect(mocks.mentions).toHaveBeenCalledWith(
+ {},
+ "viewer",
+ { limit: 3, visibleChannelIds: ["c1"] },
+ )
+ })
+
+ it("keeps an attention-only scope after its ordinary unread cursor advances", async () => {
+ mocks.visible.mockResolvedValue(["c1"])
+ mocks.channels.mockResolvedValue([])
+ mocks.mentionScopes.mockResolvedValue([{
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: "forum1",
+ attentionCount: 3,
+ lastAttentionSeq: 7,
+ }])
+ const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+
+ expect(snapshot.scopes).toEqual([{
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: "forum1",
+ ordinaryUnread: false,
+ lastUnreadSeq: 7,
+ lastAttentionSeq: 7,
+ attentionCount: 3,
+ }])
+ expect(mocks.mentions).toHaveBeenCalledWith(
+ {},
+ "viewer",
+ { limit: 3, visibleChannelIds: ["c1"] },
+ )
+ })
+
+ it("drops a raced-in item whose aggregate scope is not present", async () => {
+ mocks.channels.mockResolvedValue([])
+ mocks.mentionScopes.mockResolvedValue([])
+
+ const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+
+ expect(snapshot.scopes).toEqual([])
+ expect(snapshot.items.filter((item) => item.kind !== "friend_request")).toEqual([])
+ expect(snapshot.truncated).toBe(false)
+ expect(() => AccountAttentionSnapshotSchema.parse(snapshot)).not.toThrow()
+ })
+
+ it("keeps a raced aggregate scope without requiring a bounded item row", async () => {
+ mocks.channels.mockResolvedValue([])
+ mocks.mentionScopes.mockResolvedValue([{
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ attentionCount: 3,
+ lastAttentionSeq: 9,
+ }])
+ mocks.mentions.mockResolvedValue([])
+
+ const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+
+ expect(snapshot.scopes).toEqual([expect.objectContaining({
+ scopeId: "c1",
+ ordinaryUnread: false,
+ attentionCount: 3,
+ })])
+ expect(snapshot.items.filter((item) => item.kind !== "friend_request")).toEqual([])
+ expect(snapshot.truncated).toBe(true)
+ expect(() => AccountAttentionSnapshotSchema.parse(snapshot)).not.toThrow()
+ })
+})
diff --git a/src/shared/test/queries/community-channel-directory.test.ts b/src/shared/test/queries/community-channel-directory.test.ts
index f479631db..fcf3f7f46 100644
--- a/src/shared/test/queries/community-channel-directory.test.ts
+++ b/src/shared/test/queries/community-channel-directory.test.ts
@@ -19,11 +19,13 @@ describe("groupChannelRefDirectoryRows", () => {
serverId: "server_1",
channelId: "channel_1",
channelName: "general",
+ channelType: "text",
},
{
serverId: "server_1",
channelId: "channel_2",
channelName: "random",
+ channelType: "forum",
},
]
);
@@ -35,8 +37,8 @@ describe("groupChannelRefDirectoryRows", () => {
name: "First",
discriminator: "0001",
channels: [
- { id: "channel_1", name: "general" },
- { id: "channel_2", name: "random" },
+ { id: "channel_1", name: "general", type: "text" },
+ { id: "channel_2", name: "random", type: "forum" },
],
},
]);
@@ -72,6 +74,7 @@ describe("listChannelRefDirectoryForUser", () => {
server_id TEXT,
category_id TEXT,
name TEXT,
+ type TEXT,
position INTEGER,
parent_channel_id TEXT,
creator_id TEXT
@@ -96,17 +99,17 @@ describe("listChannelRefDirectoryForUser", () => {
('private', 's1', 1, 1),
('private_s2', 's2', 0, 1);
INSERT INTO community_channel
- (id, server_id, category_id, name, position, parent_channel_id, creator_id)
+ (id, server_id, category_id, name, type, position, parent_channel_id, creator_id)
VALUES
- ('uncategorized', 's1', NULL, 'uncategorized', 0, NULL, 'other'),
- ('public_channel', 's1', 'public', 'public-channel', 1, NULL, 'other'),
- ('private_owned', 's1', 'private', 'private-owned', 2, NULL, 'viewer'),
- ('private_access', 's1', 'private', 'private-access', 3, NULL, 'other'),
- ('private_hidden', 's1', 'private', 'private-hidden', 4, NULL, 'other'),
- ('child_thread', 's1', 'public', 'child-thread', 5, 'public_channel', 'viewer'),
- ('s2_hidden', 's2', 'private_s2', 'hidden', 0, NULL, 'other'),
- ('nonmember_public', 's3', NULL, 'nonmember-public', 0, NULL, 'other'),
- ('dm', NULL, NULL, NULL, 0, NULL, 'viewer');
+ ('uncategorized', 's1', NULL, 'uncategorized', 'text', 0, NULL, 'other'),
+ ('public_channel', 's1', 'public', 'public-channel', 'text', 1, NULL, 'other'),
+ ('private_owned', 's1', 'private', 'private-owned', 'forum', 2, NULL, 'viewer'),
+ ('private_access', 's1', 'private', 'private-access', 'text', 3, NULL, 'other'),
+ ('private_hidden', 's1', 'private', 'private-hidden', 'text', 4, NULL, 'other'),
+ ('child_thread', 's1', 'public', 'child-thread', 'thread', 5, 'public_channel', 'viewer'),
+ ('s2_hidden', 's2', 'private_s2', 'hidden', 'text', 0, NULL, 'other'),
+ ('nonmember_public', 's3', NULL, 'nonmember-public', 'text', 0, NULL, 'other'),
+ ('dm', NULL, NULL, NULL, 'dm', 0, NULL, 'viewer');
INSERT INTO community_channel_member (id, channel_id, user_id, relation) VALUES
('cm_access', 'private_access', 'viewer', 'access'),
('cm_notify', 'private_hidden', 'viewer', 'notify'),
@@ -125,10 +128,10 @@ describe("listChannelRefDirectoryForUser", () => {
name: "First",
discriminator: "0001",
channels: [
- { id: "public_channel", name: "public-channel" },
- { id: "private_owned", name: "private-owned" },
- { id: "private_access", name: "private-access" },
- { id: "uncategorized", name: "uncategorized" },
+ { id: "public_channel", name: "public-channel", type: "text" },
+ { id: "private_owned", name: "private-owned", type: "forum" },
+ { id: "private_access", name: "private-access", type: "text" },
+ { id: "uncategorized", name: "uncategorized", type: "text" },
],
},
]);
diff --git a/src/shared/test/queries/community-friendship-actionable-incoming.test.ts b/src/shared/test/queries/community-friendship-actionable-incoming.test.ts
index 1d5983340..e4e1afd9f 100644
--- a/src/shared/test/queries/community-friendship-actionable-incoming.test.ts
+++ b/src/shared/test/queries/community-friendship-actionable-incoming.test.ts
@@ -14,6 +14,7 @@ describe("listActionableIncomingRequests", () => {
CREATE TABLE user (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
+ discriminator TEXT NOT NULL DEFAULT '',
image TEXT,
avatarVersion INTEGER NOT NULL DEFAULT 0
);
@@ -66,6 +67,7 @@ describe("listActionableIncomingRequests", () => {
id: "fr_newer",
userId: "newer",
name: "Newer",
+ discriminator: "",
image: null,
avatarVersion: 2,
createdAt: "2026-09-12T02:00:00Z",
@@ -74,6 +76,7 @@ describe("listActionableIncomingRequests", () => {
id: "fr_z",
userId: "tie-z",
name: "Tie Z",
+ discriminator: "",
image: null,
avatarVersion: 3,
createdAt: "2026-09-12T01:00:00Z",
@@ -82,6 +85,7 @@ describe("listActionableIncomingRequests", () => {
id: "fr_a",
userId: "tie-a",
name: "Tie A",
+ discriminator: "",
image: null,
avatarVersion: 4,
createdAt: "2026-09-12T01:00:00Z",
diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.ts
index e5b0d9b1a..659583d22 100644
--- a/src/shared/test/queries/community-machine.test.ts
+++ b/src/shared/test/queries/community-machine.test.ts
@@ -339,8 +339,6 @@ describe("reconcileBotActivityFromRunningAgents", () => {
// The reconciler only clears "stuck" system-driven bot-activity pills to
// Idle when the bot isn't in the daemon's runningAgents list. Owner-set
// custom statuses (not matching the known bot presets) are left alone.
- // See plans/community-bot-status-telemetry.md.
-
it("returns [] when no bots are bound to the machine", async () => {
const db: any = {
select: vi.fn(() => ({
diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.ts
index 0f7da95bd..cde34e594 100644
--- a/src/shared/test/queries/community-message.test.ts
+++ b/src/shared/test/queries/community-message.test.ts
@@ -546,7 +546,7 @@ describe("createMessage — seq assignment", () => {
});
});
-describe("createMessage — CAS claim (expectedSeq, plans/fix-agent-send-race-condition.md)", () => {
+describe("createMessage — CAS claim with expectedSeq", () => {
it("expectedSeq matching the current counter succeeds and returns a row with the expected seq", async () => {
const db = createCreateMessageDbMock({ currentSeq: 19 });
const msg = await messageQueries.createMessage(db, {
@@ -738,8 +738,7 @@ describe("getLatestMessage", () => {
// ── listMessagesAround / listMessagesSince / getLatestMessageSeq ─────────
//
-// New envelope-critical queries for the anchor-scroll refactor
-// (plans/community-message-scroll-v2.md §A1). The three feed the message-list
+// New envelope-critical queries for the anchor-scroll refactor. The three feed the message-list
// route's three URL modes: `?anchor`, `?since`, and the always-present
// `latestSeq` field.
diff --git a/src/shared/test/utils/community-mentions.test.ts b/src/shared/test/utils/community-mentions.test.ts
index cc3d41a1b..014115e04 100644
--- a/src/shared/test/utils/community-mentions.test.ts
+++ b/src/shared/test/utils/community-mentions.test.ts
@@ -2,8 +2,7 @@ import { describe, it, expect } from "vitest";
import { extractMentionedUserIds } from "../../src/utils/community-mentions";
// Every mention now resolves ONLY via a fully-tagged `@Name#dddd` handle — a
-// hand-typed bare `@Alice` is not a mention (see
-// plans/mandatory-mention-discriminator.md). Rosters carry a discriminator.
+// hand-typed bare `@Alice` is not a mention. Rosters carry a discriminator.
const ROSTER = [
{ userId: "u1", name: "Alice", discriminator: "0001" },
{ userId: "u2", name: "Bob", discriminator: "0002" },
diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.ts
index 2510a3d09..82be2d7b4 100644
--- a/src/web/cloudflare-env.d.ts
+++ b/src/web/cloudflare-env.d.ts
@@ -1,5 +1,5 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 23cac87604968cdeda4aee67162a8b5c)
+// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 6d732cfc124161cdc189fd746880d10e)
// Runtime types generated with [email protected] 2026-09-07 global_fetch_strictly_public,nodejs_compat
interface __BaseEnv_CloudflareEnv {
CACHE_KV: KVNamespace;
@@ -10,6 +10,7 @@ interface __BaseEnv_CloudflareEnv {
NEXT_TAG_CACHE_D1: D1Database;
DB: D1Database;
TASK_QUEUE: Queue;
+ CF_VERSION_METADATA: WorkerVersionMetadata;
ASSETS: Fetcher;
RUNTIME_MODEL_OPTIONS: "{\"claude\":[\"claude-opus-4-6\",\"claude-sonnet-4-6\",\"claude-haiku-4-5\"],\"codex\":[\"gpt-5.4\",\"gpt-5.3-codex\"]}";
MIN_CLI_VERSION: "0.0.159";
diff --git a/src/web/migrations/0050_community_bots.sql b/src/web/migrations/0050_community_bots.sql
index 38cc9b06a..aaa18932d 100644
--- a/src/web/migrations/0050_community_bots.sql
+++ b/src/web/migrations/0050_community_bots.sql
@@ -1,5 +1,5 @@
-- Community bots — first-class community identities owned by users, bound to
--- a paired machine + runtime. See plans/community-bots.md.
+-- a paired machine + runtime.
-- 1. Extend user with bot fields.
-- isBot / ownerUserId are internal columns (never exposed to non-owners).
diff --git a/src/web/migrations/0051_community_machine_status.sql b/src/web/migrations/0051_community_machine_status.sql
index c4a4f52a3..d98c203ab 100644
--- a/src/web/migrations/0051_community_machine_status.sql
+++ b/src/web/migrations/0051_community_machine_status.sql
@@ -1,6 +1,6 @@
-- community_machine.status — explicit online/offline column.
-- Before this migration, status was derived on read from last_seen_at.
--- See plans/community-machine-presence-fix.md.
+-- The explicit status is now authoritative; last_seen_at is only telemetry.
-- 1. Add the column with a safe default. Existing rows land as offline.
ALTER TABLE community_machine ADD COLUMN status TEXT NOT NULL DEFAULT 'offline';
diff --git a/src/web/migrations/0052_community_message_seq.sql b/src/web/migrations/0052_community_message_seq.sql
index fbd46b82c..391404dcd 100644
--- a/src/web/migrations/0052_community_message_seq.sql
+++ b/src/web/migrations/0052_community_message_seq.sql
@@ -1,5 +1,5 @@
-- Per-channel/DM message sequencing via an atomic counter table.
--- See plans/community-agent-cli-bridge.md design §3.
+-- The counter stores the most recently issued sequence per channel.
--
-- `seq` is per-scope (channel or DM), monotonic, unique, but NOT guaranteed
-- gap-free (see design §3 for why a rare gap is an accepted trade-off, not a
diff --git a/src/web/migrations/0053_community_read_state_last_read_seq.sql b/src/web/migrations/0053_community_read_state_last_read_seq.sql
index ee56eff33..e8ea1d83e 100644
--- a/src/web/migrations/0053_community_read_state_last_read_seq.sql
+++ b/src/web/migrations/0053_community_read_state_last_read_seq.sql
@@ -2,5 +2,5 @@
-- and bots (bots ARE users invariant). Only the agent `ack` route and the
-- author read-watermark upsert inside createMessage populate this; existing
-- human-only read routes (mark-all-read, thread read, DM read) intentionally
--- do not maintain it — see plans/community-agent-cli-bridge.md design §4.
+-- do not maintain it.
ALTER TABLE community_read_state ADD COLUMN last_read_seq INTEGER NOT NULL DEFAULT 0;
diff --git a/src/web/migrations/0056_community_channel_member.sql b/src/web/migrations/0056_community_channel_member.sql
index 73a0f2975..b4680bad7 100644
--- a/src/web/migrations/0056_community_channel_member.sql
+++ b/src/web/migrations/0056_community_channel_member.sql
@@ -1,5 +1,5 @@
-- Per-channel membership for PRIVATE-category channels.
--- See plans/channel-category-role-permissions.md.
+-- Membership gates visibility without widening category-level access.
--
-- Rows exist ONLY for channels in private categories (creator + directly-added
-- members). Public/uncategorized channels imply access via server membership;
diff --git a/src/web/migrations/0058_community_thread_participant.sql b/src/web/migrations/0058_community_thread_participant.sql
index cbf5104de..4dfd9e675 100644
--- a/src/web/migrations/0058_community_thread_participant.sql
+++ b/src/web/migrations/0058_community_thread_participant.sql
@@ -1,5 +1,5 @@
-- Thread participant / notification set.
--- See plans/nested-membership-model.md (Phase C).
+-- Participation is independent from parent-channel access.
--
-- A thread (community_channel row of type "thread") is the NOTIFICATION
-- dimension, not access: any member of its parent channel can READ it. This
diff --git a/src/web/migrations/0059_backfill_post_rosters.sql b/src/web/migrations/0059_backfill_post_rosters.sql
index 65bb0aaff..1126409c7 100644
--- a/src/web/migrations/0059_backfill_post_rosters.sql
+++ b/src/web/migrations/0059_backfill_post_rosters.sql
@@ -1,5 +1,5 @@
-- Backfill: give existing forum POSTS their own member roster.
--- See plans/nested-membership-model.md (Phase D).
+-- Existing posts inherit the members who could already access their parent forum.
--
-- Before the nested-membership model, a forum_post inherited its forum's
-- audience. Now a post owns its roster. Without this backfill, existing posts
diff --git a/src/web/migrations/0060_backfill_thread_participants.sql b/src/web/migrations/0060_backfill_thread_participants.sql
index ab7c558ac..bb528e24b 100644
--- a/src/web/migrations/0060_backfill_thread_participants.sql
+++ b/src/web/migrations/0060_backfill_thread_participants.sql
@@ -1,5 +1,5 @@
-- Backfill: seed participant rows for existing THREADS.
--- See plans/nested-membership-model.md (Phase D).
+-- Existing threads receive participant rows before reads switch to this table.
--
-- Before the nested-membership model, every parent-channel member was notified
-- of thread activity. Now only participants are. Without this backfill, ongoing
diff --git a/src/web/migrations/0061_unify_forum_membership.sql b/src/web/migrations/0061_unify_forum_membership.sql
index 29809cfe5..bdf5152eb 100644
--- a/src/web/migrations/0061_unify_forum_membership.sql
+++ b/src/web/migrations/0061_unify_forum_membership.sql
@@ -1,5 +1,5 @@
-- Unify forum/forum_post membership with channel/thread.
--- See plans/unify-forum-forumpost-channel-thread.md.
+-- Forum posts use the same access and notification relations as other channels.
--
-- Model change: a `forum` now owns its access roster like a text channel, and a
-- `forum_post` INHERITS that roster (it is the NOTIFY dimension, like a thread),
diff --git a/src/web/migrations/0062_community_switch_perf_indexes.sql b/src/web/migrations/0062_community_switch_perf_indexes.sql
index f706c28b0..c72b6b3d2 100644
--- a/src/web/migrations/0062_community_switch_perf_indexes.sql
+++ b/src/web/migrations/0062_community_switch_perf_indexes.sql
@@ -1,5 +1,5 @@
-- Perf: two indexes on the community server-switch path.
--- See plans/community-switch-perf-optimization.md (WS4).
+-- These cover the two lookups on the server-switch critical path.
--
-- Both tables are small today, so the immediate win is marginal — this is
-- correctness insurance as membership/invite counts grow. Idempotent.
diff --git a/src/web/migrations/0064_community_bot_binding_model.sql b/src/web/migrations/0064_community_bot_binding_model.sql
index 26f776a10..b88243670 100644
--- a/src/web/migrations/0064_community_bot_binding_model.sql
+++ b/src/web/migrations/0064_community_bot_binding_model.sql
@@ -1,5 +1,5 @@
-- Per-bot LLM model selection — one narrow nullable column on the bot binding.
--- See plans/community-bot-model-sync.md (TODO 5).
+-- Null keeps existing bindings on their runtime default model.
--
-- `model_name` is the full launchable model id (e.g. "claude-opus-4-6"), or
-- NULL for the runtime's own default. The ModelConfig `kind`
diff --git a/src/web/migrations/0065_unified_friendship_approval.sql b/src/web/migrations/0065_unified_friendship_approval.sql
index 24991fbef..007b43d52 100644
--- a/src/web/migrations/0065_unified_friendship_approval.sql
+++ b/src/web/migrations/0065_unified_friendship_approval.sql
@@ -1,4 +1,4 @@
--- Unified friendship approval gate. See plans/agent-friendship-approval-gate.md.
+-- Unified friendship approval gate for people and agents.
--
-- Folds the `kind='friend'` half of `community_bot_approval_request` into
-- `community_friendship`. Pending vs accepted becomes a column value, not a
diff --git a/src/web/migrations/0066_friendship_status_cancelled.sql b/src/web/migrations/0066_friendship_status_cancelled.sql
index 5d8af9904..0dec0084a 100644
--- a/src/web/migrations/0066_friendship_status_cancelled.sql
+++ b/src/web/migrations/0066_friendship_status_cancelled.sql
@@ -1,5 +1,4 @@
--- Widen community_friendship.status to allow 'cancelled'. See
--- plans/friend-cancel-card-cleanup.md.
+-- Widen community_friendship.status to allow explicit cancellation cleanup.
--
-- A requester withdrawing a still-pending request soft-cancels the row
-- (status='cancelled') instead of hard-deleting it, so a gating owner's
diff --git a/src/web/migrations/0067_channel_member_unify.sql b/src/web/migrations/0067_channel_member_unify.sql
index 3c2f376e6..42af2e166 100644
--- a/src/web/migrations/0067_channel_member_unify.sql
+++ b/src/web/migrations/0067_channel_member_unify.sql
@@ -1,5 +1,5 @@
-- Community schema unification (1/5): merge the membership tables.
--- See plans/community-schema-unification.md.
+-- One relation column now distinguishes access from notification membership.
--
-- `community_channel_member` gains two axes on one table:
-- relation — access | notify. `access` rows gate private units (a channel in
diff --git a/src/web/migrations/0070_message_seq_channel_pk.sql b/src/web/migrations/0070_message_seq_channel_pk.sql
index f3a4479bd..87515d4a2 100644
--- a/src/web/migrations/0070_message_seq_channel_pk.sql
+++ b/src/web/migrations/0070_message_seq_channel_pk.sql
@@ -1,5 +1,5 @@
-- Community schema unification (4/5): reseat the seq allocator on channel_id.
--- See plans/community-schema-unification.md.
+-- Channel IDs are the canonical message scope for both servers and DMs.
--
-- community_message_seq drops the 'channel:<id>' / 'dm:<id>' scope_key string
-- PK for a channel_id PK (now one scope). Backfill strips the prefix from the
diff --git a/src/web/migrations/0072_message_client_nonce.sql b/src/web/migrations/0072_message_client_nonce.sql
index dd07a7b39..b2b2fd7e1 100644
--- a/src/web/migrations/0072_message_client_nonce.sql
+++ b/src/web/migrations/0072_message_client_nonce.sql
@@ -1,4 +1,4 @@
--- Mutation-idempotency (plans/mutation-idempotency.md): give community_message
+-- Give community_message
-- a client-supplied idempotency key so a resend of the SAME logical message
-- (retry over a response-losing gateway) is deduped server-side instead of
-- inserting a duplicate row.
diff --git a/src/web/package.json b/src/web/package.json
index e95b1f7bf..e96f30cd5 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -68,6 +68,8 @@
"@streamdown/math": "^1.0.2",
"@streamdown/mermaid": "^1.0.2",
"@tanstack/query-async-storage-persister": "5.103.1",
+ "@tanstack/query-db-collection": "1.2.15",
+ "@tanstack/react-db": "0.4.1",
"@tanstack/react-query": "5.103.1",
"@tanstack/react-query-persist-client": "5.103.1",
"@tanstack/react-virtual": "^3.14.10",
diff --git a/src/web/scripts/perf-report.ts b/src/web/scripts/perf-report.ts
index 2a94848a2..54a73a630 100644
--- a/src/web/scripts/perf-report.ts
+++ b/src/web/scripts/perf-report.ts
@@ -1,6 +1,6 @@
/**
* Turn perf-artifacts/switch-events.json into a human-readable
- * perf-artifacts/switch-report.md. See plans/community-switch-perf-diagnosis.md.
+ * perf-artifacts/switch-report.md.
*
* The correlation core (`analyzeSwitch`, `renderReport`) is pure and exported
* for unit testing — no filesystem, no browser.
diff --git a/src/web/scripts/seed-stress.ts b/src/web/scripts/seed-stress.ts
index eb5f544ed..c9bdf2a5e 100644
--- a/src/web/scripts/seed-stress.ts
+++ b/src/web/scripts/seed-stress.ts
@@ -1,7 +1,7 @@
/**
* Stress-seed the local community DB for perf diagnosis.
*
- * See plans/community-switch-perf-diagnosis.md. This is a LOCAL diagnostic tool
+ * This is a LOCAL diagnostic tool
* — it is not wired into CI and ships nothing to prod.
*
* Usage:
diff --git a/src/web/src/app/api/agents/[id]/skills/route.ts b/src/web/src/app/api/agents/[id]/skills/route.ts
index c11cd276e..3520b48cb 100644
--- a/src/web/src/app/api/agents/[id]/skills/route.ts
+++ b/src/web/src/app/api/agents/[id]/skills/route.ts
@@ -25,7 +25,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
}
if (!KNOWN_RUNTIMES.includes(runtime as typeof KNOWN_RUNTIMES[number])) {
- console.warn(`[skills] Unknown runtime "${runtime}" for agent ${agentId}, defaulting to "claude"`);
+ console.warn(`[skills] Unsupported runtime "${runtime}" for agent ${agentId}, defaulting to "claude"`);
runtime = "claude";
}
diff --git a/src/web/src/app/api/auth/[...all]/route.test.ts b/src/web/src/app/api/auth/[...all]/route.test.ts
index de9efab3a..7fe175751 100644
--- a/src/web/src/app/api/auth/[...all]/route.test.ts
+++ b/src/web/src/app/api/auth/[...all]/route.test.ts
@@ -9,7 +9,7 @@ vi.mock("@/lib/middleware/env", () => ({
(route: (request: NextRequest, context: { env: object }) => Promise<Response>) =>
(request: NextRequest) => route(request, { env: {} }),
}))
-vi.mock("@/lib/auth", () => ({ createAuth: () => ({}) }))
+vi.mock("@/lib/auth", () => ({ getAuth: () => ({}) }))
vi.mock("better-auth/next-js", () => ({
toNextJsHandler: () => ({ GET: betterAuthGet, POST: betterAuthPost }),
}))
@@ -48,4 +48,16 @@ describe("Better Auth server-only endpoints", () => {
expect(response.status).toBe(204)
expect(betterAuthPost).toHaveBeenCalledOnce()
})
+
+ it("delegates ordinary Better Auth GET routes", async () => {
+ betterAuthGet.mockResolvedValue(new Response(null, { status: 204 }))
+ const request = new NextRequest("https://alook.ai/api/auth/session", {
+ method: "GET",
+ })
+
+ const response = await GET(request)
+
+ expect(response.status).toBe(204)
+ expect(betterAuthGet).toHaveBeenCalledOnce()
+ })
})
diff --git a/src/web/src/app/api/auth/[...all]/route.ts b/src/web/src/app/api/auth/[...all]/route.ts
index 40cdaff9f..81b0d93e9 100644
--- a/src/web/src/app/api/auth/[...all]/route.ts
+++ b/src/web/src/app/api/auth/[...all]/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from "next/server"
import { toNextJsHandler } from "better-auth/next-js"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
import { withEnv } from "@/lib/middleware/env"
import { nativeOauthSecurityHeaders } from "@/lib/native-oauth"
@@ -21,10 +21,10 @@ function notFound(): Response {
export const GET = withEnv(async (req: NextRequest, ctx) => {
if (isServerOnlyAuthRequest(req)) return notFound()
- return toNextJsHandler(createAuth(ctx.env)).GET(req)
+ return toNextJsHandler(getAuth(ctx.env)).GET(req)
});
export const POST = withEnv(async (req: NextRequest, ctx) => {
if (isServerOnlyAuthRequest(req)) return notFound()
- return toNextJsHandler(createAuth(ctx.env)).POST(req)
+ return toNextJsHandler(getAuth(ctx.env)).POST(req)
});
diff --git a/src/web/src/app/api/auth/native/exchange/route.ts b/src/web/src/app/api/auth/native/exchange/route.ts
index 3b327dc0f..2b8770294 100644
--- a/src/web/src/app/api/auth/native/exchange/route.ts
+++ b/src/web/src/app/api/auth/native/exchange/route.ts
@@ -1,5 +1,5 @@
import { createLogger, queries } from "@alook/shared";
-import { createAuth } from "@/lib/auth";
+import { getAuth } from "@/lib/auth";
import { getPrimaryDb } from "@/lib/db";
import { withEnv } from "@/lib/middleware/env";
import {
@@ -45,7 +45,7 @@ export const POST = withEnv(async (request, ctx) => {
let verifiedHeaders: Headers;
try {
- const verified = await createAuth(ctx.env).api.verifyOneTimeToken({
+ const verified = await getAuth(ctx.env).api.verifyOneTimeToken({
body: { token: parsed.data.code },
returnHeaders: true,
});
diff --git a/src/web/src/app/api/auth/native/native-routes.test.ts b/src/web/src/app/api/auth/native/native-routes.test.ts
index 165556465..e6004ef89 100644
--- a/src/web/src/app/api/auth/native/native-routes.test.ts
+++ b/src/web/src/app/api/auth/native/native-routes.test.ts
@@ -52,7 +52,7 @@ function installMocks() {
checkRateLimit: (...args: unknown[]) => rateLimitMock(...args),
}));
vi.doMock("@/lib/auth", () => ({
- createAuth: () => ({ api: authMocks }),
+ getAuth: () => ({ api: authMocks }),
}));
vi.doMock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>(
diff --git a/src/web/src/app/api/community/billing/routes.test.ts b/src/web/src/app/api/community/billing/routes.test.ts
index 276b55679..e577a6911 100644
--- a/src/web/src/app/api/community/billing/routes.test.ts
+++ b/src/web/src/app/api/community/billing/routes.test.ts
@@ -12,6 +12,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => mocks.db), getDb: vi.fn(() => mocks.db) }))
vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({ api: { getSession: mocks.session, signOut: vi.fn() } })),
+ getAuth: vi.fn(() => ({ api: { getSession: mocks.session, signOut: vi.fn() } })),
}))
vi.mock("@alook/shared", async (original) => ({
...await original<typeof import("@alook/shared")>(),
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
index bfe10599c..ffc8bcfb4 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.test.ts
@@ -151,7 +151,6 @@ describe("POST /api/community/bots/[id]/reset-session", () => {
// re-homed to the daemon completion signal (agent_session frame at
// reborn-ready), so the record reflects "the reset actually completed," not
// "the command was dispatched." The route must NOT write any of them.
- // See plans/reset-nap-completion-rehome.md.
expect(mockInsertBotAuditSessionReset).not.toHaveBeenCalled()
expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
expect(mockBroadcastToUser).not.toHaveBeenCalled()
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
index da70c2319..629a0aadf 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
@@ -15,7 +15,7 @@ import { pushAgentResetToMachine } from "@/lib/community/bot-push"
* The `session_reset` audit row + awake-time stamp + broadcast are NOT written
* here: they are re-homed to the daemon completion signal (the `agent_session`
* frame at reborn-ready), so the record reflects "the reset actually completed"
- * rather than "the command was dispatched." See plans/reset-nap-completion-rehome.md.
+ * rather than "the command was dispatched."
*/
export const POST = withAuth(async (_req, ctx) => {
const id = ctx.params?.id as string
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index f9daa8be8..7c118d6f8 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -120,7 +120,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
const willPush = before.isActive && (nameChanged || descriptionChanged) && !!before.machineId
const owner = willPush ? await queries.user.getUserPublic(db, before.ownerUserId) : null
if (willPush && !owner) {
- return writeError("bot owner not resolvable — refusing to push a bot update with unknown ownership", 500)
+ return writeError("bot owner not resolvable — refusing to push a bot update with unresolved ownership", 500)
}
const publicProfile = nameChanged
? await queries.communityUserProfile.getProfile(db, id)
diff --git a/src/web/src/app/api/community/bots/me/nap/route.test.ts b/src/web/src/app/api/community/bots/me/nap/route.test.ts
index 47db89881..ed2788114 100644
--- a/src/web/src/app/api/community/bots/me/nap/route.test.ts
+++ b/src/web/src/app/api/community/bots/me/nap/route.test.ts
@@ -32,8 +32,8 @@ vi.mock("@/lib/community/bot-push", () => ({
pushAgentNapToMachine: (...a: unknown[]) => mockPushAgentNapToMachine(...a),
}))
-// Unified actor: nap is a bot-only verb (moved from /agent/nap to /community/nap,
-// plans/22 §9). withCommunityActor injects the resolved actor; the bot acts on
+// Unified actor: nap is a bot-only verb moved from /agent/nap to /community/nap.
+// withCommunityActor injects the resolved actor; the bot acts on
// ITSELF — botUserId/machineId come from the authenticated runner, not the body.
// requireBot is a passthrough for a bot actor (human → 403, covered by the
// community-actor unit test). This test mocks the wrapper directly (as the
@@ -134,7 +134,7 @@ describe("POST /api/community/bots/me/nap", () => {
// The `nap` audit row + lastRefreshContextAt stamp are re-homed to the daemon
// completion signal (agent_session frame at reborn-ready), so the record
// reflects "the nap actually completed," not "the command was dispatched."
- // The route must NOT write either. See plans/reset-nap-completion-rehome.md.
+ // The route must NOT write either.
expect(mockInsertBotAuditNap).not.toHaveBeenCalled()
expect(mockTouchBotRefreshContext).not.toHaveBeenCalled()
})
diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.ts
index 2b668ca09..dc275daf1 100644
--- a/src/web/src/app/api/community/bots/route.ts
+++ b/src/web/src/app/api/community/bots/route.ts
@@ -179,8 +179,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
// real accepted community_friendship row for every existing live sibling.
// Idempotent (ON CONFLICT DO NOTHING) so a concurrent createBot race is
// absorbed. A per-sibling failure never fails createBot — the
- // bot exists and is usable; siblings can reconcile via the CLI later. See
- // plans/agent-friendship-approval-gate.md §Bot creation.
+ // bot exists and is usable; siblings can reconcile via the CLI later.
try {
const siblings = await queries.communityBot.listBotsForOwner(db, ctx.userId)
for (const sibling of siblings) {
diff --git a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
index 6ffc6ffbf..717da5814 100644
--- a/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/attachments/route.test.ts
@@ -21,6 +21,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
@@ -309,8 +312,8 @@ describe("POST /api/community/channels/[id]/attachments — human arm (re-homes
mockRunAttachmentUpload.mockResolvedValueOnce(helperResponse)
// Human session resolves — withAuth adopts { userId }.
- const { createAuth } = await import("@/lib/auth")
- ;(createAuth as unknown as ReturnType<typeof vi.fn>).mockReturnValueOnce({
+ const { getAuth } = await import("@/lib/auth")
+ ;(getAuth as unknown as ReturnType<typeof vi.fn>).mockReturnValueOnce({
api: {
getSession: vi.fn(async () => ({
headers: new Headers(),
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 e3e2af9c8..3ad52dda7 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
@@ -991,8 +991,8 @@ describe("GET /api/community/channels/[id]/messages", () => {
const byId = new Map(body.messages.map((m) => [m.id, m]))
expect(byId.get("m-a")?.replyTo).toEqual({ id: "r-in-scope", authorName: "Zed", text: "original" })
- expect(byId.get("m-b")?.replyTo).toEqual({ id: "r-out-of-scope", authorName: "Unknown", text: "", deleted: true })
- expect(byId.get("m-c")?.replyTo).toEqual({ id: "r-missing", authorName: "Unknown", text: "", deleted: true })
+ expect(byId.get("m-b")?.replyTo).toEqual({ id: "r-out-of-scope", authorName: "Deleted user", text: "", deleted: true })
+ expect(byId.get("m-c")?.replyTo).toEqual({ id: "r-missing", authorName: "Deleted user", text: "", deleted: true })
expect(byId.get("m-d")?.replyTo).toEqual({ id: "r-in-scope", authorName: "Zed", text: "original" })
expect(byId.get("m-e")?.replyTo).toBeUndefined()
@@ -1029,10 +1029,10 @@ describe("GET /api/community/channels/[id]/messages", () => {
expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
})
- it("returns author.name verbatim — no 'Unknown' sentinel, no email leak", async () => {
+ it("returns author.name verbatim — no generated fallback sentinel or email leak", async () => {
// Post-migration 0050 the shared query returns user.name as a non-empty
// string. The route must drop the pre-migration cascade
- // (`authorName ?? authorEmail ?? "Unknown"`) and pass the name through.
+ // (`authorName ?? authorEmail ?? fallback`) and pass the name through.
mockListMessages.mockResolvedValue([
{
id: "m-1",
@@ -1055,7 +1055,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
messages: Array<{ authorName: string; authorAvatar: string }>
}
expect(body.messages[0]?.authorName).toBe("Alice")
- expect(body.messages[0]?.authorName).not.toBe("Unknown")
+ expect(body.messages[0]?.authorName).not.toBe("Deleted user")
expect(body.messages[0]?.authorName).not.toContain("@")
expect(body.messages[0]?.authorAvatar).toBe("A")
})
diff --git a/src/web/src/app/api/community/daemon/activate/route.ts b/src/web/src/app/api/community/daemon/activate/route.ts
index 925afd221..bc267a817 100644
--- a/src/web/src/app/api/community/daemon/activate/route.ts
+++ b/src/web/src/app/api/community/daemon/activate/route.ts
@@ -19,8 +19,7 @@ const log = createLogger({ service: "community/daemon/activate" })
*
* Exchanges a pending pairing token (`cmt_...`, Bearer) for a long-lived
* daemon credential (`cmk_...`). Server atomically revokes the pairing
- * token so it can't be re-used. See plans/remove-community-mode.md
- * "Contract 1" for the wire spec.
+ * token so it can't be re-used.
*/
export const POST = withCommunityPairingToken(async (req, ctx) => {
const tokenId = ctx.rawTokenId
diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts
index 76fffdb95..0af77c80a 100644
--- a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts
+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts
@@ -125,7 +125,7 @@ describe("POST /api/community/daemon/resync-wakes", () => {
it("Mellicent regression: bot on a server whose only unread lives in a non-participated forum_post — feeder returns null → attempted: 0", async () => {
// Post-fix behaviour: `getLatestUnreadMessageForAgent` applies the
- // thread-participation post-filter (`plans/agent-unread-visibility-unify.md`),
+ // thread-participation post-filter,
// so a message in a forum_post the bot isn't a participant of no longer
// surfaces. The feeder returns null → resync-wakes reports attempted: 0 and
// never touches the wake dispatcher.
diff --git a/src/web/src/app/api/community/friends/[id]/accept/route.ts b/src/web/src/app/api/community/friends/[id]/accept/route.ts
index b56a5b2f0..5bece0d5b 100644
--- a/src/web/src/app/api/community/friends/[id]/accept/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/accept/route.ts
@@ -8,7 +8,7 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
- // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ // Bots cannot bypass the owner-approval path through the human route.
if (ctx.user?.isBot) return writeError("forbidden", 403)
if (!id) {
diff --git a/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
index 76cdfda4e..abc24f202 100644
--- a/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
+++ b/src/web/src/app/api/community/friends/[id]/gated-and-roles.test.ts
@@ -3,8 +3,7 @@ import { NextRequest } from "next/server"
/**
* Accept/reject gated-refusal + DELETE role behavior for the unified friendship
- * flow. See plans/agent-friendship-approval-gate.md §test cases (Existing
- * human-path routes).
+ * flow through existing human-path routes.
*/
const getFriendship = vi.fn()
@@ -138,7 +137,7 @@ describe("DELETE — one path per role", () => {
it("requester cancels a gated pending request → soft-cancel + rehydrate owner's card", async () => {
// Human→bot request gated on the bot's owner: an actionable Approve/Deny
// card is sitting in the owner's DM. Withdrawing must flip that card, not
- // orphan it. See plans/friend-cancel-card-cleanup.md.
+ // orphan it.
getFriendship.mockResolvedValue({
id: "fr_1", requesterId: "u_alice", addresseeId: "bot_yara", status: "pending", needsOwnerApproval: "owner_carol",
})
diff --git a/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
index d94129ed7..ce7cfd09f 100644
--- a/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/owner-decision/route.ts
@@ -9,7 +9,6 @@ import { broadcastToUserSafe } from "@/lib/community/fanout"
* POST /api/community/friends/[id]/owner-decision — body `{ decision }`. The
* bot owner approves or denies a gated friend row via their DM card.
* Dispatches to `ownerDecideOnRow`, which encapsulates all four cases.
- * See plans/agent-friendship-approval-gate.md §Owner decision endpoint.
*/
export const POST = withAuth(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
diff --git a/src/web/src/app/api/community/friends/[id]/reject/route.ts b/src/web/src/app/api/community/friends/[id]/reject/route.ts
index bca4f8354..ce83a9f25 100644
--- a/src/web/src/app/api/community/friends/[id]/reject/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/reject/route.ts
@@ -8,7 +8,7 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
- // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ // Bots cannot bypass the owner-approval path through the human route.
if (ctx.user?.isBot) return writeError("forbidden", 403)
if (!id) {
diff --git a/src/web/src/app/api/community/friends/[id]/route.ts b/src/web/src/app/api/community/friends/[id]/route.ts
index 82de0d3cb..5d7e69595 100644
--- a/src/web/src/app/api/community/friends/[id]/route.ts
+++ b/src/web/src/app/api/community/friends/[id]/route.ts
@@ -9,7 +9,7 @@ export const DELETE = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const id = ctx.params?.id as string
- // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ // Bots cannot bypass the owner-approval path through the human route.
if (ctx.user?.isBot) return writeError("forbidden", 403)
if (!id) {
diff --git a/src/web/src/app/api/community/friends/accepted/route.bot.test.ts b/src/web/src/app/api/community/friends/accepted/route.bot.test.ts
index 4c6e5208f..43bca6d34 100644
--- a/src/web/src/app/api/community/friends/accepted/route.bot.test.ts
+++ b/src/web/src/app/api/community/friends/accepted/route.bot.test.ts
@@ -12,6 +12,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/friends/blocked/route.test.ts b/src/web/src/app/api/community/friends/blocked/route.test.ts
index 3f43a2713..f82b9374e 100644
--- a/src/web/src/app/api/community/friends/blocked/route.test.ts
+++ b/src/web/src/app/api/community/friends/blocked/route.test.ts
@@ -9,6 +9,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
index a9202ed9d..6740c065d 100644
--- a/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
+++ b/src/web/src/app/api/community/friends/friend-graph-hardening.test.ts
@@ -7,7 +7,6 @@ import { NextRequest } from "next/server"
* `middleware/auth.ts` rejects a bot session at 401 first, so these tests mock
* `withAuth` to inject a synthesized `ctx.user.isBot = true` and call the
* handler directly — the only way to actually exercise the local assertion.
- * See plans/agent-friendship-approval-gate.md §Hardening.
*/
const getFriendship = vi.fn()
diff --git a/src/web/src/app/api/community/friends/pending/route.bot.test.ts b/src/web/src/app/api/community/friends/pending/route.bot.test.ts
index 8db300896..9676e7c74 100644
--- a/src/web/src/app/api/community/friends/pending/route.bot.test.ts
+++ b/src/web/src/app/api/community/friends/pending/route.bot.test.ts
@@ -9,6 +9,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/friends/request/route.ts b/src/web/src/app/api/community/friends/request/route.ts
index 3998b31cc..ed888a673 100644
--- a/src/web/src/app/api/community/friends/request/route.ts
+++ b/src/web/src/app/api/community/friends/request/route.ts
@@ -53,8 +53,7 @@ async function handleHumanFriendRequest(
// the bot would bypass owner-approval and directly auto-friend = capability
// escalation. So keep the last-line isBot→403 even with the gate above.
// (Always false in production — a bot session is rejected at 401 before any
- // handler runs; this is the future-auth-regression backstop.) See
- // plans/agent-friendship-approval-gate.md §Hardening.
+ // handler runs; this is the future-auth-regression backstop.)
if (actor.isBot) return writeError("forbidden", 403)
let body: { userId?: string; username?: string }
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
index e114fb9a4..8739b725b 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.bot.test.ts
@@ -14,6 +14,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
index 1e237a37f..8f92f22c1 100644
--- a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
@@ -20,7 +20,7 @@ import { pushBatchResetToMachine } from "@/lib/community/bot-push"
* v1 is DISPATCH-level (Gus 架构#825): we confirm the daemon RECEIVED the batch,
* not per-agent reset completion — matching single-reset's fire-and-confirm-
* delivery honesty. No per-agent success tracking (that'd be a v2 correlated-ack
- * path the control channel doesn't have). See plans/daemon-batch-reset.md.
+ * path the control channel doesn't have).
*/
export const POST = withAuth(async (_req, ctx) => {
const machineId = ctx.params?.id as string
diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.ts
index 2e8c88918..cd96d05ae 100644
--- a/src/web/src/app/api/community/messages/[id]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts
@@ -176,6 +176,7 @@ describe("GET /api/community/messages/[id]", () => {
expect(res.status).toBe(200)
const body = await res.json()
expect(body.id).toBe("m1")
+ expect(body.channelId).toBe("c1")
expect(body.content).toBe("hello")
expect(body.authorName).toBe("Alice")
// Attachments came through the mapper (grouped shape) — url is now the
@@ -243,7 +244,7 @@ describe("GET /api/community/messages/[id]", () => {
const res = await GET(req(), { params: { id: "m1" } } as any)
const body = await res.json()
// Target not found in scope — mapper returns the `deleted` sentinel.
- expect(body.replyTo).toEqual({ id: "m0", authorName: "Unknown", text: "", deleted: true })
+ expect(body.replyTo).toEqual({ id: "m0", authorName: "Deleted user", text: "", deleted: true })
})
it("returns 404 when the message doesn't exist", async () => {
diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.ts
index 2267877d3..044021b8a 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -257,7 +257,7 @@ async function handleHumanGet(
const replyMap = new Map(replyMessages.map((m) => [m.id, m]))
const payload = mapMessageForApi(message, { replyMap, attachmentsByMessage, reactionsByMessage })
- return writeJSON(payload)
+ return writeJSON({ ...payload, channelId: message.channelId })
}
/**
diff --git a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
index d38b0be87..d2724ca98 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/[catId]/route.ts
@@ -26,7 +26,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
// Only the name is mutable. Category privacy (public/private) is fixed at
// creation — flipping it would silently widen/tighten channel visibility, so
// `private` is intentionally NOT accepted here (change it by recreating the
- // category). See plans/channel-category-role-permissions.md.
+ // category).
let body: { name?: string }
try {
body = await req.json()
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts
index 22923d165..52862a386 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.bot.test.ts
@@ -13,6 +13,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts
index 9f3654996..650769192 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.bot.test.ts
@@ -13,6 +13,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/servers/channels/route.bot.test.ts b/src/web/src/app/api/community/servers/channels/route.bot.test.ts
index bb8e403fc..b744bbcef 100644
--- a/src/web/src/app/api/community/servers/channels/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/channels/route.bot.test.ts
@@ -13,6 +13,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/servers/route.bot.test.ts b/src/web/src/app/api/community/servers/route.bot.test.ts
index d07f91d68..7bba03f3c 100644
--- a/src/web/src/app/api/community/servers/route.bot.test.ts
+++ b/src/web/src/app/api/community/servers/route.bot.test.ts
@@ -21,6 +21,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/users/[userId]/block/route.ts b/src/web/src/app/api/community/users/[userId]/block/route.ts
index 2c75d1c30..eb4cd1cc5 100644
--- a/src/web/src/app/api/community/users/[userId]/block/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/block/route.ts
@@ -8,7 +8,7 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const targetId = ctx.params?.userId as string
- // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ // Bots cannot mutate the human friendship graph through this route.
if (ctx.user?.isBot) return writeError("forbidden", 403)
if (!targetId) return writeError("userId is required", 400)
diff --git a/src/web/src/app/api/community/users/[userId]/unblock/route.ts b/src/web/src/app/api/community/users/[userId]/unblock/route.ts
index e7daf677f..54cb03b0e 100644
--- a/src/web/src/app/api/community/users/[userId]/unblock/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/unblock/route.ts
@@ -7,7 +7,7 @@ export const POST = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const targetId = ctx.params?.userId as string
- // Hardening — see plans/agent-friendship-approval-gate.md §Hardening.
+ // Bots cannot mutate the human friendship graph through this route.
if (ctx.user?.isBot) return writeError("forbidden", 403)
if (!targetId) return writeError("userId is required", 400)
diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.test.ts b/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
index 988ffc6dd..1e23d1077 100644
--- a/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
+++ b/src/web/src/app/api/community/users/me/account-deletion/route.test.ts
@@ -17,7 +17,7 @@ vi.mock("@/lib/middleware/auth", () => ({
}),
}))
vi.mock("@/lib/db", () => ({ getPrimaryDb: (...args: unknown[]) => getPrimaryDb(...args) }))
-vi.mock("@/lib/auth", () => ({ createAuth: () => ({ api: { signOut } }) }))
+vi.mock("@/lib/auth", () => ({ getAuth: () => ({ api: { signOut } }) }))
vi.mock("@/lib/account-deletion/challenge", () => ({
verifyDeletionCode: (...args: unknown[]) => verifyDeletionCode(...args),
restoreVerifiedDeletionCode: (...args: unknown[]) => restoreVerifiedDeletionCode(...args),
diff --git a/src/web/src/app/api/community/users/me/account-deletion/route.ts b/src/web/src/app/api/community/users/me/account-deletion/route.ts
index 4caa43a4a..daddeb331 100644
--- a/src/web/src/app/api/community/users/me/account-deletion/route.ts
+++ b/src/web/src/app/api/community/users/me/account-deletion/route.ts
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server"
import { z } from "zod"
import { withCookieHumanAuth } from "@/lib/middleware/auth"
import { getPrimaryDb } from "@/lib/db"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
import {
restoreVerifiedDeletionCode,
verifyDeletionCode,
@@ -72,7 +72,7 @@ export const POST = withCookieHumanAuth(async (request, context) => {
)
clearAuthCookies(response)
try {
- const signOut = await createAuth(context.env).api.signOut({
+ const signOut = await getAuth(context.env).api.signOut({
headers: request.headers,
returnHeaders: true,
}) as { headers: Headers }
diff --git a/src/web/src/app/api/community/users/me/attention/route.test.ts b/src/web/src/app/api/community/users/me/attention/route.test.ts
new file mode 100644
index 000000000..c85f77c7f
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/attention/route.test.ts
@@ -0,0 +1,57 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ snapshot: vi.fn(),
+ getPrimaryDb: vi.fn(() => ({ kind: "primary-db" })),
+}))
+
+vi.mock("@/lib/db", () => ({
+ getPrimaryDb: (...args: unknown[]) => mocks.getPrimaryDb(...args),
+}))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityAttention: {
+ getAccountAttentionSnapshot: (...args: unknown[]) => mocks.snapshot(...args),
+ },
+ },
+ readOrStale: (operation: () => unknown) => Promise.resolve(operation()).then((value) => ({
+ value,
+ stale: false,
+ })),
+ }
+})
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => (request: any) => handler(request, {
+ env: { DB: { binding: "d1" } },
+ userId: "u1",
+ }),
+}))
+vi.mock("@/lib/middleware/helpers", () => ({
+ writeJSON: (data: unknown) => Response.json(data),
+}))
+
+import { GET } from "./route"
+
+describe("GET /api/community/users/me/attention", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("uses the primary-authoritative session for the stateless snapshot", async () => {
+ mocks.snapshot.mockResolvedValue({
+ scopes: [],
+ items: [],
+ limit: 100,
+ truncated: false,
+ included: { profiles: [], messages: [] },
+ })
+
+ const response = await GET(new Request("http://localhost/api/community/users/me/attention") as any)
+
+ await expect(response.json()).resolves.toMatchObject({ scopes: [], items: [] })
+ expect(mocks.getPrimaryDb).toHaveBeenCalledWith({ binding: "d1" })
+ expect(mocks.snapshot).toHaveBeenCalledWith({ kind: "primary-db" }, "u1", 100)
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/attention/route.ts b/src/web/src/app/api/community/users/me/attention/route.ts
new file mode 100644
index 000000000..f878961b7
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/attention/route.ts
@@ -0,0 +1,34 @@
+import {
+ AccountAttentionSnapshotSchema,
+ DEFAULT_INBOX_PAGE_SIZE,
+ MAX_INBOX_PAGE_SIZE,
+ queries,
+ readOrStale,
+} from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { parseBoundedInt } from "@/lib/community/messages"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON } from "@/lib/middleware/helpers"
+
+export const GET = withAuth(async (request, ctx) => {
+ const db = getPrimaryDb(ctx.env.DB)
+ const url = new URL(request.url)
+ const limit = parseBoundedInt(
+ url.searchParams.get("limit"),
+ DEFAULT_INBOX_PAGE_SIZE,
+ MAX_INBOX_PAGE_SIZE,
+ )
+ const { value, stale } = await readOrStale(
+ () => queries.communityAttention.getAccountAttentionSnapshot(db, ctx.userId, limit),
+ {
+ scopes: [],
+ items: [],
+ limit,
+ truncated: false,
+ included: { profiles: [], messages: [] },
+ },
+ { route: "community/attention" },
+ )
+ if (stale) return writeJSON({ ...value, stale: true })
+ return writeJSON(AccountAttentionSnapshotSchema.parse(value))
+})
diff --git a/src/web/src/app/api/community/users/me/avatar/route.test.ts b/src/web/src/app/api/community/users/me/avatar/route.test.ts
index 4826a72a5..fb9dcbceb 100644
--- a/src/web/src/app/api/community/users/me/avatar/route.test.ts
+++ b/src/web/src/app/api/community/users/me/avatar/route.test.ts
@@ -20,7 +20,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@/lib/auth", () => ({
- createAuth: vi.fn(() => ({
+ getAuth: vi.fn(() => ({
api: { updateUser: (...a: unknown[]) => mockAuthUpdateUser(...a) },
})),
}))
diff --git a/src/web/src/app/api/community/users/me/avatar/route.ts b/src/web/src/app/api/community/users/me/avatar/route.ts
index 9f078e9a0..c6e8366bb 100644
--- a/src/web/src/app/api/community/users/me/avatar/route.ts
+++ b/src/web/src/app/api/community/users/me/avatar/route.ts
@@ -3,7 +3,7 @@ import { createLogger, queries } from "@alook/shared"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
import { handleBotAvatarUpload, handleUserAvatarUpload } from "@/lib/community/upload"
import { botAvatarUrl, userAvatarUrl } from "@/lib/community/storage"
import { persistUploadedBotAvatar } from "@/lib/community/bot-avatar-persistence"
@@ -112,7 +112,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
const url = userAvatarUrl(userId, avatarVersion)
let authHeaders: Headers | null = null
try {
- const auth = createAuth(ctx.env)
+ const auth = getAuth(ctx.env)
const authResult = (await auth.api.updateUser({
body: { image: userAvatarUrl(userId) },
headers: req.headers,
diff --git a/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts b/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts
index 19b82a950..967286a5e 100644
--- a/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/ack/route.test.ts
@@ -13,6 +13,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts
index e4e2c6ca2..a2e34469f 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.test.ts
@@ -69,7 +69,7 @@ describe("GET /api/community/users/me/inbox/mentions", () => {
mockListUnreadMentions.mockResolvedValue([
{
mention: { id: "mn1", kind: "mention" },
- message: { id: "m1", seq: 4, channelId: "c1", content: "@u1 hi", createdAt: "2026-06-25T10:00:00Z" },
+ message: { id: "m1", type: "system", seq: 4, channelId: "c1", content: "@u1 hi", createdAt: "2026-06-25T10:00:00Z" },
author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },
},
])
@@ -95,10 +95,32 @@ describe("GET /api/community/users/me/inbox/mentions", () => {
// authorId is the beam-avatar seed the inbox popover renders from
// (<Avatar seed={mn.m.authorId}>) — omitting it blanked image-less
// authors' avatars, same bug the pins route had.
- m: { id: "m1", seq: 4, authorId: "u-alice", authorName: "Alice", content: "@u1 hi" },
+ m: { id: "m1", type: "system", seq: 4, authorId: "u-alice", authorName: "Alice", content: "@u1 hi" },
})
})
+ it("normalizes an ordinary stored message to the canonical chat wire type", async () => {
+ mockListUnreadMentions.mockResolvedValue([{
+ mention: { id: "mn-default", kind: "mention" },
+ message: {
+ id: "m-default",
+ type: "default",
+ seq: 1,
+ channelId: "c1",
+ content: "hello",
+ createdAt: "2026-06-25T10:00:00Z",
+ },
+ author: { id: "u-alice", name: "Alice", image: null, avatarVersion: 0 },
+ }])
+ mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])
+ mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])
+
+ const body = await (await GET(new NextRequest(
+ "http://localhost/api/community/users/me/inbox/mentions",
+ ))).json()
+ expect(body.mentions[0].m).toMatchObject({ id: "m-default", type: "chat" })
+ })
+
it("tags reply-kind rows so the UI can label them 'replied to you'", async () => {
mockListUnreadMentions.mockResolvedValue([
{
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/route.ts
index 9d8bb2111..95fedce7f 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/route.ts
@@ -10,6 +10,7 @@ import {
import { parseBoundedInt } from "@/lib/community/messages"
import { avatarInitial } from "@/lib/community/avatar"
import { canonicalUserImage } from "@/lib/community/storage"
+import { projectMessageWireType } from "@/lib/community/message-wire-type"
export const GET = withAuth(async (req, ctx) => {
const db = getDb(ctx.env.DB)
@@ -65,15 +66,16 @@ export const GET = withAuth(async (req, ctx) => {
// "mention" (@-mention) vs "reply" — the UI labels them differently
// ("mentioned you" vs "replied to you").
kind: row.mention.kind,
- // srv/ch fall back to "Unknown" only when the underlying row was deleted
- // between mention insert and this read — unrelated to user-name integrity.
- server: srv ? srv.name : "Unknown",
+ // Missing navigation rows are explicit unavailable states, never a
+ // visible "Unknown" identity generated by the system.
+ server: srv ? srv.name : "Server unavailable",
serverId: ch?.serverId,
- channel: ch ? ch.name : "Unknown",
+ channel: ch ? ch.name : "Conversation unavailable",
channelId: row.message.channelId,
parentChannelId: ch?.parentChannelId ?? null,
m: {
id: row.message.id,
+ ...projectMessageWireType(row.message.type),
seq: row.message.seq,
// authorId is the beam-avatar seed the popover renders from
// (<Avatar seed={authorId}>); omitting it left image-less authors with
diff --git a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
index ce371f587..cf894dce7 100644
--- a/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/pull/route.test.ts
@@ -9,6 +9,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts b/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts
index 94f8368b4..0288d2a87 100644
--- a/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/snapshot/route.test.ts
@@ -9,6 +9,9 @@ vi.mock("@/lib/auth", () => ({
createAuth: vi.fn(() => ({
api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
})),
+ getAuth: vi.fn(() => ({
+ api: { getSession: vi.fn(async () => ({ headers: new Headers(), response: null })) },
+ })),
}))
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
diff --git a/src/web/src/app/api/community/users/me/marks/route.test.ts b/src/web/src/app/api/community/users/me/marks/route.test.ts
index b49480b25..50b36a5dd 100644
--- a/src/web/src/app/api/community/users/me/marks/route.test.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.test.ts
@@ -102,7 +102,7 @@ describe("GET /api/community/users/me/marks", () => {
mockListMarksForUser.mockResolvedValue([
{
mark: { id: "mk1", channelId: "c1", createdAt: "2026-06-25T10:00:00Z" },
- message: { id: "m1", seq: 42, content: "pinned thought", createdAt: "2026-06-25T09:00:00Z" },
+ message: { id: "m1", type: "system", seq: 42, content: "pinned thought", createdAt: "2026-06-25T09:00:00Z" },
author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },
},
])
@@ -127,10 +127,31 @@ describe("GET /api/community/users/me/marks", () => {
// serverId + channelId locate the channel, m.seq jumps to the message —
// all three required for cross-channel navigation. seq lives inside `m`
// to match the frontend `Marked` type (m: Msg).
- m: { id: "m1", authorId: "u-alice", authorName: "Alice", content: "pinned thought", seq: 42 },
+ m: { id: "m1", type: "system", authorId: "u-alice", authorName: "Alice", content: "pinned thought", seq: 42 },
})
})
+ it("normalizes an ordinary stored message to the canonical chat wire type", async () => {
+ mockListMarksForUser.mockResolvedValue([{
+ mark: { id: "mk-default", channelId: "c1" },
+ message: {
+ id: "m-default",
+ type: "default",
+ seq: 1,
+ content: "hello",
+ createdAt: "2026-06-25T09:00:00Z",
+ },
+ author: { id: "u-alice", name: "Alice", image: null, avatarVersion: 0 },
+ }])
+ mockGetChannelsByIds.mockResolvedValue([{ id: "c1", name: "general", serverId: "s1" }])
+ mockGetServersByIds.mockResolvedValue([{ id: "s1", name: "Server 1" }])
+
+ const body = await (await GET(new NextRequest(
+ "http://localhost/api/community/users/me/marks",
+ ))).json()
+ expect(body.marked[0].m).toMatchObject({ id: "m-default", type: "chat" })
+ })
+
it("returns empty marked array when none", async () => {
mockListMarksForUser.mockResolvedValue([])
const res = await GET(new NextRequest("http://localhost/api/community/users/me/marks"))
diff --git a/src/web/src/app/api/community/users/me/marks/route.ts b/src/web/src/app/api/community/users/me/marks/route.ts
index 18eb74bc7..4f84e5795 100644
--- a/src/web/src/app/api/community/users/me/marks/route.ts
+++ b/src/web/src/app/api/community/users/me/marks/route.ts
@@ -11,6 +11,7 @@ import {
import { parseBoundedInt } from "@/lib/community/messages"
import { avatarInitial } from "@/lib/community/avatar"
import { canonicalUserImage } from "@/lib/community/storage"
+import { projectMessageWireType } from "@/lib/community/message-wire-type"
// Cross-channel Marked tab: every message the current user has marked, newest
// first. Scoped to the viewer's visible channels in-query (same guard as the
@@ -113,13 +114,14 @@ export const GET = withCommunityActor(async (req, ctx) => {
const srv = ch ? serverMap.get(ch.serverId) : undefined
return {
id: row.mark.id,
- server: srv ? srv.name : "Unknown",
+ server: srv ? srv.name : "Server unavailable",
serverId: ch?.serverId,
- channel: ch ? ch.name : "Unknown",
+ channel: ch ? ch.name : "Conversation unavailable",
channelId: row.mark.channelId,
parentChannelId: ch?.parentChannelId ?? null,
m: {
id: row.message.id,
+ ...projectMessageWireType(row.message.type),
authorId: row.author.id,
authorName: row.author.name,
authorAvatar: canonicalUserImage(
diff --git a/src/web/src/app/api/community/users/me/profile/route.test.ts b/src/web/src/app/api/community/users/me/profile/route.test.ts
index fc9ce270b..bd73e20af 100644
--- a/src/web/src/app/api/community/users/me/profile/route.test.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.test.ts
@@ -20,7 +20,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@/lib/auth", () => ({
- createAuth: vi.fn(() => ({
+ getAuth: vi.fn(() => ({
api: { updateUser: (...a: unknown[]) => authApiUpdateUser(...a) },
})),
}))
diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.ts
index 227599f40..afc86aee4 100644
--- a/src/web/src/app/api/community/users/me/profile/route.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.ts
@@ -9,7 +9,7 @@ import {
withD1Retry,
} from "@alook/shared"
import { getDb } from "@/lib/db"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { fanOutProfileUpdate, fanOutStatusUpdate } from "@/lib/community/fanout"
@@ -99,7 +99,7 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
// refresh right after renaming doesn't read a stale cached session
// (the bug this fixes: cookieCache — auth.ts's `session.cookieCache`,
// 5min TTL — previously never got invalidated by a raw DB write).
- const auth = createAuth(ctx.env)
+ const auth = getAuth(ctx.env)
const result = (await auth.api.updateUser({
body: { name: trimmed },
headers: req.headers,
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
index ad4e1b895..870f2f52e 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
@@ -288,6 +288,30 @@ describe("POST /api/conversations/[id]/messages", () => {
expect(body.error).toBe("not found");
});
+ it("returns a stable fallback when task enqueue rejects with a non-Error", async () => {
+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
+ mockGetConversation.mockResolvedValue(conv);
+ mockCreateMessage.mockResolvedValue({ id: "m1", content: "hello" });
+ mockUpdateConversationTitle.mockResolvedValue(undefined);
+ mockEnqueueTask.mockRejectedValueOnce("queue unavailable");
+
+ const res = await POST(
+ new NextRequest("http://localhost/api/conversations/c1/messages", {
+ method: "POST",
+ body: JSON.stringify({ content: "hello" }),
+ headers: { "Content-Type": "application/json" },
+ }),
+ withParams("c1")
+ );
+
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({
+ message: { id: "m1", content: "hello" },
+ task: null,
+ error: "Request failed",
+ });
+ });
+
it("passes workspaceId to getConversation", async () => {
const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };
mockGetConversation.mockResolvedValue(conv);
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.ts
index 31a6bed44..8b645efb6 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -251,7 +251,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
{
message: messageToResponse(message),
task: null,
- error: err instanceof Error ? err.message : "Unknown error",
+ error: err instanceof Error ? err.message : "Request failed",
},
500
);
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts
index ed1f44bda..61d67d8c9 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts
@@ -44,6 +44,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
return writeJSON(taskToResponse(task));
} catch (e: unknown) {
- return writeError(e instanceof Error ? e.message : "Unknown error", 400);
+ return writeError(e instanceof Error ? e.message : "Request failed", 400);
}
});
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts
index 02b5cc25b..1ca10473a 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts
@@ -36,6 +36,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
return writeJSON(taskToResponse(task));
} catch (e: unknown) {
- return writeError(e instanceof Error ? e.message : "Unknown error", 400);
+ return writeError(e instanceof Error ? e.message : "Request failed", 400);
}
});
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts
index 8d1981500..6928f9819 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts
@@ -27,6 +27,6 @@ export const POST = withAuth(async (_req, ctx) => {
}
return writeJSON(taskToResponse(task));
} catch (err: unknown) {
- return writeError(err instanceof Error ? err.message : "Unknown error", 400);
+ return writeError(err instanceof Error ? err.message : "Request failed", 400);
}
});
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts
index b5ec4a5f5..0aac0135f 100644
--- a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts
@@ -32,6 +32,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
return writeJSON(taskToResponse(task));
} catch (e: unknown) {
- return writeError(e instanceof Error ? e.message : "Unknown error", 400);
+ return writeError(e instanceof Error ? e.message : "Request failed", 400);
}
});
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.auth-order.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.auth-order.test.ts
index fe5f8d5bc..7efccd1e7 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.auth-order.test.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.auth-order.test.ts
@@ -39,7 +39,7 @@ vi.mock("@/lib/cache", () => ({
cached: vi.fn(),
throttled: vi.fn(),
}))
-vi.mock("@/lib/auth", () => ({ createAuth: vi.fn() }))
+vi.mock("@/lib/auth", () => ({ createAuth: vi.fn(), getAuth: vi.fn() }))
import { POST } from "./route"
diff --git a/src/web/src/app/api/issues/[id]/route.test.ts b/src/web/src/app/api/issues/[id]/route.test.ts
index ec8b04baf..5a01ebe9a 100644
--- a/src/web/src/app/api/issues/[id]/route.test.ts
+++ b/src/web/src/app/api/issues/[id]/route.test.ts
@@ -10,6 +10,9 @@ const mockListArtifactsByConversation = vi.fn();
const mockListComments = vi.fn();
const mockCreateComment = vi.fn();
const mockGetTask = vi.fn();
+const mockGetAgent = vi.fn();
+const mockCreateConversation = vi.fn();
+const mockEnqueueTask = vi.fn();
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -27,7 +30,10 @@ vi.mock("@alook/shared", async () => {
listIssueMessages: (...a: unknown[]) => mockListIssueMessages(...a),
updateIssue: (...a: unknown[]) => mockUpdateIssue(...a),
deleteIssue: (...a: unknown[]) => mockDeleteIssue(...a),
+ setLatestTask: vi.fn(),
},
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ conversation: { createConversation: (...a: unknown[]) => mockCreateConversation(...a) },
task: {
getTask: (...a: unknown[]) => mockGetTask(...a),
},
@@ -59,6 +65,7 @@ vi.mock("@/lib/middleware/workspace", () => ({
vi.mock("@/lib/api/responses", () => ({
issueToResponse: (i: any) => ({ id: i.id, status: i.status, conversation_id: i.conversationId }),
messageToResponse: (m: any) => ({ id: m.id, role: m.role, content: m.content }),
+ taskToResponse: (t: any) => ({ id: t.id, status: t.status }),
}));
vi.mock("@/lib/logger", () => ({
@@ -74,6 +81,7 @@ const mockCancelActiveTask = vi.fn();
const mockCancelTrace = vi.fn();
vi.mock("@/lib/services/task", () => ({
TaskService: class {
+ enqueueTask(...args: any[]) { return mockEnqueueTask(...args); }
cancelActiveTask(...args: any[]) { return mockCancelActiveTask(...args); }
cancelTrace(...args: any[]) { return mockCancelTrace(...args); }
},
@@ -116,6 +124,34 @@ describe("PATCH /api/issues/[id]", () => {
expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({ role: "event", content: "Issue status changed: todo -> in_progress" }));
expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({ type: "conversation.message", conversationId: "c1" }));
});
+
+ it("records a stable assignment failure when enqueue rejects with a non-Error", async () => {
+ mockGetIssue.mockResolvedValue({
+ id: "iss_1",
+ title: "Fix",
+ description: "Body",
+ status: "todo",
+ conversationId: null,
+ });
+ mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1" });
+ mockCreateConversation.mockResolvedValue({ id: "c1" });
+ mockUpdateIssue
+ .mockResolvedValueOnce({ id: "iss_1", status: "in_progress", conversationId: "c1" })
+ .mockResolvedValueOnce({ id: "iss_1", status: "todo", conversationId: "c1" });
+ mockCreateMessage.mockResolvedValue({ id: "m1", role: "event" });
+ mockEnqueueTask.mockRejectedValueOnce("queue unavailable");
+
+ const res = await PATCH(new NextRequest("http://localhost/api/issues/iss_1", {
+ method: "PATCH",
+ body: JSON.stringify({ agent_id: "ag_1" }),
+ }), { params: { id: "iss_1" } } as any);
+
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({ error: "failed to dispatch issue" });
+ expect(mockCreateMessage).toHaveBeenLastCalledWith({}, expect.objectContaining({
+ content: "Issue dispatch failed: reason unavailable",
+ }));
+ });
});
describe("POST /api/issues/[id]", () => {
diff --git a/src/web/src/app/api/issues/[id]/route.ts b/src/web/src/app/api/issues/[id]/route.ts
index 0976e8fd8..e6bba443b 100644
--- a/src/web/src/app/api/issues/[id]/route.ts
+++ b/src/web/src/app/api/issues/[id]/route.ts
@@ -128,7 +128,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
await queries.message.createMessage(db, {
conversationId: conversation.id,
role: "event",
- content: `Issue dispatch failed: ${taskErr instanceof Error ? taskErr.message : "unknown error"}`,
+ content: `Issue dispatch failed: ${taskErr instanceof Error ? taskErr.message : "reason unavailable"}`,
metadata: JSON.stringify({ issueId: existing.id, title: existing.title, event: "dispatch_failed" as const }),
});
return writeError(taskErr instanceof Error ? taskErr.message : "failed to dispatch issue", 500);
diff --git a/src/web/src/app/api/issues/route.test.ts b/src/web/src/app/api/issues/route.test.ts
index d342ea719..91d62cebc 100644
--- a/src/web/src/app/api/issues/route.test.ts
+++ b/src/web/src/app/api/issues/route.test.ts
@@ -158,4 +158,32 @@ describe("POST /api/issues", () => {
}),
);
});
+
+ it("records a stable dispatch failure when enqueue rejects with a non-Error", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1", runtimeId: "rt1" });
+ mockCreateConversation.mockResolvedValue({ id: "c1" });
+ mockCreateIssue.mockResolvedValue({
+ id: "iss_1",
+ agentId: "ag_1",
+ title: "Fix",
+ description: "Body",
+ status: "todo",
+ conversationId: "c1",
+ });
+ mockCreateMessage
+ .mockResolvedValueOnce({ id: "m1", content: "Issue created: Fix" })
+ .mockResolvedValueOnce({ id: "m2", content: "Issue dispatch failed: reason unavailable" });
+ mockEnqueueTask.mockRejectedValueOnce("queue unavailable");
+
+ const res = await POST(new NextRequest("http://localhost/api/issues", {
+ method: "POST",
+ body: JSON.stringify({ agent_id: "ag_1", title: "Fix", description: "Body" }),
+ }), {} as any);
+
+ expect(res.status).toBe(500);
+ expect(await res.json()).toEqual({ error: "failed to dispatch issue" });
+ expect(mockCreateMessage).toHaveBeenLastCalledWith({}, expect.objectContaining({
+ content: "Issue dispatch failed: reason unavailable",
+ }));
+ });
});
diff --git a/src/web/src/app/api/issues/route.ts b/src/web/src/app/api/issues/route.ts
index 014ca42a9..5f758d036 100644
--- a/src/web/src/app/api/issues/route.ts
+++ b/src/web/src/app/api/issues/route.ts
@@ -218,7 +218,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
await queries.message.createMessage(db, {
conversationId: conversation.id,
role: "event",
- content: `Issue dispatch failed: ${taskErr instanceof Error ? taskErr.message : "unknown error"}`,
+ content: `Issue dispatch failed: ${taskErr instanceof Error ? taskErr.message : "reason unavailable"}`,
metadata: JSON.stringify({ issueId: created.id, title: created.title, event: "dispatch_failed" as const }),
});
return writeError(taskErr instanceof Error ? taskErr.message : "failed to dispatch issue", 500);
diff --git a/src/web/src/app/api/tasks/[id]/retry/route.ts b/src/web/src/app/api/tasks/[id]/retry/route.ts
index b36916b53..8a42c8072 100644
--- a/src/web/src/app/api/tasks/[id]/retry/route.ts
+++ b/src/web/src/app/api/tasks/[id]/retry/route.ts
@@ -38,6 +38,6 @@ export const POST = withAuth(async (req, ctx) => {
broadcastToUser(ctx.userId, { type: "task.updated", taskId: newTask.id, agentId: newTask.agentId, status: "queued" }).catch(() => {});
return writeJSON(taskToResponse(newTask));
} catch (e: unknown) {
- return writeError(e instanceof Error ? e.message : "Unknown error", 400);
+ return writeError(e instanceof Error ? e.message : "Request failed", 400);
}
});
diff --git a/src/web/src/app/api/ws/token/route.test.ts b/src/web/src/app/api/ws/token/route.test.ts
index 285146a42..e8c378b68 100644
--- a/src/web/src/app/api/ws/token/route.test.ts
+++ b/src/web/src/app/api/ws/token/route.test.ts
@@ -8,7 +8,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
vi.mock("@/lib/auth", () => ({
- createAuth: vi.fn(() => ({
+ getAuth: vi.fn(() => ({
api: { getSession: (...a: unknown[]) => mockGetSession(...a) },
})),
}))
diff --git a/src/web/src/app/api/ws/token/route.ts b/src/web/src/app/api/ws/token/route.ts
index 61f43ed71..a4def4a62 100644
--- a/src/web/src/app/api/ws/token/route.ts
+++ b/src/web/src/app/api/ws/token/route.ts
@@ -1,10 +1,10 @@
import { NextRequest } from "next/server"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
import { DEV_WS_DO_URL } from "@alook/shared"
import { withEnv } from "@/lib/middleware/env"
export const GET = withEnv(async (req: NextRequest, ctx) => {
- const auth = createAuth(ctx.env)
+ const auth = getAuth(ctx.env)
const session = await auth.api.getSession({ headers: req.headers })
if (!session) return new Response("Unauthorized", { status: 401 })
diff --git a/src/web/src/app/auth/native/callback/route.ts b/src/web/src/app/auth/native/callback/route.ts
index 34926d4d9..86e93de39 100644
--- a/src/web/src/app/auth/native/callback/route.ts
+++ b/src/web/src/app/auth/native/callback/route.ts
@@ -1,5 +1,5 @@
import { createLogger, queries } from "@alook/shared";
-import { createAuth } from "@/lib/auth";
+import { getAuth } from "@/lib/auth";
import { getPrimaryDb } from "@/lib/db";
import { withEnv } from "@/lib/middleware/env";
import {
@@ -47,7 +47,7 @@ export const GET = withEnv(async (request, ctx) => {
}
try {
- const generated = await createAuth(ctx.env).api.generateOneTimeToken({
+ const generated = await getAuth(ctx.env).api.generateOneTimeToken({
headers: request.headers,
returnHeaders: true,
});
diff --git a/src/web/src/app/auth/native/start/route.ts b/src/web/src/app/auth/native/start/route.ts
index 0e17e8fe6..a8b4b23aa 100644
--- a/src/web/src/app/auth/native/start/route.ts
+++ b/src/web/src/app/auth/native/start/route.ts
@@ -1,5 +1,5 @@
import { createLogger, queries } from "@alook/shared";
-import { createAuth } from "@/lib/auth";
+import { getAuth } from "@/lib/auth";
import { getPrimaryDb } from "@/lib/db";
import { withEnv } from "@/lib/middleware/env";
import {
@@ -28,7 +28,7 @@ export const GET = withEnv(async (request, ctx) => {
if (!attempt) return nativeOauthErrorPage(410);
try {
- const result = await createAuth(ctx.env).api.signInSocial({
+ const result = await getAuth(ctx.env).api.signInSocial({
body: {
provider: attempt.provider,
disableRedirect: true,
diff --git a/src/web/src/app/c/QueryProvider.dom.test.ts b/src/web/src/app/c/QueryProvider.dom.test.ts
index b7dbf48b6..58af02249 100644
--- a/src/web/src/app/c/QueryProvider.dom.test.ts
+++ b/src/web/src/app/c/QueryProvider.dom.test.ts
@@ -15,12 +15,14 @@ const queryClient = vi.hoisted(() => ({
})),
}))
const createQueryClient = vi.hoisted(() => vi.fn(() => queryClient))
-const seedPersistedMessageProfiles = vi.hoisted(() => vi.fn())
const setReconcileScheduler = vi.hoisted(() => vi.fn())
const getAccountUnreadProjection = vi.hoisted(() => vi.fn(() => ({
setReconcileScheduler,
})))
const disposeAccountUnreadProjection = vi.hoisted(() => vi.fn())
+const registryCleanup = vi.hoisted(() => vi.fn(() => Promise.resolve()))
+const captureRestoredCollections = vi.hoisted(() => vi.fn())
+const restoreResult = vi.hoisted(() => ({ current: "success" as "success" | "error" }))
vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
vi.mock("@tanstack/react-query-persist-client", async () => {
@@ -29,11 +31,16 @@ vi.mock("@tanstack/react-query-persist-client", async () => {
PersistQueryClientProvider: ({
children,
onSuccess,
+ onError,
}: {
children: React.ReactNode
onSuccess: () => void
+ onError: () => void
}) => {
- useEffect(() => onSuccess(), [onSuccess])
+ useEffect(() => {
+ if (restoreResult.current === "success") onSuccess()
+ else onError()
+ }, [onError, onSuccess])
return children
},
}
@@ -45,7 +52,21 @@ vi.mock("@/lib/query-persister", () => ({
PERSIST_MAX_AGE_MS: 1,
shouldPersistQuery: vi.fn(() => false),
}))
-vi.mock("@/lib/community/profile-seed", () => ({ seedPersistedMessageProfiles }))
+vi.mock("@/lib/community-db/collections", () => ({
+ createCommunityDbRegistry: vi.fn(() => ({
+ id: "community-db",
+ captureRestoredCollections,
+ hasRestoredCollection: vi.fn(() => false),
+ cleanup: registryCleanup,
+ })),
+ registerCommunityDbRegistry: vi.fn(() => () => {}),
+}))
+vi.mock("@/lib/community-db/projections", () => ({
+ CommunityDbProvider: ({ children }: { children: React.ReactNode }) => children,
+}))
+vi.mock("@/lib/community-db/sync", () => ({
+ installCommunityDbSync: vi.fn(() => () => {}),
+}))
vi.mock("@/hooks/community/community-ws/read-state-reconciliation", () => ({
disposeAccountReadStateReconciliation: vi.fn(),
}))
@@ -63,38 +84,42 @@ beforeEach(() => {
useCommunityWsStore.setState({ activateProfileAccount: originalActivateProfileAccount })
useCommunityWsStore.getState().reset()
createQueryClient.mockClear()
- seedPersistedMessageProfiles.mockClear()
setReconcileScheduler.mockClear()
getAccountUnreadProjection.mockClear()
disposeAccountUnreadProjection.mockClear()
+ registryCleanup.mockClear()
+ captureRestoredCollections.mockClear()
+ restoreResult.current = "success"
queryClient.invalidateQueries.mockClear()
})
describe("QueryProvider profile account lifecycle", () => {
- it("does not activate the profile account while rendering", () => {
+ it("activates the restored account after render", async () => {
const store = useCommunityWsStore.getState()
store.activateProfileAccount("viewer-a")
const activateProfileAccountSpy = vi.fn(store.activateProfileAccount)
useCommunityWsStore.setState({ activateProfileAccount: activateProfileAccountSpy })
+ const observedViewerIds: Array<string | null> = []
+ function Probe() {
+ observedViewerIds.push(useCommunityWsStore.getState().profileViewerId)
+ return null
+ }
const renderer = render(React.createElement(
- React.StrictMode,
- null,
- React.createElement(
- QueryProvider,
- { userId: "viewer-a" },
- React.createElement("span", null, "content"),
- ),
+ QueryProvider,
+ { userId: "viewer-b" },
+ React.createElement(Probe),
))
- expect(activateProfileAccountSpy).not.toHaveBeenCalled()
+ expect(observedViewerIds).toEqual(["viewer-a"])
+ await act(async () => { await Promise.resolve() })
+ expect(activateProfileAccountSpy).toHaveBeenCalledWith("viewer-b")
act(() => renderer.unmount())
})
- it("restores persisted profiles against the already-active account epoch", async () => {
+ it("revalidates durable projections after restore", async () => {
const store = useCommunityWsStore.getState()
store.activateProfileAccount("viewer-b")
- const expectedSnapshot = store.beginProfileSnapshot()
const renderer = render(React.createElement(
QueryProvider,
@@ -103,7 +128,37 @@ describe("QueryProvider profile account lifecycle", () => {
))
await act(async () => { await Promise.resolve() })
- expect(seedPersistedMessageProfiles).toHaveBeenCalledWith(queryClient, expectedSnapshot)
+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: communityKeys.folders(),
+ exact: true,
+ refetchType: "active",
+ })
+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: communityKeys.dms(),
+ exact: true,
+ refetchType: "active",
+ })
+ act(() => renderer.unmount())
+ })
+
+ it("confirms the new viewer and empty canonical baseline after restore failure", async () => {
+ restoreResult.current = "error"
+ const store = useCommunityWsStore.getState()
+ store.activateProfileAccount("viewer-old")
+ const activateProfileAccountSpy = vi.fn(store.activateProfileAccount)
+ useCommunityWsStore.setState({ activateProfileAccount: activateProfileAccountSpy })
+
+ const renderer = render(React.createElement(
+ QueryProvider,
+ { userId: "viewer-new" },
+ React.createElement("span", null, "content"),
+ ))
+ await act(async () => { await Promise.resolve() })
+
+ expect(captureRestoredCollections).toHaveBeenCalledOnce()
+ expect(activateProfileAccountSpy).toHaveBeenCalledWith("viewer-new")
+ expect(useCommunityWsStore.getState().profileViewerId).toBe("viewer-new")
+ expect(queryClient.invalidateQueries).not.toHaveBeenCalled()
act(() => renderer.unmount())
})
@@ -145,4 +200,22 @@ describe("QueryProvider profile account lifecycle", () => {
expect(detailPredicate({ queryKey: communityKeys.server("__pending__") })).toBe(false)
act(() => renderer.unmount())
})
+
+ it("does not manually destroy collections while descendant live queries release", async () => {
+ vi.useFakeTimers()
+ try {
+ const renderer = render(React.createElement(
+ QueryProvider,
+ { userId: "viewer-d" },
+ React.createElement("span", null, "content"),
+ ))
+
+ act(() => renderer.unmount())
+ await act(async () => vi.runAllTimersAsync())
+
+ expect(registryCleanup).not.toHaveBeenCalled()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
})
diff --git a/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx b/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx
new file mode 100644
index 000000000..cc4ced7aa
--- /dev/null
+++ b/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx
@@ -0,0 +1,170 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import React from "react"
+import {
+ dehydrate,
+ QueryClient,
+ useQueryClient,
+} from "@tanstack/react-query"
+import type { PersistedClient, Persister } from "@tanstack/react-query-persist-client"
+import { act, render, screen, waitFor } from "@/test/react-dom-harness"
+import { communityKeys } from "@/lib/query-keys"
+import { PERSIST_BUSTER } from "@/lib/query-persister"
+import { CurrentUserProvider } from "@/contexts/community/current-user"
+import {
+ useCanonicalMessagesById,
+ useDmProjection,
+ useTrustedRestoredPrimary,
+} from "@/lib/community-db/projections"
+
+const persister = vi.hoisted(() => ({
+ persistClient: vi.fn(() => Promise.resolve()),
+ restoreClient: vi.fn(),
+ removeClient: vi.fn(() => Promise.resolve()),
+}))
+
+vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
+vi.mock("@/lib/query-persister", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/query-persister")>()
+ return {
+ ...actual,
+ createIdbPersister: vi.fn(() => persister as Persister),
+ }
+})
+
+import { QueryProvider } from "./QueryProvider"
+
+beforeEach(() => {
+ persister.persistClient.mockClear()
+ persister.restoreClient.mockReset()
+ persister.removeClient.mockClear()
+})
+
+describe("QueryProvider persistence ordering", () => {
+ it("hydrates canonical rows before collection preload can publish an empty snapshot", async () => {
+ const viewerId = "restore-order-viewer"
+ const message = {
+ id: "persisted-message",
+ channelId: "persisted-dm",
+ type: "chat" as const,
+ seq: 1,
+ createdAt: "2026-09-25T00:00:00.000Z",
+ content: "persisted canonical body",
+ }
+ const canonicalKey = communityKeys.communityDbCollection(viewerId, "messages")
+ const seedClient = new QueryClient()
+ seedClient.setQueryData(
+ communityKeys.communityDbCollection(viewerId, "categories"),
+ [],
+ { updatedAt: Date.now() - 60_000 },
+ )
+ seedClient.setQueryData(
+ communityKeys.communityDbCollection(viewerId, "channels"),
+ [{
+ id: "persisted-dm",
+ serverId: null,
+ categoryId: null,
+ name: "",
+ type: "dm",
+ parentChannelId: null,
+ parentMessageId: null,
+ creatorId: null,
+ position: 0,
+ archived: false,
+ muted: false,
+ unread: false,
+ tags: [],
+ pending: false,
+ lastMessageAt: null,
+ }],
+ { updatedAt: Date.now() - 60_000 },
+ )
+ seedClient.setQueryData(
+ communityKeys.communityDbCollection(viewerId, "channelMemberships"),
+ [
+ {
+ id: `persisted-dm:${viewerId}:access`,
+ channelId: "persisted-dm",
+ userId: viewerId,
+ relation: "access",
+ },
+ {
+ id: "persisted-dm:peer:access",
+ channelId: "persisted-dm",
+ userId: "peer",
+ relation: "access",
+ },
+ ],
+ { updatedAt: Date.now() - 60_000 },
+ )
+ seedClient.setQueryData(
+ communityKeys.communityDbCollection(viewerId, "profiles"),
+ [{
+ userId: "peer",
+ name: "Persisted peer",
+ discriminator: "0001",
+ avatar: "P",
+ avatarVersion: 0,
+ }],
+ { updatedAt: Date.now() - 60_000 },
+ )
+ seedClient.setQueryData(canonicalKey, [message], {
+ updatedAt: Date.now() - 60_000,
+ })
+ const persisted: PersistedClient = {
+ timestamp: Date.now(),
+ buster: PERSIST_BUSTER,
+ clientState: dehydrate(seedClient),
+ }
+ let resolveRestore!: (client: PersistedClient) => void
+ persister.restoreClient.mockReturnValue(new Promise((resolve) => {
+ resolveRestore = resolve
+ }))
+
+ const mounted = { client: null as QueryClient | null }
+ function Probe() {
+ mounted.client = useQueryClient()
+ const trustedRestoredPrimary = useTrustedRestoredPrimary()
+ const messages = useCanonicalMessagesById()
+ const dms = useDmProjection()
+ return React.createElement(
+ "output",
+ {
+ "data-testid": "canonical-message",
+ "data-trusted-restored-primary": String(trustedRestoredPrimary),
+ },
+ [messages?.get(message.id)?.content ?? "missing", dms?.[0]?.name ?? "missing-dm"].join("|"),
+ )
+ }
+
+ const renderer = render(
+ <QueryProvider userId={viewerId}>
+ <CurrentUserProvider initialUser={{
+ id: viewerId,
+ name: "Restored viewer",
+ email: "[email protected]",
+ avatar: "V",
+ avatarVersion: 0,
+ }}>
+ <Probe />
+ </CurrentUserProvider>
+ </QueryProvider>,
+ )
+
+ await waitFor(() => expect(persister.restoreClient).toHaveBeenCalledOnce())
+ expect(mounted.client?.getQueryState(canonicalKey)).toMatchObject({
+ data: undefined,
+ status: "pending",
+ })
+
+ await act(async () => resolveRestore(persisted))
+ await waitFor(() => {
+ expect(screen.getByTestId("canonical-message").textContent)
+ .toBe(`${message.content}|Persisted peer`)
+ })
+ expect(screen.getByTestId("canonical-message"))
+ .toHaveAttribute("data-trusted-restored-primary", "true")
+ expect(mounted.client?.getQueryData(canonicalKey)).toEqual([message])
+
+ act(() => renderer.unmount())
+ })
+})
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index 8765cbc61..a2c09efd0 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -1,6 +1,7 @@
"use client"
-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"
+import { useIsRestoring, type QueryClient } from "@tanstack/react-query"
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"
import { createQueryClient } from "@/lib/query-client"
@@ -13,7 +14,6 @@ import {
import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"
import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"
import { useCommunityWsStore } from "@/stores/community/ws"
-import { seedPersistedMessageProfiles } from "@/lib/community/profile-seed"
import {
disposeAccountUnreadProjection,
getAccountUnreadProjection,
@@ -22,7 +22,62 @@ import {
communityKeys,
isCommunityServerDetailQueryKey,
} from "@/lib/query-keys"
-import { installStructuralSnapshotProjection } from "@/hooks/community/use-structural-snapshot"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import { installCommunityDbSync } from "@/lib/community-db/sync"
+
+function createRestoreGate() {
+ let release!: () => void
+ const ready = new Promise<void>((resolve) => { release = resolve })
+ return { ready, release }
+}
+
+function CommunityDbRuntime({
+ children,
+ onRestoreComplete,
+ queryClient,
+ registry,
+}: {
+ children: ReactNode
+ onRestoreComplete: () => void
+ queryClient: QueryClient
+ registry: CommunityDbRegistry
+}) {
+ const isRestoring = useIsRestoring()
+ const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ useLayoutEffect(() => {
+ if (disposeTimer.current !== null) {
+ clearTimeout(disposeTimer.current)
+ disposeTimer.current = null
+ }
+ const unregisterCommunityDb = registerCommunityDbRegistry(registry)
+ return () => {
+ unregisterCommunityDb()
+ disposeTimer.current = setTimeout(() => {
+ disposeTimer.current = null
+ disposeReadCoordinator(queryClient)
+ disposeAccountReadStateReconciliation(queryClient)
+ disposeAccountUnreadProjection(queryClient)
+ }, 0)
+ }
+ }, [queryClient, registry])
+
+ useLayoutEffect(() => {
+ if (isRestoring) return
+ onRestoreComplete()
+ // A collection preload writes the queryFn result into TanStack Query. It
+ // must not run before persisted hydration, otherwise a fresh empty array
+ // outranks the older canonical rows on disk by dataUpdatedAt.
+ return installCommunityDbSync(queryClient, registry)
+ }, [isRestoring, onRestoreComplete, queryClient, registry])
+
+ return <CommunityDbProvider registry={registry}>{children}</CommunityDbProvider>
+}
/**
* Owns the TanStack QueryClient for the community subtree.
@@ -45,10 +100,11 @@ export function QueryProvider({
children: ReactNode
userId: string | null
}) {
- const [restoreProfileSnapshot] = useState(
- () => useCommunityWsStore.getState().beginProfileSnapshot(),
- )
const [queryClient] = useState(() => createQueryClient())
+ const [restoreGate] = useState(createRestoreGate)
+ const [communityDb] = useState(() => createCommunityDbRegistry(queryClient, userId, {
+ waitForRestore: restoreGate.ready,
+ }))
const unreadProjection = useMemo(
() => userId ? getAccountUnreadProjection(queryClient, userId) : null,
[queryClient, userId],
@@ -77,32 +133,48 @@ export function QueryProvider({
// id, so we don't need to reactively rebuild the persister mid-session.
const [persister] = useState(() => createIdbPersister(userId))
const isDev = process.env.NODE_ENV !== "production"
- const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
-
- useEffect(() => {
- if (disposeTimer.current !== null) {
- clearTimeout(disposeTimer.current)
- disposeTimer.current = null
- }
- return () => {
- disposeTimer.current = setTimeout(() => {
- disposeTimer.current = null
- disposeReadCoordinator(queryClient)
- disposeAccountReadStateReconciliation(queryClient)
- disposeAccountUnreadProjection(queryClient)
- }, 0)
+ const settleRestoredAccount = () => {
+ communityDb.captureRestoredCollections()
+ const profiles = useCommunityWsStore.getState()
+ if (profiles.profileViewerId !== userId) {
+ profiles.activateProfileAccount(userId)
}
- }, [queryClient])
-
- useEffect(
- () => installStructuralSnapshotProjection(queryClient, userId),
- [queryClient, userId],
- )
+ }
return (
<PersistQueryClientProvider
client={queryClient}
- onSuccess={() => seedPersistedMessageProfiles(queryClient, restoreProfileSnapshot)}
+ onSuccess={() => {
+ // `onSuccess` runs after hydrate and before `isRestoring` becomes
+ // false. Freeze which canonical collections came from that restore so
+ // later network results can never be misclassified as persisted.
+ settleRestoredAccount()
+ void Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: communityKeys.servers(),
+ exact: true,
+ refetchType: "active",
+ }),
+ queryClient.invalidateQueries({
+ queryKey: communityKeys.folders(),
+ exact: true,
+ refetchType: "active",
+ }),
+ queryClient.invalidateQueries({
+ queryKey: communityKeys.dms(),
+ exact: true,
+ refetchType: "active",
+ }),
+ queryClient.invalidateQueries({
+ predicate: ({ queryKey }) => isCommunityServerDetailQueryKey(queryKey),
+ refetchType: "active",
+ }),
+ ])
+ }}
+ // A failed IndexedDB read still completes the identity handoff. The
+ // account gate remains visible until this atomically clears any previous
+ // viewer state, then the new account mounts against an empty live cache.
+ onError={settleRestoredAccount}
persistOptions={{
persister,
maxAge: PERSIST_MAX_AGE_MS,
@@ -110,9 +182,9 @@ export function QueryProvider({
dehydrateOptions: {
shouldDehydrateQuery: (query) => {
// Two-stage filter:
- // 1. Key must be in the persisted allowlist (only message queries
- // are persisted — presence/servers/etc. refetch on mount).
- // 2. For message queries, `pages[0]` must be a trusted
+ // 1. Key must be in the persisted allowlist (canonical collection
+ // rows plus the retained raw read closure).
+ // 2. For raw message queries, `pages[0]` must be a trusted
// newest-tail shape. A since-mode or older-only envelope has
// no `hasMore` flag on page 0 → the next mount reads
// `hasMoreOlder ?? hasMore ?? false` as false and silently
@@ -124,8 +196,14 @@ export function QueryProvider({
},
}}
>
- {children}
- {isDev ? <ReactQueryDevtools initialIsOpen={false} /> : null}
+ <CommunityDbRuntime
+ onRestoreComplete={restoreGate.release}
+ queryClient={queryClient}
+ registry={communityDb}
+ >
+ {children}
+ {isDev ? <ReactQueryDevtools initialIsOpen={false} /> : null}
+ </CommunityDbRuntime>
</PersistQueryClientProvider>
)
}
diff --git a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts b/src/web/src/app/c/channels/[serverId]/page.dom.test.ts
index 8bbbda29a..129d7dde8 100644
--- a/src/web/src/app/c/channels/[serverId]/page.dom.test.ts
+++ b/src/web/src/app/c/channels/[serverId]/page.dom.test.ts
@@ -57,7 +57,7 @@ describe("ServerDefaultPage checkpoint route contract", () => {
expect(rendered.container).toBeEmptyDOMElement()
})
- it("keeps metadata loading neutral, then redirects only when the target is known", async () => {
+ it("keeps cold or incomplete detail on the root, then redirects only when canonical detail is known", async () => {
mocks.breakpoint.current = "desktop"
mocks.server.current = null
const rendered = render(createElement(ServerDefaultPage))
@@ -86,6 +86,28 @@ describe("ServerDefaultPage checkpoint route contract", () => {
expect(screen.getByRole("main", { name: "Loading server" })).toBeInTheDocument()
})
+ it("does not enqueue the same landing redirect again while restored detail reconciles", async () => {
+ mocks.breakpoint.current = "desktop"
+ mocks.lastChannel.current = "channel_2"
+ const rendered = render(createElement(ServerDefaultPage))
+
+ mocks.server.current = {
+ categories: [{ channels: [{ id: "channel_1" }, { id: "channel_2" }] }],
+ }
+ rendered.rerender(createElement(ServerDefaultPage))
+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith(
+ "/c/channels/server_1/channel_2",
+ )
+
+ mocks.lastChannel.current = null
+ mocks.server.current = { categories: [{ channels: [{ id: "channel_3" }] }] }
+ rendered.rerender(createElement(ServerDefaultPage))
+ expect(mocks.replace).toHaveBeenNthCalledWith(
+ 2,
+ "/c/channels/server_1/channel_3",
+ )
+ })
+
it("falls back to the first top-level channel on desktop", async () => {
mocks.breakpoint.current = "desktop"
diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsx
index 86a9ebad2..c23c58aa4 100644
--- a/src/web/src/app/c/channels/[serverId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/page.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useEffect } from "react"
+import { useEffect, useRef } from "react"
import { useParams, useRouter, useSearchParams } from "next/navigation"
import { ServerLandingPendingFrame } from "@/components/community/shell/server-landing-pending-frame"
import { useServer } from "@/hooks/community/use-servers"
@@ -14,6 +14,7 @@ export default function ServerDefaultPage() {
const serverId = decodeURIComponent(params.serverId)
const { server: currentServer } = useServer(serverId)
const breakpoint = useBreakpoint()
+ const replacingHrefRef = useRef<string | null>(null)
useEffect(() => {
if (breakpoint !== "desktop" || !currentServer) return
@@ -26,7 +27,10 @@ export default function ServerDefaultPage() {
)
if (target) {
const search = searchParams.toString()
- router.replace(`/c/channels/${serverId}/${target}${search ? `?${search}` : ""}`)
+ const href = `/c/channels/${serverId}/${target}${search ? `?${search}` : ""}`
+ if (replacingHrefRef.current === href) return
+ replacingHrefRef.current = href
+ router.replace(href)
}
}, [breakpoint, currentServer, serverId, router, searchParams])
diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
index 307714125..2d2ad3146 100644
--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts
@@ -23,12 +23,10 @@ const mocks = vi.hoisted(() => ({
serverDetails: new Map<string, {
categories: Array<{ channels: Array<{ id: string; pending?: boolean }> }>
}>(),
- structuralSnapshot: { current: null as null | {
- servers: Array<{ id: string; channels: Array<{ id: string }> }>
- } },
lastChannels: new Map<string, string>(),
serverListSuccess: { current: true },
serverListFetching: { current: false },
+ serverListLiveAuthoritative: { current: true },
serverAccessRevoked: { current: false },
queryClient: { getQueryData: vi.fn(), fetchQuery: vi.fn() },
}))
@@ -128,15 +126,9 @@ vi.mock("@/hooks/community/use-servers", () => ({
servers: mocks.servers.current,
isSuccess: mocks.serverListSuccess.current,
isFetching: mocks.serverListFetching.current,
+ isLiveAuthoritative: mocks.serverListLiveAuthoritative.current,
}),
}))
-vi.mock("@/hooks/community/use-structural-snapshot", () => ({
- useStructuralSnapshot: () => mocks.structuralSnapshot.current,
- structuralHintServer: () => null,
- hasStructuralServerTree: (server: { channels?: unknown[] } | null) => (
- (server?.channels?.length ?? 0) > 0
- ),
-}))
vi.mock("@/hooks/community/use-server-members", () => ({
useServerMembers: () => ({
members: [], loading: false, loadingMore: false, hasMore: false, total: 0,
@@ -259,10 +251,10 @@ describe("ServerLayout deletion routing", () => {
mocks.useServer.mockClear()
mocks.servers.current = []
mocks.serverDetails.clear()
- mocks.structuralSnapshot.current = null
mocks.lastChannels.clear()
mocks.serverListSuccess.current = true
mocks.serverListFetching.current = false
+ mocks.serverListLiveAuthoritative.current = true
mocks.serverAccessRevoked.current = false
mocks.queryClient.getQueryData.mockImplementation((key: unknown[]) => {
if (key.length === 2 && key[1] === "servers") {
@@ -290,6 +282,7 @@ describe("ServerLayout deletion routing", () => {
it("passes the authenticated leaf and target-specific revoke facts to generic eject", () => {
mocks.serverListSuccess.current = false
mocks.serverListFetching.current = true
+ mocks.serverListLiveAuthoritative.current = false
mocks.serverAccessRevoked.current = true
mocks.runEject.mockImplementation((args: {
replace: (destination: string) => void
@@ -312,6 +305,38 @@ describe("ServerLayout deletion routing", () => {
expect(mocks.registerRoute).toHaveBeenCalledWith("missing-server", mocks.routeToken)
})
+ it("keeps restored absence non-authoritative until the current client settles a live list", () => {
+ mocks.serverListLiveAuthoritative.current = false
+ const rendered = render(createElement(ServerLayout, null, createElement("div")))
+
+ expect(mocks.runEject).toHaveBeenLastCalledWith(expect.objectContaining({
+ isSuccess: false,
+ isFetching: false,
+ }))
+ expect(mocks.replace).not.toHaveBeenCalled()
+
+ mocks.serverListLiveAuthoritative.current = true
+ rendered.rerender(createElement(ServerLayout, null, createElement("div")))
+
+ expect(mocks.runEject).toHaveBeenLastCalledWith(expect.objectContaining({
+ isSuccess: true,
+ isFetching: false,
+ }))
+ })
+
+ it("keeps a failed list non-authoritative even after this client had a live snapshot", () => {
+ mocks.serverListSuccess.current = false
+ mocks.serverListLiveAuthoritative.current = true
+
+ render(createElement(ServerLayout, null, createElement("div")))
+
+ expect(mocks.runEject).toHaveBeenLastCalledWith(expect.objectContaining({
+ isSuccess: false,
+ isFetching: false,
+ }))
+ expect(mocks.replace).not.toHaveBeenCalled()
+ })
+
it("suppresses optimistic/list eject and replaces directly to the survivor Channel leaf", async () => {
mocks.servers.current = [
{ id: "missing-server" },
@@ -378,34 +403,6 @@ describe("ServerLayout deletion routing", () => {
expect(mocks.navigatePath).not.toHaveBeenCalled()
})
- it("resolves a survivor leaf from the structural snapshot without waiting for a fetch", async () => {
- mocks.servers.current = [
- { id: "missing-server" },
- { id: "surviving-server" },
- ]
- mocks.structuralSnapshot.current = {
- servers: [{
- id: "surviving-server",
- channels: [{ id: "channel-structural" }],
- }],
- }
- render(createElement(ServerLayout, null, createElement("div")))
-
- await act(async () => mocks.deleteServerAction.current?.())
- const callbacks = mocks.deleteServer.mock.calls[0]![1] as {
- onSuccess: (needsNavigation?: boolean) => void
- }
- mocks.servers.current = [{ id: "surviving-server" }]
- await act(async () => callbacks.onSuccess())
-
- expect(mocks.queryClient.fetchQuery).not.toHaveBeenCalled()
- expect(mocks.claimNavigation).toHaveBeenCalledWith(
- "missing-server",
- mocks.routeToken,
- "/c/channels/surviving-server/channel-structural",
- )
- })
-
it("keeps an already committed safe route without resolving or navigating", async () => {
mocks.servers.current = [
{ id: "missing-server" },
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 910356873..486930d16 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -15,7 +15,7 @@ import {
serverRootHref,
} from "@/lib/community/community-route"
import { useBreakpoint } from "@/hooks/use-mobile"
-import { ChannelSidebarScope } from "@/components/community/channels/channel-sidebar-tree-owner"
+import { ChannelSidebarRevealBoundary } from "@/components/community/channels/channel-sidebar-tree-owner"
import { ChannelRoute } from "@/components/community/channels/channel-route"
import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"
import { ServerSettings } from "@/components/community/settings/server-settings"
@@ -81,10 +81,10 @@ import {
useRevokeInvite,
} from "@/hooks/community/mutations"
import {
- hasStructuralServerTree,
- structuralHintServer,
- useStructuralSnapshot,
-} from "@/hooks/community/use-structural-snapshot"
+ useCanonicalProfilesByUserId,
+ useOptionalCommunityDbRegistry,
+ useTrustedRestoredPrimary,
+} from "@/lib/community-db/projections"
export default function ServerLayout({ children }: { children: ReactNode }) {
const params = useParams<{ serverId: string; channelId?: string }>()
@@ -109,6 +109,8 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const router = useRouter()
const queryClient = useQueryClient()
+ const communityDb = useOptionalCommunityDbRegistry()
+ const trustedRestoredPrimary = useTrustedRestoredPrimary()
const cancelPendingNavigation = useCallback(() => {
useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()
}, [])
@@ -116,24 +118,24 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const serverAccessRevoked = useCommunityWsStore(
(state) => state.revokedServerIds.has(serverId),
)
- const structuralSnapshot = useStructuralSnapshot(currentUser.id)
- const structuralServer = useMemo(
- () => structuralHintServer(structuralSnapshot, serverId),
- [serverId, structuralSnapshot],
- )
- const { server: currentServer } = useServer(ownerDeleteRouteProtected ? null : serverId)
- const structuralTreeReady = hasStructuralServerTree(structuralServer)
+ const {
+ server: currentServer,
+ data: authoritativeServer,
+ } = useServer(ownerDeleteRouteProtected ? null : serverId)
const sidebarCategories = useMemo(
- () => currentServer?.categories ?? (structuralTreeReady ? structuralServer?.categoriesView : undefined) ?? [],
- [currentServer, structuralServer, structuralTreeReady],
+ () => currentServer?.categories ?? [],
+ [currentServer],
)
- const sidebarHintOnly = !currentServer && structuralTreeReady
+ const sidebarHintOnly = Boolean(currentServer && !authoritativeServer)
const membersHook = useServerMembers(currentServer ? serverId : null)
- const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)
+ const profilesByUserId = useCanonicalProfilesByUserId()
const enrichedMembers = useMemo(
() =>
membersHook.members.map((m) => {
- const profile = readCommunityProfile(profilesByUserId.get(m.userId), m.userId)
+ const canonical = profilesByUserId.get(m.userId)
+ const profile = canonical
+ ? readCommunityProfile(canonical, m.userId)
+ : { ...m, presence: m.status }
return {
...m,
name: profile.name,
@@ -194,10 +196,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const serversList = useServers()
const serverDestination = useCallback(async (id: string) => {
- const structural = structuralSnapshot?.servers.find((server) => server.id === id)
const lastChannel = getLastChannel(id)
let detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(id))
- if (!detail && !lastChannel && !hasStructuralServerTree(structural)) {
+ const canonicalChannelIds = communityDb
+ ? Array.from(communityDb.collections.channels.values())
+ .filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending)
+ .map((channel) => channel.id)
+ : []
+ if (!detail && !lastChannel && canonicalChannelIds.length === 0) {
try {
detail = await queryClient.fetchQuery({
queryKey: communityKeys.server(id),
@@ -213,9 +219,9 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
category.channels
.filter((channel) => !channel.pending)
.map((channel) => channel.id),
- ) ?? structural?.channels.map((channel) => channel.id) ?? []
+ ) ?? canonicalChannelIds
return pickServerLandingHref(id, channelIds, lastChannel)
- }, [queryClient, structuralSnapshot])
+ }, [communityDb, queryClient])
// Mutations
const createChannelMut = useCreateChannel()
@@ -287,7 +293,11 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
servers: serversList.servers,
// A target-specific 403/404 is already definitive even if revoking the
// target advanced the access epoch and retired an in-flight list read.
- isSuccess: serverAccessRevoked || serversList.isSuccess,
+ // A restored list is renderable but its absence is not an access
+ // verdict. Only a live list confirmed for this QueryClient + auth
+ // generation may drive the generic eject path.
+ isSuccess: serverAccessRevoked
+ || (serversList.isSuccess && serversList.isLiveAuthoritative),
isFetching: serverAccessRevoked ? false : serversList.isFetching,
ownerDeleteRouteProtected: isOwnerServerDeleteRouteProtected(serverId),
consumeVoluntaryLeave,
@@ -300,7 +310,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
router.replace(destination)
},
})
- }, [cancelPendingNavigation, currentUser.id, pathname, serverAccessRevoked, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])
+ }, [cancelPendingNavigation, currentUser.id, pathname, serverAccessRevoked, serverId, serversList.isLiveAuthoritative, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])
// Reset the guard when the URL changes to a NEW server id — otherwise
// navigating server → dangling-server → server would leave the ref
// latched and skip the eject.
@@ -374,7 +384,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
: { ...channel, unread: forumSidebar.parentUnread[channel.id] },
),
})), [forumSidebar.parentUnread, sidebarCategories])
- const sidebarDataReady = Boolean(currentServer) || structuralTreeReady
+ const sidebarDataReady = Boolean(currentServer)
const channelTreeScopeKey = `server:${serverId}`
const setActiveChannel = useCallback((id: string) => {
@@ -470,14 +480,12 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
}, [])
const channelProps = useMemo(() => ({
- serverName: currentServer?.name ?? structuralServer?.name ?? "",
- serverIcon: currentServer?.icon ?? structuralServer?.icon ?? null,
+ serverName: currentServer?.name ?? "",
+ serverIcon: currentServer?.icon ?? null,
official: currentServer?.official ?? false,
activeChannel: currentChannelMeta?.parentChannelId ?? currentChannelId ?? "",
isAdmin,
currentUserId: currentUser.id,
- loading: (!currentServer && !structuralServer)
- || (!sidebarHintOnly && forumSidebar.isLoading),
setActiveChannel,
prefetchChannel,
forumThreadsByParent,
@@ -500,9 +508,10 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
invitePopoverOpen,
onInvitePopoverOpenChange: sidebarHintOnly ? undefined : setInvitePopoverOpen,
}), [
- currentServer, structuralServer, sidebarHintOnly, currentChannelMeta?.parentChannelId,
+ currentServer, sidebarHintOnly,
+ currentChannelMeta?.parentChannelId,
currentChannelId, isAdmin, currentUser.id, setActiveChannel, prefetchChannel,
- forumThreadsByParent, forumSidebar.isLoading, activeForumThreadId, setActiveForumThread,
+ forumThreadsByParent, activeForumThreadId, setActiveForumThread,
onSidebarOpenSettings, onBlockedCreate, mutedChannels,
onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel,
onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar,
@@ -519,14 +528,26 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const closeSettings = () => { setServerSettingsOpen(false); setSettingsSection("overview") }
const sidebar = useCallback((opts: { noHeader?: boolean } = {}) => (
- <ChannelSidebarScope
+ <ChannelSidebarRevealBoundary
+ key={channelTreeScopeKey}
scopeKey={channelTreeScopeKey}
- categories={sidebarDataReady ? categories : null}
+ categories={categories}
+ primaryReady={sidebarDataReady}
+ forumProjectionMissing={!forumSidebar.projectionReady}
+ trustedRestoredPrimary={trustedRestoredPrimary}
targetServerId={serverId}
{...channelProps}
{...opts}
/>
- ), [categories, channelProps, channelTreeScopeKey, serverId, sidebarDataReady])
+ ), [
+ categories,
+ channelProps,
+ channelTreeScopeKey,
+ forumSidebar.projectionReady,
+ serverId,
+ sidebarDataReady,
+ trustedRestoredPrimary,
+ ])
const serverSettingsDialog = (
<Dialog open={serverSettingsOpen && !!currentServer && isAdmin} onOpenChange={(o) => { if (!o) closeSettings() }}>
diff --git a/src/web/src/app/c/community-layout-client.tsx b/src/web/src/app/c/community-layout-client.tsx
new file mode 100644
index 000000000..a24b4ab5c
--- /dev/null
+++ b/src/web/src/app/c/community-layout-client.tsx
@@ -0,0 +1,54 @@
+"use client"
+
+import { useEffect, type ReactNode } from "react"
+import { usePathname, useRouter } from "next/navigation"
+import { CommunityShell } from "./community-shell"
+import { SignupTracker } from "@/components/signup-tracker"
+import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"
+import { resolveCommunityModulePlan } from "@/lib/community/community-route"
+import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary"
+import { AuthenticatedNativeOauthCleanup } from "@/components/authenticated-native-oauth-cleanup"
+import {
+ clearCommunityColdEntryAttempts,
+ retireCommunityColdEntryAttempt,
+} from "@/lib/community/last-community-route"
+import type { CurrentUser } from "@/contexts/community/current-user"
+
+function isPublicCommunityPath(pathname: string): boolean {
+ return resolveCommunityModulePlan(pathname).route === "public-invite"
+}
+
+export function CommunityLayoutClient({
+ children,
+ currentUser,
+}: {
+ children: ReactNode
+ currentUser: CurrentUser | null
+}) {
+ const router = useRouter()
+ const pathname = usePathname()
+ const isPublic = isPublicCommunityPath(pathname)
+
+ useEffect(() => {
+ if (!isPublic && !currentUser) router.replace("/sign-in")
+ }, [currentUser, isPublic, router])
+
+ useEffect(() => {
+ if (!currentUser) {
+ clearCommunityColdEntryAttempts()
+ return
+ }
+ retireCommunityColdEntryAttempt(currentUser.id, pathname)
+ }, [currentUser, pathname])
+
+ if (isPublic) return <><SignupTracker />{children}</>
+ if (!currentUser) return <CommunitySessionPendingFrame pathname={pathname} />
+
+ return (
+ <AuthenticatedContextMenuBoundary>
+ <AuthenticatedNativeOauthCleanup />
+ <SignupTracker redirectTo="/c/me/machines" />
+ <CommunityShell currentUser={currentUser}>{children}</CommunityShell>
+ </AuthenticatedContextMenuBoundary>
+ )
+}
diff --git a/src/web/src/app/c/community-shell.identity.dom.test.ts b/src/web/src/app/c/community-shell.identity.dom.test.ts
index fc12f9117..b444c3007 100644
--- a/src/web/src/app/c/community-shell.identity.dom.test.ts
+++ b/src/web/src/app/c/community-shell.identity.dom.test.ts
@@ -29,6 +29,10 @@ vi.mock("@/contexts/community/current-user", () => ({
}))
vi.mock("@/hooks/community/use-community-ws", () => ({ useCommunityWs: vi.fn() }))
vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSettings }))
+vi.mock("@/hooks/community/use-account-attention", () => ({
+ useAccountAttention: vi.fn(),
+ useAccountAttentionScopeHydration: vi.fn(),
+}))
vi.mock("@/lib/community/profile-seed", () => ({
apiFetchProfiles: (...args: unknown[]) => apiFetchProfiles(...args),
}))
@@ -42,6 +46,22 @@ vi.mock("@/components/community/onboarding/community-onboarding-form", () => ({
vi.mock("@/components/community/shell/community-ws-reconnect-overlay", () => ({
CommunityWsReconnectBoundary: ({ children }: { children: React.ReactNode }) => children,
}))
+vi.mock("@/components/community/shell/community-restore-bootstrap", () => ({
+ CommunityRestoreBoundary: ({ children }: { children: React.ReactNode }) => React.createElement(
+ "div",
+ { "data-testid": "restore-boundary" },
+ children,
+ ),
+}))
+vi.mock("next/navigation", () => ({
+ usePathname: () => "/c/me",
+}))
+vi.mock("@/components/community/shell/community-session-pending-frame", () => ({
+ CommunitySessionPendingFrame: ({ pathname }: { pathname: string }) => React.createElement(
+ "div",
+ { "data-testid": "session-pending", "data-pathname": pathname },
+ ),
+}))
vi.mock("@/components/community/shell/owner-server-delete-route-guard", () => ({
OwnerServerDeleteRouteGuard: () => null,
}))
@@ -59,6 +79,25 @@ beforeEach(() => {
})
describe("CommunityShell identity boundary", () => {
+ it("keeps restore lifecycle ownership outside the account activation frame", () => {
+ const activateProfileAccount = useCommunityWsStore.getState().activateProfileAccount
+ useCommunityWsStore.setState({
+ profileViewerId: null,
+ activateProfileAccount: vi.fn(() => 0),
+ })
+ const renderer = render(React.createElement(
+ CommunityShell,
+ { currentUser: activeUser },
+ React.createElement("span", null, "content"),
+ ))
+
+ const pending = renderer.getByTestId("session-pending")
+ expect(renderer.getByTestId("restore-boundary").contains(pending)).toBe(true)
+
+ act(() => renderer.unmount())
+ useCommunityWsStore.setState({ activateProfileAccount })
+ })
+
it("remounts the in-memory query boundary when the signed-in user changes", () => {
const renderer = render(React.createElement(
CommunityShell,
@@ -80,23 +119,21 @@ describe("CommunityShell identity boundary", () => {
})
it("does not mount a new account subtree against the previous account profile state", () => {
- const renderedProfileStates: Array<{ viewerId: string | null; profileNames: string[] }> = []
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined)
+ const renderedProfileStates: Array<{ viewerId: string | null; presenceIds: string[] }> = []
function ProfileStateProbe() {
const viewerId = useCommunityWsStore((state) => state.profileViewerId)
- const profiles = useCommunityWsStore((state) => state.profilesByUserId)
+ const presence = useCommunityWsStore((state) => state.presenceByUserId)
renderedProfileStates.push({
viewerId,
- profileNames: [...profiles.values()].map((profile) => profile.name),
+ presenceIds: [...presence.keys()],
})
return null
}
const profiles = useCommunityWsStore.getState()
profiles.activateProfileAccount("user-a")
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
- id: "user-a",
- identityAbout: { name: "Previous account" },
- }])
+ profiles.setPresence("user-a", "online")
const accountAEpoch = useCommunityWsStore.getState().profileAccountEpoch
const renderer = render(React.createElement(
@@ -117,13 +154,15 @@ describe("CommunityShell identity boundary", () => {
expect(renderedProfileStates.length).toBeGreaterThan(0)
expect(renderedProfileStates).toEqual(
- renderedProfileStates.map(() => ({ viewerId: "user-b", profileNames: [] })),
+ renderedProfileStates.map(() => ({ viewerId: "user-b", presenceIds: [] })),
)
expect(useCommunityWsStore.getState()).toMatchObject({
profileViewerId: "user-b",
profileAccountEpoch: accountAEpoch + 1,
})
+ expect(consoleError.mock.calls.flat().join("\n")).not.toContain("while rendering a different component")
act(() => renderer.unmount())
+ consoleError.mockRestore()
})
it("reactivates a cleared account without a render-phase update in StrictMode", () => {
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsx
index ceedb4bd0..4810a6b5e 100644
--- a/src/web/src/app/c/community-shell.tsx
+++ b/src/web/src/app/c/community-shell.tsx
@@ -1,6 +1,7 @@
"use client"
import { useEffect, useLayoutEffect, type ReactNode } from "react"
+import { usePathname } from "next/navigation"
import { apiFetchProfiles } from "@/lib/community/profile-seed"
import { QueryProvider } from "./QueryProvider"
import {
@@ -11,11 +12,17 @@ import {
import { useCommunityWs } from "@/hooks/community/use-community-ws"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
import { useNativeSystemNotifications } from "@/hooks/community/use-native-system-notifications"
+import {
+ useAccountAttention,
+ useAccountAttentionScopeHydration,
+} from "@/hooks/community/use-account-attention"
import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"
import { CommunityOnboardingForm } from "@/components/community/onboarding/community-onboarding-form"
import { CommunityWsReconnectBoundary } from "@/components/community/shell/community-ws-reconnect-overlay"
import { useCommunityWsStore } from "@/stores/community/ws"
import { OwnerServerDeleteRouteGuard } from "@/components/community/shell/owner-server-delete-route-guard"
+import { CommunityRestoreBoundary } from "@/components/community/shell/community-restore-bootstrap"
+import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"
/**
* Client wrapper that provides the QueryClient, CurrentUser, and the
@@ -38,13 +45,15 @@ export function CommunityShell({
children: ReactNode
}) {
return (
- <ProfileAccountBoundary viewerId={currentUser.id}>
- <QueryProvider key={currentUser.id} userId={currentUser.id}>
- <CurrentUserProvider initialUser={currentUser}>
- <CommunityBootstrap>{children}</CommunityBootstrap>
- </CurrentUserProvider>
- </QueryProvider>
- </ProfileAccountBoundary>
+ <QueryProvider key={currentUser.id} userId={currentUser.id}>
+ <CommunityRestoreBoundary>
+ <ProfileAccountBoundary viewerId={currentUser.id}>
+ <CurrentUserProvider initialUser={currentUser}>
+ <CommunityBootstrap>{children}</CommunityBootstrap>
+ </CurrentUserProvider>
+ </ProfileAccountBoundary>
+ </CommunityRestoreBoundary>
+ </QueryProvider>
)
}
@@ -56,15 +65,15 @@ function ProfileAccountBoundary({
viewerId: string
}) {
const activeViewerId = useCommunityWsStore((state) => state.profileViewerId)
-
+ const pathname = usePathname()
useLayoutEffect(() => {
if (activeViewerId !== viewerId) {
useCommunityWsStore.getState().activateProfileAccount(viewerId)
}
}, [activeViewerId, viewerId])
-
- if (activeViewerId !== viewerId) return null
- return children
+ return activeViewerId === viewerId
+ ? children
+ : <CommunitySessionPendingFrame pathname={pathname} />
}
/**
@@ -79,6 +88,8 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {
const currentUser = useCurrentUser()
useNotificationSettings()
+ useAccountAttention()
+ useAccountAttentionScopeHydration()
useNativeSystemNotifications(currentUser.id)
// Wire the WS handler once for the whole community subtree. `viewerUserId`
// powers the `me` flag on incoming reactions — passing null would leave that
diff --git a/src/web/src/app/c/layout.dom.test.ts b/src/web/src/app/c/layout.dom.test.ts
index 21deb4753..37c12b4ed 100644
--- a/src/web/src/app/c/layout.dom.test.ts
+++ b/src/web/src/app/c/layout.dom.test.ts
@@ -9,14 +9,12 @@ const mocks = vi.hoisted(() => ({
replace: vi.fn(),
retireAttempt: vi.fn(),
clearAttempts: vi.fn(),
- session: { data: null as null | { user: { id: string; name: string; email: string; image: string | null } }, isPending: true },
}))
vi.mock("next/navigation", () => ({
usePathname: () => mocks.pathname,
useRouter: () => ({ replace: mocks.replace }),
}))
-vi.mock("@/lib/auth-client", () => ({ useSession: () => mocks.session }))
vi.mock("@/lib/community/last-community-route", () => ({
retireCommunityColdEntryAttempt: mocks.retireAttempt,
clearCommunityColdEntryAttempts: mocks.clearAttempts,
@@ -39,12 +37,20 @@ vi.mock("@/components/signup-tracker", () => ({
vi.mock("@/components/authenticated-native-oauth-cleanup", () => ({
AuthenticatedNativeOauthCleanup: () => createElement("div", { "data-testid": "native-oauth-cleanup" }),
}))
-import CommunityLayout from "./layout"
+import { CommunityLayoutClient } from "./community-layout-client"
-function renderLayout() {
+const user = {
+ id: "u1",
+ name: "Ada",
+ email: "[email protected]",
+ avatar: "A",
+ avatarVersion: 0,
+}
+
+function renderLayout(currentUser: typeof user | null = null) {
return render(createElement(
- CommunityLayout,
- null,
+ CommunityLayoutClient,
+ { currentUser },
createElement("div", { "data-testid": "child" }),
))
}
@@ -52,23 +58,12 @@ function renderLayout() {
describe("CommunityLayout session boundary", () => {
beforeEach(() => {
mocks.pathname = "/c/me"
- mocks.session = { data: null, isPending: true }
mocks.replace.mockClear()
mocks.retireAttempt.mockClear()
mocks.clearAttempts.mockClear()
})
- it("keeps a stable frame while identity is pending", () => {
- renderLayout()
- expect(screen.getByTestId("session-pending")).toHaveAttribute("data-pathname", "/c/me")
- expect(screen.queryByTestId("community-shell")).not.toBeInTheDocument()
- expect(screen.queryByTestId("native-oauth-cleanup")).not.toBeInTheDocument()
- expect(mocks.retireAttempt).not.toHaveBeenCalled()
- expect(mocks.clearAttempts).not.toHaveBeenCalled()
- })
-
it("keeps the frame mounted while a signed-out redirect commits", () => {
- mocks.session = { data: null, isPending: false }
renderLayout()
expect(mocks.replace).toHaveBeenCalledWith("/sign-in")
expect(mocks.clearAttempts).toHaveBeenCalledTimes(1)
@@ -76,12 +71,8 @@ describe("CommunityLayout session boundary", () => {
expect(screen.queryByTestId("native-oauth-cleanup")).not.toBeInTheDocument()
})
- it("constructs the shell only after identity is available", () => {
- mocks.session = {
- data: { user: { id: "u1", name: "Ada", email: "[email protected]", image: null } },
- isPending: false,
- }
- renderLayout()
+ it("constructs the shell from the server-seeded identity on its first render", () => {
+ renderLayout(user)
expect(JSON.parse(screen.getByTestId("community-shell").dataset.currentUser!)).toMatchObject({
id: "u1",
name: "Ada",
@@ -112,16 +103,27 @@ describe("CommunityLayout session boundary", () => {
expect(screen.queryByTestId("child")).not.toBeInTheDocument()
})
- it("wires the Me verifier to canonical fetch-in-flight state", () => {
+ it("keeps authenticated session resolution in the server layout", () => {
+ const source = readFileSync(resolve(
+ process.cwd(),
+ process.cwd().endsWith("/src/web") ? "" : "src/web",
+ "src/app/c/layout.tsx",
+ ), "utf8")
+ expect(source).toContain("await getSession()")
+ expect(source).toContain("<CommunityLayoutClient currentUser={currentUser}>")
+ expect(source).not.toContain("useSession")
+ })
+
+ it("keeps background DM refresh out of route loading semantics", () => {
const source = readFileSync(resolve(
process.cwd(),
process.cwd().endsWith("/src/web") ? "" : "src/web",
"src/app/c/me/layout.tsx",
), "utf8")
expect(source).toMatch(/isPending:\s*dmsPending/)
- expect(source).toMatch(/isFetching:\s*dmsFetching/)
- expect(source).toContain("const canonicalDmsUnsettled = dmsPending || dmsFetching")
- expect(source).toContain("useDmRouteVerification(params.dmId, rawDms, canonicalDmsUnsettled)")
+ expect(source).not.toMatch(/isFetching:\s*dmsFetching/)
+ expect(source).toContain("const canonicalDmsUnsettled = dmsPending")
+ expect(source).toContain("useDmRouteVerification(params.dmId, dms, canonicalDmsUnsettled)")
})
it("keeps the daemon update controller inside the authenticated Community query cache", () => {
diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsx
index 8a3d0bb2c..18d196c58 100644
--- a/src/web/src/app/c/layout.tsx
+++ b/src/web/src/app/c/layout.tsx
@@ -1,75 +1,23 @@
-"use client"
-
-import { useEffect } from "react"
-import { usePathname, useRouter } from "next/navigation"
-import { useSession } from "@/lib/auth-client"
-import { CommunityShell } from "./community-shell"
+import type { ReactNode } from "react"
+import { getSession } from "@/lib/session"
import { avatarInitial } from "@/lib/community/avatar"
-import { SignupTracker } from "@/components/signup-tracker"
-import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"
-import { resolveCommunityModulePlan } from "@/lib/community/community-route"
-import { AuthenticatedContextMenuBoundary } from "@/components/authenticated-context-menu-boundary"
-import { AuthenticatedNativeOauthCleanup } from "@/components/authenticated-native-oauth-cleanup"
-import {
- clearCommunityColdEntryAttempts,
- retireCommunityColdEntryAttempt,
-} from "@/lib/community/last-community-route"
-
-// The invite landing page is preview-first: a logged-out visitor must be able
-// to see it (and only hit the login wall on Join). It's a standalone
-// full-screen page that doesn't use CommunityShell (which requires a
-// logged-in user), so it's exempt from this layout's session gate AND the
-// shell — its own middleware exemption keeps the server side public. Keep the
-// client bypass exact so malformed invite descendants do not inherit it.
-function isPublicCommunityPath(pathname: string): boolean {
- return resolveCommunityModulePlan(pathname).route === "public-invite"
-}
-
-export default function CommunityLayout({
- children,
-}: {
- children: React.ReactNode
-}) {
- const router = useRouter()
- const pathname = usePathname()
- const isPublic = isPublicCommunityPath(pathname)
- const { data: session, isPending } = useSession()
- const sessionUserId = session?.user.id
-
- useEffect(() => {
- if (!isPublic && !isPending && !session) {
- router.replace("/sign-in")
- }
- }, [isPublic, isPending, session, router])
-
- useEffect(() => {
- if (isPending) return
- if (!sessionUserId) {
- clearCommunityColdEntryAttempts()
- return
- }
- retireCommunityColdEntryAttempt(sessionUserId, pathname)
- }, [isPending, pathname, sessionUserId])
-
- // Public community pages (invite landing) render standalone — no session
- // gate, no CommunityShell (a logged-out visitor has no currentUser).
- if (isPublic) return <><SignupTracker />{children}</>
-
- if (isPending || !session) return <CommunitySessionPendingFrame pathname={pathname} />
-
- const currentUser = {
- id: session.user.id,
- name: session.user.name,
- email: session.user.email,
- avatar: session.user.image || avatarInitial(session.user.name),
- avatarVersion: 0,
- }
+import { CommunityLayoutClient } from "./community-layout-client"
+
+export default async function CommunityLayout({ children }: { children: ReactNode }) {
+ const session = await getSession()
+ const currentUser = session
+ ? {
+ id: session.user.id,
+ name: session.user.name,
+ email: session.user.email,
+ avatar: session.user.image || avatarInitial(session.user.name),
+ avatarVersion: 0,
+ }
+ : null
return (
- <AuthenticatedContextMenuBoundary>
- <AuthenticatedNativeOauthCleanup />
- <SignupTracker redirectTo="/c/me/machines" />
- <CommunityShell currentUser={currentUser}>{children}</CommunityShell>
- </AuthenticatedContextMenuBoundary>
+ <CommunityLayoutClient currentUser={currentUser}>
+ {children}
+ </CommunityLayoutClient>
)
}
diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.ts
index d8e8cb564..9d54c7814 100644
--- a/src/web/src/app/c/me/[dmId]/page.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.test.ts
@@ -6,7 +6,8 @@ describe("DM page loading ownership", () => {
const source = readFileSync(new URL("./page.tsx", import.meta.url), "utf8")
expect(source).toContain("fullFramePending: !hasDm && dmsLoading")
expect(source).toContain("notFound: !hasDm && !dmsLoading")
- expect(source).toContain("messageBodyLoading: hasDm && (")
+ expect(source).toContain("messageBodyLoading: hasDm && messagesLoading")
+ expect(source).not.toContain("currentChannelMatches")
expect(source).not.toContain("readSnapshotFetching ||\n messagesLoading")
expect(source).toContain("waitForAnchor: true")
expect(source).toContain("if (navigationBlocked)")
@@ -28,6 +29,12 @@ describe("DM page loading ownership", () => {
expect(source).not.toContain("<DmHeaderSkeleton")
})
+ it("uses the cache-first DM projection as the header and composer identity", () => {
+ const source = readFileSync(new URL("./page.tsx", import.meta.url), "utf8")
+ expect(source).toContain("dms.find((candidate) => candidate.id === dmId) ?? null")
+ expect(source).not.toContain("profilesByUserId.get(raw.userId)")
+ })
+
it("owns lazy channel-directory state and retry inside the keyed DM view", () => {
const source = readFileSync(new URL("./page.tsx", import.meta.url), "utf8")
expect(source).toContain("return <DmView key={params.dmId} />")
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 3b8f68c1c..5e47f6372 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -18,12 +18,10 @@ import type { FileAttachment, ImagePreview } from "@/lib/community/models/messag
import type { OpenProfile } from "@/components/community/social/profile-types"
import {
useCommunityStore,
- useCurrentChannelId,
useUiHandlers,
useTypingUsersForScope,
useTypingNamesForScope,
} from "@/stores/community"
-import { useCommunityWsStore } from "@/stores/community/ws"
import { tid } from "@/lib/community/testids"
import { readCommunityProfile } from "@/lib/community/profile-read"
import { makeUserNameResolver } from "@/lib/community/display-name"
@@ -31,6 +29,7 @@ import { useDms } from "@/hooks/community/use-dms"
import { useFriends } from "@/hooks/community/use-friends"
import { useDmMessages } from "@/hooks/community/use-messages"
import { useDmReadStateSnapshot } from "@/hooks/community/use-dm-read-state"
+import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"
import { useDmWatermark } from "@/hooks/community/use-dm-watermark"
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import { toChannelRefCandidate } from "@/lib/community/channel-ref-extension"
@@ -57,6 +56,10 @@ import { useNotificationSettings } from "@/hooks/community/use-notification-sett
import { useSetChannelNotif } from "@/hooks/community/mutations"
import { toastApiError } from "@/lib/api/client"
import { displayReplyContent } from "@/lib/community/reply-content"
+import {
+ useCanonicalProfilesByUserId,
+ useReadStateProjection,
+} from "@/lib/community-db/projections"
// Thin re-mount wrapper — same reason as the server-side channel view: the
// dynamic segment reuses the same component instance across DM switches, so
@@ -69,21 +72,16 @@ export default function DmPage() {
function resolveDmLoadingOwnership({
hasDm,
dmsLoading,
- currentChannelMatches,
messagesLoading,
}: {
hasDm: boolean
dmsLoading: boolean
- currentChannelMatches: boolean
messagesLoading: boolean
}) {
return {
fullFramePending: !hasDm && dmsLoading,
notFound: !hasDm && !dmsLoading,
- messageBodyLoading: hasDm && (
- !currentChannelMatches ||
- messagesLoading
- ),
+ messageBodyLoading: hasDm && messagesLoading,
}
}
@@ -92,7 +90,6 @@ function DmView() {
const dmId = params.dmId
const bp = useBreakpoint()
const currentUser = useCurrentUser()
- const currentChannelId = useCurrentChannelId()
const uiHandlers = useUiHandlers()
const notifications = useNotificationSettings()
const setNotification = useSetChannelNotif()
@@ -104,14 +101,17 @@ function DmView() {
const dms = dmsQuery.dms
const dmsLoading = dmsQuery.isLoading
const { friends: rawFriends, blocked } = useFriends()
- const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)
+ const profilesByUserId = useCanonicalProfilesByUserId()
// Enrich with presence — the Composer @-picker uses `f.status` to render
// the avatar presence dot; without this enrichment every avatar shows offline.
const friends = useMemo(
() =>
rawFriends.map((f) => {
const userId = f.userId ?? f.id
- const profile = readCommunityProfile(profilesByUserId.get(userId), userId)
+ const canonical = profilesByUserId.get(userId)
+ const profile = canonical
+ ? readCommunityProfile(canonical, userId)
+ : { ...f, presence: f.status }
return {
...f,
name: profile.name,
@@ -128,8 +128,9 @@ function DmView() {
// Frozen-once snapshot of the viewer's DM read pointer — the anchor for
// the "New" divider AND the initial-page mode. Mirrors the channel-view
// wiring so both surfaces open with the same anchor-window UX.
+ const canonicalReadSnapshot = useReadStateProjection(dmId)
const { snapshot: readSnapshot, isFetching: readSnapshotFetching } =
- useDmReadStateSnapshot(dmId)
+ useDmReadStateSnapshot(dmId, canonicalReadSnapshot)
// Anchor the initial page on the viewer's read pointer. Pass `undefined`
// (not `null`) while the snapshot resolves — the hook's initialPageParam
@@ -151,6 +152,7 @@ function DmView() {
isError: messagesError,
refetch: refetchMessages,
navigationBlocked,
+ anchorReconciled,
} = useDmMessages(dmId, {
lastReadMessageId: readSnapshotFetching
? undefined
@@ -231,26 +233,13 @@ function DmView() {
// inputs aren't guaranteed to agree on every commit).
const { newDividerBefore, anchorFound } = useMemo(() => {
if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
- const lastId = readSnapshot.lastReadMessageId
- // First-visit case: viewer never opened this DM (no read-state row
- // yet). The inbox surfaces the DM as unread, so the whole loaded
- // window is unread from the viewer's perspective — anchor the
- // divider on the first non-self message so the user lands centered
- // on "here's what you missed" instead of the bottom. No anchor id to
- // find — trivially "in cache".
- if (!lastId) {
- for (const m of messages) {
- if (m.authorId !== currentUser.id) return { newDividerBefore: m.id, anchorFound: true }
- }
- return { newDividerBefore: undefined, anchorFound: true }
- }
- const idx = messages.findIndex((m) => m.id === lastId)
- if (idx === -1) return { newDividerBefore: undefined, anchorFound: false }
- for (let i = idx + 1; i < messages.length; i++) {
- if (messages[i].authorId !== currentUser.id) return { newDividerBefore: messages[i].id, anchorFound: true }
- }
- return { newDividerBefore: undefined, anchorFound: true }
- }, [messages, readSnapshot, currentUser.id])
+ return resolveMessageReadProjection({
+ messages,
+ lastReadMessageId: readSnapshot.lastReadMessageId,
+ viewerUserId: currentUser.id,
+ anchorReconciled,
+ })
+ }, [anchorReconciled, messages, readSnapshot, currentUser.id])
// Gates `<MessageList>`'s mount-time scroll action until the anchor is
// actually present in the loaded `messages`.
@@ -324,22 +313,7 @@ function DmView() {
setReplyTo(null)
}, [dmId])
- const dm = useMemo(() => {
- const raw = dms.find((d) => d.id === dmId) ?? null
- if (!raw) return null
- const profile = readCommunityProfile(
- profilesByUserId.get(raw.userId),
- raw.userId,
- )
- return {
- ...raw,
- name: profile.name,
- discriminator: profile.discriminator,
- avatar: profile.avatar,
- avatarVersion: profile.avatarVersion,
- status: profile.presence,
- }
- }, [dms, dmId, profilesByUserId])
+ const dm = useMemo(() => dms.find((candidate) => candidate.id === dmId) ?? null, [dms, dmId])
const openProfile: OpenProfile = (name, e, discriminator, userId) => {
uiHandlers.openProfile?.(name, e, discriminator, userId)
@@ -445,7 +419,6 @@ function DmView() {
const loadingOwnership = resolveDmLoadingOwnership({
hasDm: !!dm,
dmsLoading,
- currentChannelMatches: currentChannelId === dmId,
messagesLoading,
})
diff --git a/src/web/src/app/c/me/friends/page.tsx b/src/web/src/app/c/me/friends/page.tsx
index dddaba1d1..f671615b3 100644
--- a/src/web/src/app/c/me/friends/page.tsx
+++ b/src/web/src/app/c/me/friends/page.tsx
@@ -6,7 +6,7 @@ import { useMemo } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useFriends } from "@/hooks/community/use-friends"
import { useUiHandlers } from "@/stores/community"
-import { useCommunityWsStore } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
useSendFriendRequest,
@@ -28,12 +28,15 @@ export default function MeFriendsPage() {
const activeTab = searchParams.get("tab") === "new" ? "new" : "all"
const { friends: rawFriends, pending, blocked, isLoading } = useFriends()
const uiHandlers = useUiHandlers()
- const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)
+ const profilesByUserId = useCanonicalProfilesByUserId()
const friends = useMemo(
() =>
rawFriends.map((f) => {
const userId = f.userId ?? f.id
- const profile = readCommunityProfile(profilesByUserId.get(userId), userId)
+ const canonical = profilesByUserId.get(userId)
+ const profile = canonical
+ ? readCommunityProfile(canonical, userId)
+ : { ...f, presence: f.status }
return {
...f,
name: profile.name,
diff --git a/src/web/src/app/c/me/layout.route-memory.dom.test.ts b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
index 683d33b66..230078529 100644
--- a/src/web/src/app/c/me/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
@@ -71,7 +71,7 @@ vi.mock("@/stores/community", () => {
}
})
vi.mock("@/hooks/community/use-dms", () => ({
- useDms: () => ({ dms: [], isLoading: false, isPending: false, isFetching: false }),
+ useDms: () => ({ dms: [], isLoading: false, isPending: false }),
}))
vi.mock("@/hooks/community/use-dm-route-verification", () => ({
useDmRouteVerification: () => ({ status: mocks.dmStatus, retry: vi.fn(), retrying: false }),
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index b96efd381..3a37a6d3a 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -15,10 +15,7 @@ import { useCommunityStore, useCurrentChannelId } from "@/stores/community"
import { useDms } from "@/hooks/community/use-dms"
import { useDmRouteVerification } from "@/hooks/community/use-dm-route-verification"
import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
-import { actionableIncomingRequests } from "@/lib/community/friend-requests"
-import { useFriendRequestActionState } from "@/hooks/community/use-friend-request-action-state"
-import { useCommunityWsStore } from "@/stores/community/ws"
-import { readCommunityProfile } from "@/lib/community/profile-read"
+import { useInboxUnreads } from "@/hooks/community/use-inbox"
import { useCurrentUser } from "@/contexts/community/current-user"
import {
clearLastMeLocation,
@@ -46,38 +43,14 @@ export default function MeLayout({ children }: { children: ReactNode }) {
? "/c/me"
: `/c/me/${selectedSegments.join("/")}`
const {
- dms: rawDms,
+ dms,
isLoading: dmsLoading,
isPending: dmsPending,
- isFetching: dmsFetching,
} = useDms()
- const canonicalDmsUnsettled = dmsPending || dmsFetching
- const dmRouteVerification = useDmRouteVerification(params.dmId, rawDms, canonicalDmsUnsettled)
- const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)
- const dms = useMemo(
- () =>
- rawDms.map((d) => {
- const profile = readCommunityProfile(profilesByUserId.get(d.userId), d.userId)
- return {
- ...d,
- name: profile.name,
- discriminator: profile.discriminator,
- avatar: profile.avatar,
- avatarVersion: profile.avatarVersion,
- status: profile.presence,
- }
- }),
- [profilesByUserId, rawDms],
- )
- const { blocked, pending } = useFriends()
- const incomingFriendRequests = useMemo(
- () => actionableIncomingRequests(pending),
- [pending],
- )
- const friendRequestCount = useFriendRequestActionState({
- rows: incomingFriendRequests,
- surface: "friends",
- }).items.length
+ const canonicalDmsUnsettled = dmsPending
+ const dmRouteVerification = useDmRouteVerification(params.dmId, dms, canonicalDmsUnsettled)
+ const { blocked } = useFriends()
+ const friendRequestCount = useInboxUnreads().friendRequests.length
const currentChannelId = useCurrentChannelId()
const cancelPendingNavigation = useCallback(() => {
useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()
diff --git a/src/web/src/app/c/me/page.dom.test.ts b/src/web/src/app/c/me/page.dom.test.ts
index 1555eb64a..027c39995 100644
--- a/src/web/src/app/c/me/page.dom.test.ts
+++ b/src/web/src/app/c/me/page.dom.test.ts
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
breakpoint: "unknown" as "unknown" | "desktop" | "mobile",
lastLeaf: null as string | null,
onboarding: null as { status: "active"; stage: "harness" } | null,
+ ownerDeleteRootLanding: false,
replace: vi.fn(),
}))
@@ -18,6 +19,9 @@ vi.mock("@/lib/community/last-me-location", () => ({
getLastMeLeaf: () => mocks.lastLeaf,
pickMeLandingLocation: (leaf: string | null) => `/c/me/${leaf ?? "friends"}`,
}))
+vi.mock("@/lib/community/eject-server", () => ({
+ isOwnerServerDeleteMeRootLanding: () => mocks.ownerDeleteRootLanding,
+}))
vi.mock("@/components/community/shell/community-pending-frame", () => ({
CommunityPendingFrame: ({ href }: { href: string }) => createElement("div", {
"data-testid": "pending-frame",
@@ -32,6 +36,7 @@ describe("MeListPage", () => {
mocks.breakpoint = "unknown"
mocks.lastLeaf = null
mocks.onboarding = null
+ mocks.ownerDeleteRootLanding = false
mocks.replace.mockClear()
})
@@ -58,6 +63,14 @@ describe("MeListPage", () => {
expect(screen.getByTestId("pending-frame")).toHaveAttribute("data-href", "/c/me/friends")
})
+ it("keeps an explicit owner-delete landing on the canonical root", () => {
+ mocks.breakpoint = "desktop"
+ mocks.ownerDeleteRootLanding = true
+ const rendered = render(createElement(MeListPage))
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(rendered.container).toBeEmptyDOMElement()
+ })
+
it("keeps desktop on the canonical root while onboarding is active", () => {
mocks.breakpoint = "desktop"
mocks.onboarding = { status: "active", stage: "harness" }
diff --git a/src/web/src/app/c/me/page.tsx b/src/web/src/app/c/me/page.tsx
index 06fa51c33..0ad751545 100644
--- a/src/web/src/app/c/me/page.tsx
+++ b/src/web/src/app/c/me/page.tsx
@@ -6,12 +6,15 @@ import { useBreakpoint } from "@/hooks/use-mobile"
import { CommunityPendingFrame } from "@/components/community/shell/community-pending-frame"
import { useCommunityOnboarding } from "@/lib/community-onboarding"
import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"
+import { isOwnerServerDeleteMeRootLanding } from "@/lib/community/eject-server"
export default function MeListPage() {
const router = useRouter()
const breakpoint = useBreakpoint()
const onboarding = useCommunityOnboarding()
- const destination = breakpoint === "desktop" && !onboarding
+ const destination = breakpoint === "desktop"
+ && !onboarding
+ && !isOwnerServerDeleteMeRootLanding()
? pickMeLandingLocation(getLastMeLeaf())
: null
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index 5a949a81b..38bd965d3 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -9,6 +9,23 @@
@custom-variant dark (&:is(.dark *));
+@media (min-width: 640px) {
+ html[data-community-shell-layout] [data-slot="community-shell-root"] [data-slot="resizable-panel-group"][data-testid="community-shell"] > [data-slot="resizable-panel"][data-testid="sidebar"] {
+ flex-basis: var(--community-shell-prepaint-sidebar-width) !important;
+ flex-grow: 0 !important;
+ flex-shrink: 0 !important;
+ }
+
+ html[data-community-shell-layout] [data-slot="community-shell-root"] [data-slot="resizable-panel-group"][data-testid="community-shell"] > [data-slot="resizable-panel"][data-testid="main"] {
+ flex-basis: 0 !important;
+ flex-grow: 1 !important;
+ }
+
+ html[data-community-shell-layout] [data-slot="community-shell-root"] [data-slot="community-user-bar-overlay"] {
+ --community-desktop-user-bar-width: var(--community-shell-prepaint-user-bar-width) !important;
+ }
+}
+
@theme inline {
--text-base: 0.9375rem;
--text-base--line-height: 1.6;
@@ -474,14 +491,6 @@ body.driver-active .community-ws-reconnect-overlay * {
--border: oklch(0.86 0.01 80);
--input: oklch(0.86 0.01 80);
--ring: oklch(0.55 0.03 230);
- --initial-position-aurora-cyan: oklch(0.76 0.17 205);
- --initial-position-aurora-blue: oklch(0.67 0.18 250);
- --initial-position-aurora-violet: oklch(0.67 0.19 292);
- --initial-position-aurora-magenta: oklch(0.72 0.18 333);
- --initial-position-aurora-opacity: 0.62;
- --initial-position-aurora-bloom-opacity: 0.58;
- --initial-position-aurora-glint-opacity: 0.82;
- --initial-position-aurora-reduced-opacity: 0.45;
--chart-1: oklch(0.85 0.01 80);
--chart-2: oklch(0.55 0.01 60);
--chart-3: oklch(0.44 0.01 60);
@@ -538,14 +547,6 @@ body.driver-active .community-ws-reconnect-overlay * {
--border: oklch(1 0.005 80 / 10%);
--input: oklch(1 0.005 80 / 15%);
--ring: oklch(0.55 0.01 60);
- --initial-position-aurora-cyan: oklch(0.78 0.18 205);
- --initial-position-aurora-blue: oklch(0.67 0.2 252);
- --initial-position-aurora-violet: oklch(0.7 0.2 294);
- --initial-position-aurora-magenta: oklch(0.74 0.19 333);
- --initial-position-aurora-opacity: 0.82;
- --initial-position-aurora-bloom-opacity: 0.72;
- --initial-position-aurora-glint-opacity: 0.95;
- --initial-position-aurora-reduced-opacity: 0.6;
--chart-1: oklch(0.85 0.01 80);
--chart-2: oklch(0.55 0.01 60);
--chart-3: oklch(0.44 0.01 60);
diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsx
index 7feb3a814..34a791622 100644
--- a/src/web/src/app/layout.tsx
+++ b/src/web/src/app/layout.tsx
@@ -8,6 +8,7 @@ import { MockNetworkBanner } from "@/components/mock-network-banner";
import { TauriThemeSync } from "@/components/tauri-theme-sync";
import { ThemeColorSync } from "@/components/theme-color-sync";
import { siteMetadata, siteStructuredData, siteViewport } from "@/lib/seo/site-metadata";
+import { communityShellLayoutBootstrapScript } from "@/components/community/shell/shell-frame-geometry";
import { caveat, dmMono, dmSans, instrumentSerif, literata, vt323 } from "./fonts";
import "./globals.css";
@@ -26,6 +27,7 @@ export default function RootLayout({
suppressHydrationWarning
>
<head>
+ <script dangerouslySetInnerHTML={{ __html: communityShellLayoutBootstrapScript }} />
<link rel="manifest" href="/manifest.json" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
diff --git a/src/web/src/components/canvas/active-tasks-float.tsx b/src/web/src/components/canvas/active-tasks-float.tsx
index 2ec8c4c62..1e260f604 100644
--- a/src/web/src/components/canvas/active-tasks-float.tsx
+++ b/src/web/src/components/canvas/active-tasks-float.tsx
@@ -49,7 +49,7 @@ function TaskRow({
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 leading-tight">
<span className="text-sm font-medium truncate">
- {task.agent?.name ?? "Unknown"}
+ {task.agent?.name ?? "Agent unavailable"}
</span>
<span className="text-xs text-muted-foreground shrink-0">
#{task.channel}
diff --git a/src/web/src/components/canvas/upcoming-events-float.tsx b/src/web/src/components/canvas/upcoming-events-float.tsx
index 59b8fc857..62e4cc0f7 100644
--- a/src/web/src/components/canvas/upcoming-events-float.tsx
+++ b/src/web/src/components/canvas/upcoming-events-float.tsx
@@ -63,7 +63,7 @@ export function UpcomingEventsFloat() {
const agent = agentMap.get(agentId);
agentSummaries.push({
agentId,
- agentName: agent?.name ?? "Unknown",
+ agentName: agent?.name ?? "Agent unavailable",
avatarUrl: agent?.avatar_url ?? null,
count: eventCount,
});
diff --git a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts b/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts
index a5a9f818f..1ef4a9534 100644
--- a/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-activity-modal.dom.test.ts
@@ -52,8 +52,8 @@ vi.mock("@/components/avatar", () => ({
AgentAvatar: (props: Record<string, unknown>) => React.createElement("agent-avatar", props),
}))
-vi.mock("@/stores/community/ws", () => ({
- useCommunityProfile: (botId: string | undefined) => {
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalCommunityProfile: (botId: string | undefined) => {
profileHook(botId)
return { presence: "online" }
},
diff --git a/src/web/src/components/community/bots/bot-activity-modal.tsx b/src/web/src/components/community/bots/bot-activity-modal.tsx
index 9a8dd1cc9..955ec58e9 100644
--- a/src/web/src/components/community/bots/bot-activity-modal.tsx
+++ b/src/web/src/components/community/bots/bot-activity-modal.tsx
@@ -3,7 +3,7 @@
import { useLayoutEffect, useMemo, useRef, useEffect } from "react"
import { AgentAvatar } from "@/components/avatar"
import { CommunitySheet } from "@/components/community/shell/community-sheet"
-import { useCommunityProfile } from "@/stores/community/ws"
+import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import {
useBotAuditLog,
type AuditEvent,
@@ -43,7 +43,7 @@ export function BotActivityModal({
// presence). A viewer with a broken WS wouldn't receive events either, but
// the daemon-side signal is what determines whether new rows are actually
// being produced right now.
- const profile = useCommunityProfile(bot?.id)
+ const profile = useCanonicalCommunityProfile(bot?.id)
const online = profile?.presence === "online"
const {
events,
diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsx
index 019d47c77..cd55f8913 100644
--- a/src/web/src/components/community/bots/bot-activity-row.tsx
+++ b/src/web/src/components/community/bots/bot-activity-row.tsx
@@ -194,8 +194,8 @@ function RowBody({ event }: { event: AuditEvent }) {
senderHandle?: string
reason?: "unread" | "mention"
} | null
- const sender = p?.senderHandle ?? "@unknown"
- const channel = p?.channel ?? "/unknown"
+ const sender = p?.senderHandle ?? "Sender unavailable"
+ const channel = p?.channel ?? "Conversation unavailable"
const seqLabel = p?.seq != null ? `#${p.seq}` : ""
const verb = p?.reason === "mention" ? "Mentioned by" : "Woken by"
const detail = `${verb} ${sender} in ${channel}${seqLabel ? ` ${seqLabel}` : ""}`
diff --git a/src/web/src/components/community/bots/bot-list-card.dom.test.ts b/src/web/src/components/community/bots/bot-list-card.dom.test.ts
index ce9dccedc..5679fbd49 100644
--- a/src/web/src/components/community/bots/bot-list-card.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-card.dom.test.ts
@@ -34,8 +34,8 @@ vi.mock("@/hooks/community/use-bots", () => ({
vi.mock("@/hooks/community/mutations", () => ({
useCreateOrGetDm: () => ({ mutateAsync: vi.fn() }),
}))
-vi.mock("@/stores/community/ws", () => ({
- useProfilesByUserId: () => new Map(),
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalProfilesByUserId: () => new Map(),
}))
function passthrough(name: string) {
diff --git a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
index 719240bc8..1f4a8e3a1 100644
--- a/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.dom.test.ts
@@ -96,8 +96,8 @@ vi.mock("@/hooks/community/use-machines", () => ({
return { machines: mocks.machines, isLoading: mocks.machinesLoading }
},
}))
-vi.mock("@/stores/community/ws", () => ({
- useProfilesByUserId: () => {
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalProfilesByUserId: () => {
mocks.hookOrder.push("profiles")
return new Map([...mocks.online].map((id) => [id, { id, presence: "online" }]))
},
@@ -228,7 +228,7 @@ describe("useBotListController", () => {
"const searchParams = useSearchParams()",
"const botsQuery = useBots()",
"const { machines, isLoading: machinesLoading } = useMachines()",
- "const profilesByUserId = useProfilesByUserId()",
+ "const profilesByUserId = useCanonicalProfilesByUserId()",
"const [createOpen",
"const [editingBot",
"const [editOpen",
@@ -317,7 +317,7 @@ describe("useBotListController", () => {
"unknown-a",
"unknown-b",
])
- expect(latest.machineName("gone")).toBe("Unknown machine")
+ expect(latest.machineName("gone")).toBe("Machine unavailable")
})
it("projects plan inventory and blocks create at owned capacity with recovery copy", () => {
diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.ts
index 60f4a8dfe..6df7420f5 100644
--- a/src/web/src/components/community/bots/bot-list-controller.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.ts
@@ -17,7 +17,7 @@ import {
type BotSummary,
} from "@/hooks/community/use-bots"
import { useCreateOrGetDm } from "@/hooks/community/mutations"
-import { useProfilesByUserId } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import {
advanceCommunityOnboarding,
readCommunityOnboardingState,
@@ -42,7 +42,7 @@ export function useBotListController(): BotListController {
window.history.pushState(null, "", `${next.pathname}${next.search}${next.hash}`)
}
const { machines, isLoading: machinesLoading } = useMachines()
- const profilesByUserId = useProfilesByUserId()
+ const profilesByUserId = useCanonicalProfilesByUserId()
const [createOpen, setCreateOpen] = useState(false)
const [editingBot, setEditingBot] = useState<BotSummary | null>(null)
const [editOpen, setEditOpen] = useState(false)
@@ -163,7 +163,7 @@ export function useBotListController(): BotListController {
const machineName = (id: string): string => {
const machine = machines.find((item) => item.id === id)
- if (!machine) return "Unknown machine"
+ if (!machine) return "Machine unavailable"
return resolveMachineName(machine)
}
diff --git a/src/web/src/components/community/bots/bot-quota-summary.tsx b/src/web/src/components/community/bots/bot-quota-summary.tsx
index 15dc5344b..4bb72a9ae 100644
--- a/src/web/src/components/community/bots/bot-quota-summary.tsx
+++ b/src/web/src/components/community/bots/bot-quota-summary.tsx
@@ -89,7 +89,7 @@ function productLabel(limit: QuotaLimit): string {
function modelLabel(limit: QuotaLimit): string | null {
const model = limit.bucket.model
if (model.kind === "not_applicable") return null
- return model.kind === "unknown" ? "Unknown model" : model.id
+ return model.kind === "unknown" ? "Model unavailable" : model.id
}
function resetLabel(limit: QuotaLimit): string {
diff --git a/src/web/src/components/community/channels/channel-loading-frame.test.ts b/src/web/src/components/community/channels/channel-loading-frame.test.ts
index 281360e69..c1b54c7d6 100644
--- a/src/web/src/components/community/channels/channel-loading-frame.test.ts
+++ b/src/web/src/components/community/channels/channel-loading-frame.test.ts
@@ -10,7 +10,8 @@ describe("ChannelLoadingFrame", () => {
expect(markup.match(/data-community-unresolved-main=""/g)).toHaveLength(1)
expect(markup).not.toContain('data-slot="skeleton"')
- expect(markup).toContain('aria-label="Connecting…"')
+ expect(markup).toContain('aria-label="Loading"')
+ expect(markup).not.toContain("Connecting")
expect(markup).toContain('aria-busy="true"')
expect(markup).toContain('aria-label="Loading conversation"')
expect(markup).not.toContain("data-community-mobile-transition")
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
index 83974cc8f..f1d4094f4 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
@@ -21,6 +21,7 @@ const {
mockSplitParentSurface,
mockCommitLastCommunityRoute,
mockSetLastChannel,
+ mockClearLastChannel,
mockNavigationGate,
mockCurrentChannelId,
mockCanManageServer,
@@ -36,6 +37,7 @@ const {
mockSplitParentSurface: vi.fn(() => null),
mockCommitLastCommunityRoute: vi.fn(),
mockSetLastChannel: vi.fn(),
+ mockClearLastChannel: vi.fn(),
mockNavigationGate: { allowed: true },
mockCurrentChannelId: { value: "channel_1" as string | null },
mockCanManageServer: vi.fn((role?: string | null) => role === "owner" || role === "admin"),
@@ -148,6 +150,7 @@ vi.mock("@alook/shared", () => ({
}))
vi.mock("@/lib/community/last-channel", () => ({
setLastChannel: (...args: unknown[]) => mockSetLastChannel(...args),
+ clearLastChannel: (...args: unknown[]) => mockClearLastChannel(...args),
}))
vi.mock("@/lib/community/last-community-route", () => ({
commitLastCommunityRoute: (...args: unknown[]) => mockCommitLastCommunityRoute(...args),
@@ -342,6 +345,7 @@ describe("ChannelRoute message surface ownership", () => {
mockHeaderParentNavigate.current = undefined
mockCommitLastCommunityRoute.mockClear()
mockSetLastChannel.mockClear()
+ mockClearLastChannel.mockClear()
mockNavigationGate.allowed = true
mockCurrentChannelId.value = "channel_1"
mockMemberViewModel.myRole = "member"
@@ -391,11 +395,12 @@ describe("ChannelRoute message surface ownership", () => {
it.each([
["pending", true],
["ready", false],
- ] as const)("keeps %s metadata neutral while access=%s", (routeLifecycle, accessAllowed) => {
+ ] as const)("keeps %s metadata on its known forum skeleton while access=%s", (routeLifecycle, accessAllowed) => {
Object.assign(mockRouteModel, {
channel: { id: "channel_1", name: "cached-forum", type: "forum" },
isForum: true,
routeLifecycle,
+ skeletonSubtype: "forum",
})
mockNavigationGate.allowed = accessAllowed
mockedUseChannelMessageFeed.mockReturnValue(feed())
@@ -409,8 +414,9 @@ describe("ChannelRoute message surface ownership", () => {
})
expect(renderer.container.querySelector(
- '[data-community-conversation-subtype="unknown"]',
+ '[data-community-conversation-subtype="forum"]',
)).not.toBeNull()
+ expect(screen.getByTestId("forum-view-skeleton")).not.toBeNull()
expect(mockedForumChannelSurface).not.toHaveBeenCalled()
expect(mockedMessageList).not.toHaveBeenCalled()
})
@@ -506,7 +512,7 @@ describe("ChannelRoute message surface ownership", () => {
await act(async () => renderer.unmount())
})
- it("mounts authoritative split geometry before a thread body is active", () => {
+ it("keeps an authoritative split route structural until the effect-owned pointer commits", () => {
configureThreadRoute()
mockSplitMode.value = "split"
mockCurrentChannelId.value = null
@@ -529,6 +535,75 @@ describe("ChannelRoute message surface ownership", () => {
expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
})
+ it("keeps the live surface fenced while the channel pointer belongs to the previous route", () => {
+ mockCurrentChannelId.value = "previous_channel"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+
+ const renderer = render(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+
+ expect(renderer.container.querySelector("[data-message-list-skeleton]")).not.toBeNull()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ expect(mockSetLastChannel).not.toHaveBeenCalled()
+ expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
+ })
+
+ it("fences a cleared pointer without re-committing route memory", () => {
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ const renderer = render(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledOnce()
+ expect(mockCommitLastCommunityRoute).toHaveBeenCalledOnce()
+
+ mockedUseChannelMessageFeed.mockClear()
+ mockCommitLastCommunityRoute.mockClear()
+ mockSetLastChannel.mockClear()
+ mockCurrentChannelId.value = null
+ act(() => {
+ renderer.rerender(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+ })
+
+ expect(renderer.container.querySelector("[data-message-list-skeleton]")).not.toBeNull()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ expect(mockSetLastChannel).not.toHaveBeenCalled()
+ expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
+ })
+
+ it("leaves a deleted top-level route immediately instead of waiting for metadata fallback", () => {
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ const renderer = render(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+
+ Object.assign(mockRouteModel, {
+ channel: null,
+ isChild: true,
+ routeHydrated: false,
+ routeLifecycle: "pending",
+ server: {
+ ...mockRouteModel.server,
+ categories: [{ channels: [{ id: "channel_2", name: "survivor", type: "text" }] }],
+ },
+ })
+ act(() => {
+ renderer.rerender(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+ })
+
+ expect(mockClearLastChannel).toHaveBeenCalledExactlyOnceWith("server_1")
+ expect(mockRouter.replace).toHaveBeenCalledWith("/c/channels/server_1/channel_2")
+ })
+
it("commits only a ready channel route for the active account", () => {
mockedUseChannelMessageFeed.mockReturnValue(feed())
act(() => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 46e316188..d156e3fa6 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useMemo, useState } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { toastApiError } from "@/lib/api/client"
import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"
@@ -17,7 +17,7 @@ import { ConversationResolutionPendingFrame } from "@/components/community/chann
import { useChannelMemberViewModel } from "@/components/community/members/channel-member-view-model"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { canManageServer, USE_SERVER_DEFAULT } from "@alook/shared"
-import { setLastChannel } from "@/lib/community/last-channel"
+import { clearLastChannel, setLastChannel } from "@/lib/community/last-channel"
import { commitLastCommunityRoute } from "@/lib/community/last-community-route"
import { resolveChannelDisplayName } from "@/lib/community/channel-display-name"
import { toChannelRefCandidate } from "@/lib/community/channel-ref-extension"
@@ -86,6 +86,23 @@ export function ChannelRoute({ serverParam, channelId }: {
isForumPostChild,
isNotifyUnit,
} = routeModel
+ const [topLevelRouteOwnership, setTopLevelRouteOwnership] = useState(() => ({
+ channelId,
+ wasTopLevel: channelInServer !== null,
+ }))
+ const routeWasTopLevel = topLevelRouteOwnership.channelId === channelId
+ && topLevelRouteOwnership.wasTopLevel
+ useLayoutEffect(() => {
+ setTopLevelRouteOwnership((ownership) => {
+ if (ownership.channelId !== channelId) {
+ return { channelId, wasTopLevel: channelInServer !== null }
+ }
+ if (channelInServer !== null && !ownership.wasTopLevel) {
+ return { channelId, wasTopLevel: true }
+ }
+ return ownership
+ })
+ }, [channelId, channelInServer])
const forumPostOpener = useForumOpenerHint(
serverId,
currentChannelMeta?.parentMessageId,
@@ -147,6 +164,16 @@ export function ChannelRoute({ serverParam, channelId }: {
const navigateServerRoot = useCallback(() => {
uiHandlers.replacePath?.(serverRootHref(serverParam))
}, [serverParam, uiHandlers])
+ useEffect(() => {
+ if (!routeWasTopLevel || channelInServer !== null) return
+ clearLastChannel(serverId)
+ const survivor = currentServer?.categories
+ .flatMap((category) => category.channels)
+ .find((channel) => channel.id !== channelId && !channel.pending)
+ router.replace(survivor
+ ? channelHref(serverParam, survivor.id)
+ : serverRootHref(serverParam))
+ }, [channelId, channelInServer, currentServer, routeWasTopLevel, router, serverId, serverParam])
const navigateParent = useCallback(() => {
const parentChannelId = currentChannelMeta?.parentChannelId
if (!parentChannelId) return
diff --git a/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx b/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx
index d55ca6c68..e6cb54f96 100644
--- a/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar-tree-owner.dom.test.tsx
@@ -3,7 +3,10 @@ import { describe, expect, it, vi } from "vitest"
import { fireEvent, render, screen } from "@/test/react-dom-harness"
import type { Category } from "@/lib/community/models/navigation"
import { tid } from "@/lib/community/testids"
-import { ChannelSidebarScope } from "./channel-sidebar-tree-owner"
+import {
+ ChannelSidebarRevealBoundary,
+ ChannelSidebarScope,
+} from "./channel-sidebar-tree-owner"
const targetCategories: Category[] = [{
id: "target-category",
@@ -13,7 +16,7 @@ const targetCategories: Category[] = [{
],
}]
-function scopeProps(categories: Category[] | null, loading = false) {
+function scopeProps(categories: Category[] | null) {
return {
categories,
scopeKey: "server:target",
@@ -24,11 +27,97 @@ function scopeProps(categories: Category[] | null, loading = false) {
setActiveChannel: vi.fn(),
isAdmin: false,
currentUserId: "viewer",
- loading,
}
}
describe("ChannelSidebarScope", () => {
+ it("reveals restored rows immediately while forum projection is pending", () => {
+ render(createElement(ChannelSidebarRevealBoundary, {
+ ...scopeProps(targetCategories),
+ categories: targetCategories,
+ primaryReady: true,
+ forumProjectionMissing: true,
+ trustedRestoredPrimary: true,
+ }))
+
+ expect(screen.getByTestId(tid.channelRow("target-one"))).toBeInTheDocument()
+ expect(screen.queryByTestId(tid.channelSidebarPending("target"))).not.toBeInTheDocument()
+ })
+
+ it("reveals asynchronously restored primary rows while forum projection stays pending", () => {
+ const base = {
+ ...scopeProps(targetCategories),
+ categories: targetCategories,
+ forumProjectionMissing: true,
+ }
+ const rendered = render(createElement(ChannelSidebarRevealBoundary, {
+ ...base,
+ primaryReady: false,
+ trustedRestoredPrimary: false,
+ }))
+ expect(screen.getByTestId(tid.channelSidebarPending("target"))).toBeInTheDocument()
+
+ rendered.rerender(createElement(ChannelSidebarRevealBoundary, {
+ ...base,
+ primaryReady: true,
+ trustedRestoredPrimary: true,
+ }))
+
+ expect(screen.getByTestId(tid.channelRow("target-one"))).toBeInTheDocument()
+ expect(screen.queryByTestId(tid.channelSidebarPending("target"))).not.toBeInTheDocument()
+ })
+
+ it("keeps true-cold primary rows hidden until forum is ready, then preserves the DOM", () => {
+ const base = {
+ ...scopeProps(targetCategories),
+ categories: targetCategories,
+ }
+ const rendered = render(createElement(ChannelSidebarRevealBoundary, {
+ ...base,
+ primaryReady: false,
+ forumProjectionMissing: true,
+ trustedRestoredPrimary: false,
+ }))
+ expect(screen.getByTestId(tid.channelSidebarPending("target"))).toBeInTheDocument()
+
+ rendered.rerender(createElement(ChannelSidebarRevealBoundary, {
+ ...base,
+ primaryReady: true,
+ forumProjectionMissing: true,
+ trustedRestoredPrimary: false,
+ }))
+ expect(screen.getByTestId(tid.channelSidebarPending("target"))).toBeInTheDocument()
+
+ rendered.rerender(createElement(ChannelSidebarRevealBoundary, {
+ ...base,
+ primaryReady: true,
+ forumProjectionMissing: false,
+ trustedRestoredPrimary: false,
+ }))
+ const owner = rendered.container.querySelector("[data-community-channel-tree-scope]")
+ const scroll = screen.getByTestId(tid.channelSidebarScroll)
+ expect(owner).toBeInTheDocument()
+
+ rendered.rerender(createElement(ChannelSidebarRevealBoundary, {
+ ...base,
+ primaryReady: true,
+ forumProjectionMissing: true,
+ trustedRestoredPrimary: false,
+ }))
+ expect(rendered.container.querySelector("[data-community-channel-tree-scope]")).toBe(owner)
+ expect(screen.getByTestId(tid.channelSidebarScroll)).toBe(scroll)
+ expect(screen.queryByTestId(tid.channelSidebarPending("target"))).not.toBeInTheDocument()
+
+ rendered.rerender(createElement(ChannelSidebarRevealBoundary, {
+ ...base,
+ primaryReady: true,
+ forumProjectionMissing: false,
+ trustedRestoredPrimary: false,
+ }))
+ expect(rendered.container.querySelector("[data-community-channel-tree-scope]")).toBe(owner)
+ expect(screen.getByTestId(tid.channelSidebarScroll)).toBe(scroll)
+ })
+
it("does not mount the tree owner until target data exists", () => {
const rendered = render(createElement(ChannelSidebarScope, scopeProps(null)))
@@ -47,19 +136,29 @@ describe("ChannelSidebarScope", () => {
expect(rendered.container.textContent).not.toContain("source-one")
})
- it("keeps the same owner and collapsed state through inner forum loading", () => {
+ it("keeps cached rows and collapsed state while forum children reconcile", () => {
const rendered = render(createElement(ChannelSidebarScope, scopeProps(targetCategories)))
const owner = rendered.container.querySelector("[data-community-channel-tree-scope]")!
fireEvent.click(screen.getByText("Target category"))
expect(screen.queryByTestId(tid.channelRow("target-one"))).not.toBeInTheDocument()
- rendered.rerender(createElement(ChannelSidebarScope, scopeProps(targetCategories, true)))
- expect(rendered.container.querySelector("[data-community-channel-tree-scope]")).toBe(owner)
- expect(rendered.container.querySelector('[data-slot="skeleton"]')).toBeInTheDocument()
-
- rendered.rerender(createElement(ChannelSidebarScope, scopeProps(targetCategories, false)))
+ rendered.rerender(createElement(ChannelSidebarScope, {
+ ...scopeProps(targetCategories),
+ forumThreadsByParent: {
+ "target-one": [{
+ id: "thread-one",
+ parentChannelId: "target-one",
+ parentMessageId: "message-one",
+ title: "Thread one",
+ activityAt: "2026-09-25T00:00:00.000Z",
+ expiresAt: "2026-09-28T00:00:00.000Z",
+ unread: false,
+ }],
+ },
+ }))
expect(rendered.container.querySelector("[data-community-channel-tree-scope]")).toBe(owner)
+ expect(rendered.container.querySelector('[data-slot="skeleton"]')).not.toBeInTheDocument()
expect(screen.queryByTestId(tid.channelRow("target-one"))).not.toBeInTheDocument()
})
diff --git a/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsx b/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsx
index 2e11efe02..6ed61949f 100644
--- a/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar-tree-owner.tsx
@@ -1,5 +1,6 @@
"use client"
+import { useEffect, useState } from "react"
import type { Category } from "@/lib/community/models/navigation"
import {
ChannelSidebar,
@@ -18,7 +19,50 @@ export type ChannelSidebarScopeProps = Omit<ChannelSidebarTreeOwnerProps, "categ
targetServerId: string
}
-/** Keeps the cold readiness gate outside the state-owning tree component. */
+export type ChannelSidebarRevealBoundaryProps = Omit<
+ ChannelSidebarScopeProps,
+ "categories"
+> & {
+ categories: Category[]
+ primaryReady: boolean
+ forumProjectionMissing: boolean
+ trustedRestoredPrimary: boolean
+}
+
+/**
+ * A trusted restored primary tree reveals even when it arrives asynchronously
+ * and the non-persisted forum projection is still pending. A true-cold tree
+ * reveals once, after its primary data and initial forum projection are both
+ * ready. Later forum refetches never hide or remount the revealed tree.
+ */
+export function ChannelSidebarRevealBoundary({
+ categories,
+ primaryReady,
+ forumProjectionMissing,
+ trustedRestoredPrimary,
+ ...scopeProps
+}: ChannelSidebarRevealBoundaryProps) {
+ const [revealed, setRevealed] = useState(primaryReady && trustedRestoredPrimary)
+
+ useEffect(() => {
+ if (primaryReady && (trustedRestoredPrimary || !forumProjectionMissing)) {
+ setRevealed(true)
+ }
+ }, [forumProjectionMissing, primaryReady, trustedRestoredPrimary])
+
+ return (
+ <ChannelSidebarScope
+ categories={primaryReady && revealed ? categories : null}
+ {...scopeProps}
+ />
+ )
+}
+
+/**
+ * Owns the only server-sidebar loading boundary. Once canonical or structural
+ * categories exist, secondary fetches may reconcile the mounted tree but must
+ * never replace cached rows with a skeleton.
+ */
export function ChannelSidebarScope({
categories,
scopeKey,
diff --git a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
index 6810146e4..e386cf530 100644
--- a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
+++ b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs"
import { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
-import { ChannelSidebar } from "./channel-sidebar"
+import { ChannelSidebar, ChannelSidebarSkeleton } from "./channel-sidebar"
import type { ChannelTree } from "./use-channel-tree"
const emptyTree = {
@@ -38,15 +38,8 @@ const render = () =>
const renderLoading = () =>
renderToStaticMarkup(
- createElement(ChannelSidebar, {
- tree: emptyTree,
- serverName: "Alpha",
- serverIcon: null,
- serverId: "srv_1",
- activeChannel: "",
- setActiveChannel: vi.fn(),
- loading: true,
- onInvitePopoverOpenChange: vi.fn(),
+ createElement(ChannelSidebarSkeleton, {
+ showInviteAction: true,
}),
)
@@ -134,7 +127,7 @@ describe("ChannelSidebar header", () => {
expect(css).toContain("scrollbar-width: none")
})
- it("keeps the same header action slot and scroll owner while loading", () => {
+ it("keeps the same header action slot and scroll owner in the cold skeleton", () => {
const html = renderLoading()
expect(html).toContain("flex min-h-0 min-w-0 flex-1 flex-col")
expect(html).toContain(
diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsx
index a0c7963f5..fce3efb02 100644
--- a/src/web/src/components/community/channels/channel-sidebar.tsx
+++ b/src/web/src/components/community/channels/channel-sidebar.tsx
@@ -67,7 +67,6 @@ export type ChannelSidebarProps = {
currentUserId?: string
onBlockedCreate?: () => void
mutedChannels?: Record<string, boolean>
- loading?: boolean
onCreateChannel?: (categoryId: string, name: string, type: ChannelType) => Promise<string | null> | void
onCreateCategory?: (name: string, opts?: { private?: boolean }) => Promise<string | null> | void
onDeleteChannel?: (channelId: string) => void
@@ -88,7 +87,7 @@ export type ChannelSidebarProps = {
export const ChannelSidebar = memo(function ChannelSidebar({
tree, serverName, official, activeChannel, setActiveChannel, prefetchChannel, noHeader, onOpenSettings,
- isAdmin = true, currentUserId, onBlockedCreate, mutedChannels, loading,
+ isAdmin = true, currentUserId, onBlockedCreate, mutedChannels,
onCreateChannel, onCreateCategory, onDeleteChannel, onDeleteCategory,
onUpdateCategory, onRenameChannel, onReorderCategories, onReorderChannels,
onMoveChannel, onBlockedMove,
@@ -218,23 +217,6 @@ export const ChannelSidebar = memo(function ChannelSidebar({
// Find the "none" category ID (empty name) — only if one explicitly exists
const noneCatId = Object.keys(catNames).find((id) => catNames[id] === "") ?? ""
- // Initial load / server switch — render skeleton so the sidebar holds its
- // width and rhythm instead of collapsing to an empty column. Do NOT gate on
- // `catOrder.length === 0`: the tree is derived from `categories` inside a
- // useEffect (use-channel-tree.ts), so on a server switch it still holds the
- // PREVIOUS server's categories for one commit while `loading` has already
- // flipped true. Gating on catOrder would flash the old server's channel list
- // for a frame before collapsing to skeleton.
- if (loading) {
- return (
- <ChannelSidebarSkeleton
- noHeader={noHeader}
- showInviteAction={Boolean(serverId && onInvitePopoverOpenChange)}
- />
- )
- }
-
-
// Who may create a channel where:
// - uncategorized (empty categoryId) / public category → admins only
// - private category → any member (they own the channel + its roster)
diff --git a/src/web/src/components/community/channels/conversation-resolution-pending-frame.test.ts b/src/web/src/components/community/channels/conversation-resolution-pending-frame.test.ts
index d9398cf7d..c4a689908 100644
--- a/src/web/src/components/community/channels/conversation-resolution-pending-frame.test.ts
+++ b/src/web/src/components/community/channels/conversation-resolution-pending-frame.test.ts
@@ -9,7 +9,8 @@ describe("ConversationResolutionPendingFrame", () => {
expect(markup.match(/data-community-unresolved-main=""/g)).toHaveLength(1)
expect(markup).not.toContain('data-slot="skeleton"')
- expect(markup).toContain('aria-label="Connecting…"')
+ expect(markup).toContain('aria-label="Loading"')
+ expect(markup).not.toContain("Connecting")
})
it("stays inert and exposes no speculative conversation content", () => {
@@ -23,4 +24,19 @@ describe("ConversationResolutionPendingFrame", () => {
expect(markup).not.toMatch(/<(?:header|button|a|form|textarea)\b/)
expect(markup).not.toMatch(/Message|Forum|Thread|composer|previous channel/i)
})
+
+ it.each([
+ ["text", "Loading conversation"],
+ ["forum", "Loading forum"],
+ ["thread", "Loading thread"],
+ ] as const)("keeps a known %s transition on its typed skeleton", (subtype, label) => {
+ const markup = renderToStaticMarkup(createElement(
+ ConversationResolutionPendingFrame,
+ { subtype },
+ ))
+
+ expect(markup).toContain(`data-community-conversation-subtype="${subtype}"`)
+ expect(markup).toContain(`aria-label="${label}"`)
+ expect(markup).not.toContain('data-community-conversation-subtype="unknown"')
+ })
})
diff --git a/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx b/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx
index fb568bfb7..4a73f9d84 100644
--- a/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx
+++ b/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx
@@ -1,7 +1,46 @@
import { UnresolvedMainSkeleton } from "../shell/unresolved-main-skeleton"
+import { ChannelHeaderSkeleton } from "./channel-header"
+import { ConversationMessageSkeleton } from "./conversation-message-skeleton"
+import { ForumViewSkeleton } from "./forum-view"
+import { ComposerSkeleton } from "../messages/composer"
/** Inert main-area placeholder used until canonical route metadata proves the subtype. */
-export function ConversationResolutionPendingFrame() {
+export function ConversationResolutionPendingFrame({
+ subtype = "unknown",
+}: {
+ subtype?: "unknown" | "text" | "forum" | "thread"
+} = {}) {
+ if (subtype === "forum") {
+ return (
+ <>
+ <ChannelHeaderSkeleton kind="forum" />
+ <main
+ aria-busy="true"
+ aria-label="Loading forum"
+ data-community-conversation-subtype="forum"
+ className="flex min-h-0 min-w-0 flex-1 flex-col"
+ >
+ <ForumViewSkeleton />
+ </main>
+ </>
+ )
+ }
+ if (subtype === "text" || subtype === "thread") {
+ return (
+ <>
+ <ChannelHeaderSkeleton kind={subtype} />
+ <main
+ aria-busy="true"
+ aria-label={subtype === "thread" ? "Loading thread" : "Loading conversation"}
+ data-community-conversation-subtype={subtype}
+ className="flex min-h-0 min-w-0 flex-1 flex-col"
+ >
+ <ConversationMessageSkeleton />
+ <ComposerSkeleton />
+ </main>
+ </>
+ )
+ }
return (
<main
aria-busy="true"
diff --git a/src/web/src/components/community/channels/forum-view.test.ts b/src/web/src/components/community/channels/forum-view.test.ts
index 26f21eba4..4b94ffa19 100644
--- a/src/web/src/components/community/channels/forum-view.test.ts
+++ b/src/web/src/components/community/channels/forum-view.test.ts
@@ -13,8 +13,8 @@ import { tid } from "@/lib/community/testids"
import type { ForumThread } from "@/lib/community/models/message"
const profileState = vi.hoisted(() => ({ map: new Map<string, Record<string, unknown>>() }))
-vi.mock("@/stores/community/ws", () => ({
- useProfilesByUserId: () => profileState.map,
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalProfilesByUserId: () => profileState.map,
}))
const LAST_AT = "2020-01-01T00:00:00.000Z"
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index ddb74f525..10e736120 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -23,7 +23,7 @@ import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-s
import { tagColorClassName, tagColorStyle } from "@/lib/community/tag-color"
import { cn } from "@/lib/utils"
import { FORUM_ARCHIVE_TAG } from "@alook/shared"
-import { useProfilesByUserId } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
HorizontalOverflowFadeOverlays,
@@ -221,7 +221,7 @@ export function ForumView({
deletingPost?: string | null
onScrollRoot?: (node: HTMLDivElement | null) => void
}) {
- const profilesByUserId = useProfilesByUserId()
+ const profilesByUserId = useCanonicalProfilesByUserId()
const [composing, setComposing] = useState(false)
const [deletingFor, setDeletingFor] = useState<ForumThread | null>(null)
const newPostTriggerRef = useRef<HTMLButtonElement>(null)
diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
index e87b23dba..39ce1504f 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
@@ -268,6 +268,8 @@ describe("ThreadChannelSurface ownership", () => {
expect(opener.type).toBe(ThreadOpener)
expect(opener.props).toEqual(expect.objectContaining({
parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
viewerUserId: "viewer_1",
onOpenProfile: props.onOpenProfile,
onToggleReaction: expect.any(Function),
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 5f730d4d6..b61fdf631 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -170,6 +170,8 @@ export function ThreadChannelSurface({
const opener = parentMessageId && !parentIsForum ? (
<ThreadOpener
parentMessageId={parentMessageId}
+ parentChannelId={parentChannelId}
+ serverId={serverId}
viewerUserId={viewer.id}
onOpenProfile={onOpenProfile}
onToggleReaction={parentChannelId ? toggleOpenerReaction : undefined}
diff --git a/src/web/src/components/community/channels/use-channel-tree.dom.test.ts b/src/web/src/components/community/channels/use-channel-tree.dom.test.ts
index 4fb5fc609..e77a34c3e 100644
--- a/src/web/src/components/community/channels/use-channel-tree.dom.test.ts
+++ b/src/web/src/components/community/channels/use-channel-tree.dom.test.ts
@@ -26,6 +26,12 @@ function CaptureTree({ categories, onResult }: { categories: Category[]; onResul
return null
}
+function ReallocatedCaptureTree({ onResult }: { onResult: (tree: Tree) => void }) {
+ const categories = [category("cat_A", [ch("a1"), ch("a2")])]
+ onResult(useChannelTree(categories))
+ return null
+}
+
let nextOwnerId = 0
function ScopedCaptureTree({
@@ -310,11 +316,90 @@ describe("useChannelTree scope ownership", () => {
expect(samples[0].tree.collapsed).toEqual(new Set())
expect(samples[0].tree.order.cat_A.map((channel) => channel.id)).toEqual(["a1", "tmp_A"])
})
+
+ it("does not schedule an order update for equivalent categories with new references", async () => {
+ let current!: Tree
+ let renders = 0
+ const onResult = (tree: Tree) => {
+ current = tree
+ renders += 1
+ }
+ const renderer = rtlRender(React.createElement(ReallocatedCaptureTree, { onResult }))
+ const initialOrder = current.order
+
+ await act(async () => current.toggleCat("cat_A"))
+ expect(current.collapsed).toEqual(new Set(["cat_A"]))
+ expect(current.order).toBe(initialOrder)
+ expect(renders).toBe(2)
+
+ renderer.rerender(React.createElement(ReallocatedCaptureTree, { onResult }))
+ expect(renders).toBe(3)
+ expect(current.order).toBe(initialOrder)
+ })
+
+ it("reconciles category metadata without replacing drag order", async () => {
+ let current!: Tree
+ const onResult = (tree: Tree) => { current = tree }
+ const renderer = rtlRender(React.createElement(CaptureTree, {
+ categories: categoriesA,
+ onResult,
+ }))
+ const initialOrder = current.order
+
+ renderer.rerender(React.createElement(CaptureTree, {
+ categories: categoriesA.map((item) => item.id === "cat_A" ? {
+ ...item,
+ name: "Renamed",
+ private: false,
+ pending: false,
+ creatorId: "owner_B",
+ } : item),
+ onResult,
+ }))
+ await act(async () => { await Promise.resolve() })
+
+ expect(current.order).toBe(initialOrder)
+ expect(current.catNames.cat_A).toBe("Renamed")
+ expect(current.catPrivate.cat_A).toBe(false)
+ expect(current.catPending.cat_A).toBe(false)
+ expect(current.catCreators.cat_A).toBe("owner_B")
+ })
+
+ it("reconciles channel interaction, permission, and type metadata for stable ids", async () => {
+ let current!: Tree
+ const onResult = (tree: Tree) => { current = tree }
+ const initial: Category[] = [category("cat_A", [{
+ ...ch("channel_1"),
+ pending: true,
+ creatorId: "owner_A",
+ type: "text",
+ }])]
+ const renderer = rtlRender(React.createElement(CaptureTree, {
+ categories: initial,
+ onResult,
+ }))
+
+ renderer.rerender(React.createElement(CaptureTree, {
+ categories: [category("cat_A", [{
+ ...ch("channel_1"),
+ pending: false,
+ creatorId: "owner_B",
+ type: "forum",
+ }])],
+ onResult,
+ }))
+ await act(async () => { await Promise.resolve() })
+
+ expect(current.order.cat_A[0]).toMatchObject({
+ pending: false,
+ creatorId: "owner_B",
+ type: "forum",
+ })
+ })
})
-// Regression: the sync effect's id-set early-return silently swallowed
-// metadata-only updates (unread/name) — see "The useChannelTree gap" in
-// plans/community-unread-indicators.md.
+// Regression: the sync effect's id-set early-return must not swallow
+// metadata-only updates such as unread and name changes.
describe("mergeChannelMetadata", () => {
const cat = (id: string, channels: Channel[]): Category => ({ id, name: id, channels })
diff --git a/src/web/src/components/community/channels/use-channel-tree.ts b/src/web/src/components/community/channels/use-channel-tree.ts
index bcabb2606..b43091639 100644
--- a/src/web/src/components/community/channels/use-channel-tree.ts
+++ b/src/web/src/components/community/channels/use-channel-tree.ts
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useMemo, useRef, useState } from "react"
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react"
import { arrayMove } from "@dnd-kit/sortable"
import type { DragEndEvent } from "@dnd-kit/core"
import type { Category, Channel } from "@/lib/community/models/navigation"
@@ -11,6 +11,36 @@ export const catId = (id: string) => id
export type ChannelOrder = Record<string, Channel[]>
+function channelTreeIdentity(categories: Category[]): string {
+ return JSON.stringify(categories.map((category) => [
+ category.id,
+ category.name,
+ Boolean(category.private),
+ Boolean(category.pending),
+ category.creatorId ?? null,
+ category.channels.map((channel) => [
+ channel.id,
+ channel.name,
+ Boolean(channel.unread),
+ channel.pending ?? null,
+ channel.creatorId ?? null,
+ channel.type ?? null,
+ ]),
+ ]))
+}
+
+function replaceRecordIfChanged<T>(
+ current: Record<string, T>,
+ next: Record<string, T>,
+): Record<string, T> {
+ const keys = Object.keys(next)
+ if (keys.length === Object.keys(current).length &&
+ keys.every((key) => current[key] === next[key])) {
+ return current
+ }
+ return next
+}
+
/** Which category currently holds a channel id (or the category itself if `id` is an order key). */
export function catOf(id: string, order: ChannelOrder): string | undefined {
if (Object.hasOwn(order, id)) return id
@@ -78,9 +108,23 @@ export function mergeChannelMetadata(
next[catId] = channels.map((ch) => {
const src = incoming.get(ch.id)
if (!src) return ch
- if (src.unread === ch.unread && src.name === ch.name) return ch
+ const pending = src.pending === undefined ? ch.pending : src.pending
+ if (
+ src.unread === ch.unread &&
+ src.name === ch.name &&
+ Boolean(pending) === Boolean(ch.pending) &&
+ (src.creatorId ?? null) === (ch.creatorId ?? null) &&
+ (src.type ?? null) === (ch.type ?? null)
+ ) return ch
changed = true
- return { ...ch, unread: src.unread, name: src.name }
+ return {
+ ...ch,
+ unread: src.unread,
+ name: src.name,
+ pending,
+ creatorId: src.creatorId,
+ type: src.type,
+ }
})
}
return { next: changed ? next : order, changed }
@@ -101,6 +145,7 @@ export function reorderCategories(catOrder: string[], activeCatId: string, overC
* sort among themselves, channels sort across categories.
*/
export function useChannelTree(categories: Category[]) {
+ const categoriesIdentity = channelTreeIdentity(categories)
const [collapsed, setCollapsed] = useState<Set<string>>(new Set())
const [catOrder, setCatOrder] = useState<string[]>(() => categories.map((c) => c.id))
const [order, setOrder] = useState<ChannelOrder>(() =>
@@ -125,11 +170,12 @@ export function useChannelTree(categories: Category[]) {
)
// Sync state when categories change from API (initial load or server switch)
- const prevCatsRef = useRef(categories)
- useEffect(() => {
- const prev = prevCatsRef.current
- prevCatsRef.current = categories
- if (categories === prev) return
+ const prevCatsRef = useRef({ categories, identity: categoriesIdentity })
+ const reconcileCategories = useEffectEvent(() => {
+ const previous = prevCatsRef.current
+ if (previous.identity === categoriesIdentity) return
+ const prev = previous.categories
+ prevCatsRef.current = { categories, identity: categoriesIdentity }
// Server-detail cleared on route change — collapse our derived state so the
// sidebar's loading branch can render the skeleton instead of stale rows.
if (categories.length === 0) {
@@ -148,12 +194,31 @@ export function useChannelTree(categories: Category[]) {
if (prevKey === nextKey) {
// Id sets are unchanged, but metadata fields (`unread`, `name`) may
// have changed underneath — e.g. a WS-driven cache patch or a refetch
- // that only flips a flag. Merge those without resetting drag order or
- // collapse state (see plans/community-unread-indicators.md).
+ // that only flips a flag. Merge those while preserving drag order and
+ // collapse state.
setOrder((prevOrder) => {
const { next, changed } = mergeChannelMetadata(prevOrder, categories)
return changed ? next : prevOrder
})
+ setCatNames((current) => replaceRecordIfChanged(
+ current,
+ Object.fromEntries(categories.map((category) => [category.id, category.name])),
+ ))
+ setCatPrivate((current) => replaceRecordIfChanged(
+ current,
+ Object.fromEntries(categories.map((category) => [category.id, !!category.private])),
+ ))
+ setCatPending((current) => replaceRecordIfChanged(
+ current,
+ Object.fromEntries(categories.map((category) => [
+ category.id,
+ category.pending === undefined ? (current[category.id] ?? false) : category.pending,
+ ])),
+ ))
+ setCatCreators((current) => replaceRecordIfChanged(
+ current,
+ Object.fromEntries(categories.map((category) => [category.id, category.creatorId ?? null])),
+ ))
return
}
setCatOrder(categories.map((c) => c.id))
@@ -162,7 +227,10 @@ export function useChannelTree(categories: Category[]) {
setCatPrivate(Object.fromEntries(categories.map((c) => [c.id, !!c.private])))
setCatPending(Object.fromEntries(categories.map((c) => [c.id, !!c.pending])))
setCatCreators(Object.fromEntries(categories.map((c) => [c.id, c.creatorId ?? null])))
- }, [categories])
+ })
+ useEffect(() => {
+ reconcileCategories()
+ }, [categoriesIdentity])
const toggleCat = useCallback((id: string) =>
setCollapsed((prev) => {
diff --git a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts b/src/web/src/components/community/members/channel-member-view-model.dom.test.ts
index 037811927..b90c211d3 100644
--- a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts
+++ b/src/web/src/components/community/members/channel-member-view-model.dom.test.ts
@@ -96,8 +96,8 @@ vi.mock("@/hooks/community/mutations", () => ({
useSetMemberRole: () => ({ mutate: mocks.setMemberRole }),
useKickMember: () => ({ mutateAsync: mocks.kickMember }),
}))
-vi.mock("@/stores/community/ws", () => ({
- useCommunityWsStore: (selector: (state: { profilesByUserId: Map<string, unknown> }) => unknown) => {
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalProfilesByUserId: () => {
const rows = [
...mocks.serverMembers,
...[...mocks.channelMembers.values()].flat(),
@@ -119,7 +119,7 @@ vi.mock("@/stores/community/ws", () => ({
statusText: status?.text,
}]]
}))
- return selector({ profilesByUserId })
+ return profilesByUserId
},
}))
vi.mock("@/components/community/members/add-members-dialog", () => ({
diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsx
index b33f21864..9bd29f13f 100644
--- a/src/web/src/components/community/members/channel-member-view-model.tsx
+++ b/src/web/src/components/community/members/channel-member-view-model.tsx
@@ -22,7 +22,7 @@ import {
useRemoveThreadParticipant,
} from "@/hooks/community/use-thread-participants"
import { useKickMember, useSetMemberRole } from "@/hooks/community/mutations"
-import { useCommunityWsStore } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
type MentionCandidateSource = NonNullable<ComposerProps["mentionCandidates"]>
@@ -91,7 +91,7 @@ export function useChannelMemberViewModel({
myRole: Role | undefined
} {
const membersHook = useServerMembers(accessAllowed && currentServer ? serverId : null)
- const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)
+ const profilesByUserId = useCanonicalProfilesByUserId()
const [memberUi, setMemberUi] = useState({ channelId, query: "", dialogOpen: false })
const memberQuery = memberUi.channelId === channelId ? memberUi.query : ""
const manageMembersOpen = memberUi.channelId === channelId && memberUi.dialogOpen
@@ -106,10 +106,10 @@ export function useChannelMemberViewModel({
const members = useMemo(
() => membersHook.members.map((member) => {
- const profile = readCommunityProfile(
- profilesByUserId.get(member.userId),
- member.userId,
- )
+ const canonical = profilesByUserId.get(member.userId)
+ const profile = canonical
+ ? readCommunityProfile(canonical, member.userId)
+ : { ...member, presence: member.status }
return {
...member,
name: profile.name,
diff --git a/src/web/src/components/community/messages/channel-ref-pill.tsx b/src/web/src/components/community/messages/channel-ref-pill.tsx
index b7c4ac57a..cf9b00388 100644
--- a/src/web/src/components/community/messages/channel-ref-pill.tsx
+++ b/src/web/src/components/community/messages/channel-ref-pill.tsx
@@ -23,7 +23,7 @@ export type ChannelRefPillView =
// target (see decision table below).
threadSuffix?: number
// Set when the ref pins a specific message inside a thread
- // (`/s/c/#N#M`, see plans/agent-thread-emoji-react.md). Rendered as
+ // (`/s/c/#N#M`). Rendered as
// plain trailing text (`#M`, no leading slash) — the clickable target
// is still the thread channel; `#M` is a visible cursor, not a deep
// link anchor.
diff --git a/src/web/src/components/community/messages/initial-position-aurora.dom.test.tsx b/src/web/src/components/community/messages/initial-position-aurora.dom.test.tsx
deleted file mode 100644
index e0d63f6ef..000000000
--- a/src/web/src/components/community/messages/initial-position-aurora.dom.test.tsx
+++ /dev/null
@@ -1,204 +0,0 @@
-import { readFileSync } from "node:fs"
-import { dirname, resolve } from "node:path"
-import { fileURLToPath } from "node:url"
-import React from "react"
-import { describe, expect, it, vi } from "vitest"
-import { render } from "@/test/react-dom-harness"
-import { tid } from "@/lib/community/testids"
-import { INITIAL_POSITION_CROSSFADE_MS } from "./initial-position-transition"
-import { InitialPositionAurora } from "./initial-position-aurora"
-
-vi.mock("./initial-position-aurora.module.css", () => ({
- default: new Proxy({}, { get: (_target, key) => String(key) }),
-}))
-
-const styles = readFileSync(
- resolve(dirname(fileURLToPath(import.meta.url)), "initial-position-aurora.module.css"),
- "utf8",
-)
-const componentSource = readFileSync(
- resolve(dirname(fileURLToPath(import.meta.url)), "initial-position-aurora.tsx"),
- "utf8",
-)
-const globals = readFileSync(
- resolve(dirname(fileURLToPath(import.meta.url)), "../../../app/globals.css"),
- "utf8",
-)
-
-describe("InitialPositionAurora", () => {
- it("renders only for the visible and crossfade phases without interaction or prose", () => {
- const renderer = render(React.createElement(InitialPositionAurora, { phase: "positioning" }))
- expect(renderer.queryByTestId(tid.initialPositionAurora)).toBeNull()
-
- renderer.rerender(React.createElement(InitialPositionAurora, { phase: "aurora" }))
- const aurora = renderer.getByTestId(tid.initialPositionAurora)
- expect(aurora).toHaveAttribute("aria-hidden", "true")
- expect(aurora).toHaveAttribute("data-phase", "aurora")
- expect(aurora).toHaveTextContent("")
- expect(aurora).toHaveClass("visible")
-
- renderer.rerender(React.createElement(InitialPositionAurora, { phase: "revealing" }))
- expect(renderer.getByTestId(tid.initialPositionAurora)).toHaveAttribute(
- "data-phase",
- "revealing",
- )
- expect(renderer.getByTestId(tid.initialPositionAurora)).toBe(aurora)
- expect(aurora).toHaveClass("leaving")
- expect(aurora).not.toHaveClass("visible")
- renderer.rerender(React.createElement(InitialPositionAurora, { phase: "revealed" }))
- expect(renderer.queryByTestId(tid.initialPositionAurora)).toBeNull()
- })
-
- it("keeps Composer-bound geometry, deterministic bottom-anchored bars, and a linear 300ms exit", () => {
- const renderer = render(React.createElement(InitialPositionAurora, { phase: "aurora" }))
- const bars = Array.from(
- renderer.container.querySelectorAll<HTMLElement>("[data-aurora-bar]"),
- )
- const numberProperty = (bar: HTMLElement, property: string) =>
- Number.parseFloat(bar.style.getPropertyValue(property))
- const signature = () => Array.from(
- renderer.container.querySelectorAll<HTMLElement>("[data-aurora-bar]"),
- (bar) => [
- bar.dataset.layer,
- bar.dataset.tone,
- bar.dataset.motion,
- bar.getAttribute("style"),
- ],
- )
-
- expect(bars).toHaveLength(52)
- const layers = Array.from(
- renderer.container.querySelectorAll<HTMLElement>("[data-aurora-layer]"),
- )
- expect(layers).toHaveLength(2)
- expect(layers.map((layer) => [
- layer.dataset.auroraLayer,
- layer.querySelectorAll("[data-aurora-bar]").length,
- ])).toEqual([["fine", 39], ["broad", 13]])
- const firstSignature = signature()
- renderer.rerender(React.createElement(InitialPositionAurora, { phase: "aurora" }))
- expect(signature()).toEqual(firstSignature)
- expect(componentSource).not.toMatch(/Math\.random|\brandom\s*\(/)
-
- expect(styles).toMatch(/position:\s*absolute/)
- expect(styles).toMatch(/pointer-events:\s*none/)
- expect(styles).toContain(
- "left: calc(var(--community-composer-inline-start) + var(--community-composer-top-radius));",
- )
- expect(styles).toContain(
- "right: calc(var(--community-composer-inline-end) + var(--community-composer-top-radius));",
- )
- expect(globals).toContain(
- "--community-composer-inline-start: max(0.75rem, var(--app-safe-area-left));",
- )
- expect(globals).toContain(
- "--community-composer-inline-end: max(0.75rem, var(--app-safe-area-right));",
- )
- expect(globals).toMatch(
- /@media \(hover: hover\) and \(pointer: fine\)[\s\S]*?--community-composer-top-radius:\s*0\.75rem;/,
- )
- expect(globals).toMatch(
- /@media \(min-width: 40rem\)[\s\S]*?--community-composer-inline-start:\s*0\.75rem;[\s\S]*?--community-composer-inline-end:\s*0\.75rem;/,
- )
- expect(globals).toContain("--community-composer-top-radius: 1.5rem;")
-
- expect(styles).toContain(`animation: aurora-enter ${INITIAL_POSITION_CROSSFADE_MS}ms var(--ease-out) both`)
- expect(styles).toContain(`animation: aurora-leave ${INITIAL_POSITION_CROSSFADE_MS}ms linear both`)
- expect(styles).toMatch(/@keyframes aurora-enter\s*\{\s*from \{ opacity: 0; \}\s*to \{ opacity: var\(--aurora-opacity\); \}/)
- expect(styles).toMatch(/@keyframes aurora-leave\s*\{\s*from \{ opacity: var\(--aurora-opacity\); \}\s*to \{ opacity: 0; \}/)
- expect(styles).toContain("calc(var(--initial-position-aurora-opacity) * 0.5)")
- expect(styles).toContain("calc(var(--initial-position-aurora-reduced-opacity) * 0.5)")
- expect(styles).toMatch(/\.aurora\s*\{[^}]*z-index: 0;/)
- expect(styles.match(/\.peaks\s*\{([^}]+)\}/)?.[1]).not.toMatch(/background:/)
- expect(styles).toContain("left: var(--bar-x);")
- expect(styles).toContain("transform-origin: center bottom;")
- expect(styles).toContain(
- "animation: aurora-bar-length var(--bar-duration) var(--ease-in-out) var(--bar-delay) infinite alternate both;",
- )
- expect(styles).toMatch(
- /@keyframes aurora-bar-length\s*\{\s*from\s*\{\s*transform:\s*scaleY\(var\(--bar-min-scale\)\);\s*\}\s*to\s*\{\s*transform:\s*scaleY\(1\);/,
- )
- expect(styles).not.toMatch(/translate(?:X|3d)?\s*\(/)
- expect(styles).toMatch(/\.aurora\s*\{[\s\S]*?height:\s*3\.5rem;/)
- expect(styles).toMatch(
- /@media \(max-width: 40rem\)[\s\S]*?\.aurora\s*\{[\s\S]*?height:\s*3rem;/,
- )
- const themeTokens = [
- "--initial-position-aurora-cyan",
- "--initial-position-aurora-blue",
- "--initial-position-aurora-violet",
- "--initial-position-aurora-magenta",
- "--initial-position-aurora-opacity",
- "--initial-position-aurora-bloom-opacity",
- "--initial-position-aurora-glint-opacity",
- "--initial-position-aurora-reduced-opacity",
- ]
- for (const token of themeTokens) {
- expect(styles).toContain(`var(${token})`)
- expect(globals.match(new RegExp(`${token}:`, "g"))).toHaveLength(2)
- }
- expect(styles).toMatch(/\.fineBars\s*\{[^}]*filter:\s*blur\(1px\)/)
- expect(styles).toMatch(/\.broadBars\s*\{[^}]*opacity:\s*0\.72;[^}]*filter:\s*blur\(5px\)/)
- const barRule = styles.match(/\.bar\s*\{([^}]+)\}/)?.[1] ?? ""
- expect(barRule).not.toContain("filter:")
- expect(barRule).not.toContain("will-change:")
- expect(styles).toContain(".haze::before")
- expect(styles).not.toContain("clip-path")
- expect(styles).not.toContain("repeating-linear-gradient")
-
- const peakProfiles = ["fine", "broad"].map((layer) => bars
- .filter((bar) => bar.dataset.layer === layer)
- .map((bar) => ({
- position: numberProperty(bar, "--bar-x"),
- height: numberProperty(bar, "--bar-height"),
- })))
- const meanHeight = (profile: Array<{ height: number }>) =>
- profile.reduce((sum, peak) => sum + peak.height, 0) / profile.length
- const hasRiseAndFall = (profile: Array<{ height: number }>) => {
- const changes = profile.slice(1).map((peak, index) => peak.height - profile[index]!.height)
- return changes.some((change) => change > 0) && changes.some((change) => change < 0)
- }
- for (const profile of peakProfiles) {
- expect(profile.find(({ position }) => position === 0)?.height).toBe(0)
- expect(profile.find(({ position }) => position === 100)?.height).toBe(0)
- const center = profile.filter(({ position }) => position >= 25 && position <= 75)
- const leftShoulder = profile.filter(({ position }) => position > 12.5 && position < 25)
- const leftOuter = profile.filter(({ position }) => position <= 12.5)
- const rightShoulder = profile.filter(({ position }) => position > 75 && position < 87.5)
- const rightOuter = profile.filter(({ position }) => position >= 87.5)
- expect(meanHeight(leftOuter)).toBeLessThan(meanHeight(leftShoulder))
- expect(meanHeight(leftShoulder)).toBeLessThan(meanHeight(center))
- expect(meanHeight(rightOuter)).toBeLessThan(meanHeight(rightShoulder))
- expect(meanHeight(rightShoulder)).toBeLessThan(meanHeight(center))
- expect(hasRiseAndFall(profile.filter(({ position }) => position <= 25))).toBe(true)
- expect(hasRiseAndFall(profile.filter(({ position }) => position >= 75).reverse())).toBe(true)
- }
-
- expect(new Set(bars.map((bar) => numberProperty(bar, "--bar-duration"))).size)
- .toBeGreaterThan(12)
- expect(new Set(bars.map((bar) => numberProperty(bar, "--bar-min-scale"))).size)
- .toBeGreaterThan(10)
- expect(new Set(bars.map((bar) => bar.dataset.motion)).size).toBe(bars.length)
- expect(new Set(bars.map((bar) => [
- bar.style.getPropertyValue("--bar-min-scale"),
- bar.style.getPropertyValue("--bar-duration"),
- bar.style.getPropertyValue("--bar-delay"),
- ].join("/"))).size).toBe(bars.length)
- const directionsAtStart = new Set(bars
- .filter((bar) => numberProperty(bar, "--bar-height") > 0)
- .map((bar) => {
- const duration = numberProperty(bar, "--bar-duration")
- const delay = numberProperty(bar, "--bar-delay")
- expect(delay).toBeLessThan(0)
- const phase = (-delay) % (duration * 2)
- return phase < duration ? "rising" : "falling"
- }))
- expect(directionsAtStart).toEqual(new Set(["rising", "falling"]))
-
- expect(styles).toMatch(
- /@media \(prefers-reduced-motion: reduce\)[\s\S]*?\.bar,[\s\S]*?\.haze,[\s\S]*?\.haze::before[\s\S]*?animation:\s*none/,
- )
- expect(styles).not.toMatch(/#[\da-f]{3,8}\b/i)
- expect(styles).not.toMatch(/oklch\(/)
- })
-})
diff --git a/src/web/src/components/community/messages/initial-position-aurora.module.css b/src/web/src/components/community/messages/initial-position-aurora.module.css
deleted file mode 100644
index e6f13439f..000000000
--- a/src/web/src/components/community/messages/initial-position-aurora.module.css
+++ /dev/null
@@ -1,192 +0,0 @@
-.aurora {
- --aurora-opacity: calc(var(--initial-position-aurora-opacity) * 0.5);
- position: absolute;
- right: calc(var(--community-composer-inline-end) + var(--community-composer-top-radius));
- bottom: 0;
- left: calc(var(--community-composer-inline-start) + var(--community-composer-top-radius));
- z-index: 0;
- height: 3.5rem;
- overflow: hidden;
- pointer-events: none;
- opacity: 0;
- will-change: opacity;
-}
-
-.visible {
- opacity: var(--aurora-opacity);
- animation: aurora-enter 300ms var(--ease-out) both;
-}
-
-.leaving {
- opacity: 0;
- animation: aurora-leave 300ms linear both;
-}
-
-.peaks,
-.haze {
- position: absolute;
- inset: 0;
- transform-origin: center bottom;
-}
-
-.peaks {
- z-index: 2;
- opacity: var(--initial-position-aurora-glint-opacity);
- filter:
- drop-shadow(0 -2px 5px color-mix(in oklab, var(--initial-position-aurora-blue) 48%, transparent))
- drop-shadow(0 -1px 3px color-mix(in oklab, var(--initial-position-aurora-magenta) 38%, transparent));
-}
-
-.fineBars,
-.broadBars {
- position: absolute;
- inset: 0;
-}
-
-.fineBars {
- filter: blur(1px);
-}
-
-.broadBars {
- opacity: 0.72;
- filter: blur(5px);
-}
-
-.bar {
- --bar-color: var(--initial-position-aurora-cyan);
- position: absolute;
- bottom: 0;
- left: var(--bar-x);
- width: var(--bar-width);
- height: var(--bar-height);
- transform: scaleY(var(--bar-min-scale));
- transform-origin: center bottom;
- background: linear-gradient(
- to top,
- color-mix(in oklab, var(--bar-color) var(--bar-strength), transparent),
- transparent
- );
- animation: aurora-bar-length var(--bar-duration) var(--ease-in-out) var(--bar-delay) infinite alternate both;
-}
-
-.bar[data-tone="blue"] {
- --bar-color: var(--initial-position-aurora-blue);
-}
-
-.bar[data-tone="violet"] {
- --bar-color: var(--initial-position-aurora-violet);
-}
-
-.bar[data-tone="magenta"] {
- --bar-color: var(--initial-position-aurora-magenta);
-}
-
-.haze {
- z-index: 1;
- background:
- radial-gradient(
- 12% 58% at 10% 100%,
- color-mix(in oklab, var(--initial-position-aurora-cyan) 58%, transparent),
- transparent 64%
- ),
- radial-gradient(
- 22% 95% at 31% 100%,
- color-mix(in oklab, var(--initial-position-aurora-blue) 52%, transparent),
- transparent 66%
- ),
- radial-gradient(
- 20% 88% at 52% 100%,
- color-mix(in oklab, var(--initial-position-aurora-violet) 58%, transparent),
- transparent 64%
- ),
- radial-gradient(
- 16% 92% at 68% 100%,
- color-mix(in oklab, var(--initial-position-aurora-blue) 46%, transparent),
- transparent 64%
- ),
- radial-gradient(
- 14% 62% at 90% 100%,
- color-mix(in oklab, var(--initial-position-aurora-magenta) 62%, transparent),
- transparent 66%
- );
- opacity: var(--initial-position-aurora-bloom-opacity);
- filter: blur(16px);
- mask-image: linear-gradient(to top, black 0%, black 34%, transparent 100%);
- animation: aurora-haze 3.1s var(--ease-in-out) -2.2s infinite alternate;
-}
-
-.haze::before {
- position: absolute;
- inset: 0;
- content: "";
- transform-origin: center bottom;
- background:
- radial-gradient(14% 54% at 18% 100%, color-mix(in oklab, var(--initial-position-aurora-cyan) 58%, transparent), transparent 66%),
- radial-gradient(18% 82% at 45% 100%, color-mix(in oklab, var(--initial-position-aurora-magenta) 54%, transparent), transparent 64%),
- radial-gradient(20% 76% at 72% 100%, color-mix(in oklab, var(--initial-position-aurora-violet) 52%, transparent), transparent 66%),
- radial-gradient(10% 44% at 92% 100%, color-mix(in oklab, var(--initial-position-aurora-cyan) 46%, transparent), transparent 64%);
- filter: blur(9px);
- will-change: transform, opacity;
- animation: aurora-secondary-haze 3.7s var(--ease-in-out) -0.9s infinite alternate;
-}
-
-@keyframes aurora-enter {
- from { opacity: 0; }
- to { opacity: var(--aurora-opacity); }
-}
-
-@keyframes aurora-leave {
- from { opacity: var(--aurora-opacity); }
- to { opacity: 0; }
-}
-
-@keyframes aurora-bar-length {
- from {
- transform: scaleY(var(--bar-min-scale));
- }
-
- to {
- transform: scaleY(1);
- }
-}
-
-@keyframes aurora-haze {
- from {
- transform: scaleY(0.88);
- }
-
- to {
- transform: scaleY(1.04);
- }
-}
-
-@keyframes aurora-secondary-haze {
- from {
- transform: scaleY(1.02);
- opacity: 0.7;
- }
-
- to {
- transform: scaleY(0.86);
- opacity: 1;
- }
-}
-
-@media (max-width: 40rem) {
- .aurora {
- height: 3rem;
- }
-}
-
-@media (prefers-reduced-motion: reduce) {
- .aurora {
- --aurora-opacity: calc(var(--initial-position-aurora-reduced-opacity) * 0.5);
- }
-
- .bar,
- .haze,
- .haze::before {
- animation: none;
- transform: none;
- }
-}
diff --git a/src/web/src/components/community/messages/initial-position-aurora.tsx b/src/web/src/components/community/messages/initial-position-aurora.tsx
deleted file mode 100644
index 2f59bb400..000000000
--- a/src/web/src/components/community/messages/initial-position-aurora.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import type { CSSProperties } from "react"
-import { tid } from "@/lib/community/testids"
-import type { InitialPositionPhase } from "./initial-position-transition"
-import styles from "./initial-position-aurora.module.css"
-
-type AuroraTone = "cyan" | "blue" | "violet" | "magenta"
-type AuroraLayer = "fine" | "broad"
-type AuroraBarShape = readonly [
- x: number,
- widthRem: number,
- maxHeight: number,
- tone: AuroraTone,
- strength?: number,
-]
-
-type AuroraBarStyle = CSSProperties & {
- "--bar-x": string
- "--bar-width": string
- "--bar-height": string
- "--bar-min-scale": string
- "--bar-duration": string
- "--bar-delay": string
- "--bar-strength": string
-}
-
-const BAR_MIN_SCALES = [
- 0.42, 0.68, 0.52, 0.73, 0.46, 0.63, 0.57, 0.71, 0.49, 0.65, 0.54, 0.75, 0.6,
-] as const
-const BAR_DURATIONS_MS = [
- 1_780, 2_230, 1_960, 2_410, 2_110, 1_840, 2_320, 2_050, 2_170,
- 1_890, 2_470, 1_990, 2_280, 1_760, 2_380, 2_080, 2_210,
-] as const
-const BAR_PHASE_CYCLES = [
- 0.15, 1.28, 0.39, 1.61, 0.72, 1.9, 0.06, 1.43, 0.84, 1.13,
- 0.52, 1.77, 0.26, 1.55, 0.95, 1.04, 0.63, 1.87, 0.31,
-] as const
-
-const FINE_BAR_SHAPES = [
- [0, 0.08, 0, "cyan"],
- [2, 0.16, 5, "cyan"],
- [3.4, 0.1, 12, "cyan"],
- [5.5, 0.24, 8, "cyan"],
- [6.8, 0.12, 19, "cyan"],
- [8.4, 0.12, 14, "cyan"],
- [10.1, 0.1, 26, "blue"],
- [12.3, 0.14, 21, "cyan"],
- [17, 0.18, 36, "blue"],
- [22.5, 0.14, 55, "violet"],
- [24.2, 0.1, 34, "blue"],
- [27, 0.28, 84, "blue"],
- [28.4, 0.12, 46, "blue"],
- [30.6, 0.14, 61, "violet"],
- [34.8, 0.1, 31, "magenta"],
- [36, 0.17, 43, "magenta"],
- [38.2, 0.11, 58, "violet"],
- [40.5, 0.22, 67, "violet"],
- [42.1, 0.1, 39, "blue"],
- [45.5, 0.3, 91, "magenta"],
- [47.1, 0.12, 48, "violet"],
- [55, 0.13, 38, "blue"],
- [57.3, 0.1, 50, "violet"],
- [60.5, 0.2, 58, "violet"],
- [62.2, 0.1, 35, "magenta"],
- [64, 0.26, 78, "magenta"],
- [65.7, 0.12, 45, "violet"],
- [68.2, 0.1, 27, "blue"],
- [73.5, 0.16, 45, "cyan"],
- [75.1, 0.1, 63, "cyan"],
- [77, 0.12, 32, "blue"],
- [82.1, 0.11, 42, "violet"],
- [84.2, 0.12, 33, "magenta"],
- [86, 0.28, 46, "magenta"],
- [88.2, 0.1, 27, "magenta"],
- [90, 0.16, 34, "violet"],
- [92.4, 0.1, 15, "blue"],
- [96.5, 0.22, 6, "cyan"],
- [100, 0.08, 0, "cyan"],
-] satisfies readonly AuroraBarShape[]
-
-const BROAD_BAR_SHAPES = [
- [0, 0.5, 0, "cyan", 68],
- [4.5, 1.15, 11, "cyan", 78],
- [11, 0.7, 7, "cyan", 68],
- [18, 1, 32, "blue", 70],
- [27.5, 1.2, 79, "blue", 76],
- [39, 1.65, 61, "violet", 74],
- [46, 1.05, 88, "magenta", 82],
- [62, 1.8, 70, "violet", 70],
- [74, 0.85, 47, "cyan", 72],
- [82, 1, 19, "violet", 72],
- [87, 1.5, 25, "magenta", 78],
- [96, 0.75, 8, "cyan", 68],
- [100, 0.5, 0, "cyan", 68],
-] satisfies readonly AuroraBarShape[]
-
-function buildBars(layer: AuroraLayer, shapes: readonly AuroraBarShape[], motionOffset: number) {
- return shapes.map(([x, widthRem, maxHeight, tone, strength = 100], index) => {
- const motionIndex = index + motionOffset
- const minScale = BAR_MIN_SCALES[motionIndex % BAR_MIN_SCALES.length]!
- const durationMs = BAR_DURATIONS_MS[motionIndex % BAR_DURATIONS_MS.length]!
- const phaseCycles = BAR_PHASE_CYCLES[motionIndex % BAR_PHASE_CYCLES.length]!
- return {
- layer,
- x,
- widthRem,
- maxHeight,
- tone,
- strength,
- motionIndex,
- minScale,
- durationMs,
- delayMs: -Math.round(durationMs * phaseCycles),
- }
- })
-}
-
-const FINE_BARS = buildBars("fine", FINE_BAR_SHAPES, 0)
-const BROAD_BARS = buildBars("broad", BROAD_BAR_SHAPES, FINE_BAR_SHAPES.length)
-const AURORA_LAYERS = [
- { layer: "fine", className: styles.fineBars, bars: FINE_BARS },
- { layer: "broad", className: styles.broadBars, bars: BROAD_BARS },
-] as const
-
-function barStyle(bar: ReturnType<typeof buildBars>[number]): AuroraBarStyle {
- return {
- "--bar-x": `${bar.x}%`,
- "--bar-width": `${bar.widthRem}rem`,
- "--bar-height": `${bar.maxHeight}%`,
- "--bar-min-scale": String(bar.minScale),
- "--bar-duration": `${bar.durationMs}ms`,
- "--bar-delay": `${bar.delayMs}ms`,
- "--bar-strength": `${bar.strength}%`,
- }
-}
-
-export function InitialPositionAurora({ phase }: { phase: InitialPositionPhase }) {
- if (phase !== "aurora" && phase !== "revealing") return null
-
- return (
- <div
- aria-hidden="true"
- data-testid={tid.initialPositionAurora}
- data-phase={phase}
- className={`${styles.aurora} ${phase === "aurora" ? styles.visible : styles.leaving}`}
- >
- <div className={styles.peaks}>
- {AURORA_LAYERS.map(({ layer, className, bars }) => (
- <div key={layer} data-aurora-layer={layer} className={className}>
- {bars.map((bar) => (
- <span
- key={bar.x}
- data-aurora-bar
- data-layer={bar.layer}
- data-motion={bar.motionIndex}
- data-tone={bar.tone}
- className={styles.bar}
- style={barStyle(bar)}
- />
- ))}
- </div>
- ))}
- </div>
- <div className={styles.haze} />
- </div>
- )
-}
diff --git a/src/web/src/components/community/messages/initial-position-transition.dom.test.ts b/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
index 025e49348..e83585585 100644
--- a/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
+++ b/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
@@ -3,8 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, render } from "@/test/react-dom-harness"
import {
INITIAL_POSITION_CROSSFADE_MS,
- INITIAL_POSITION_EFFECT_DELAY_MS,
- INITIAL_POSITION_MINIMUM_EFFECT_MS,
INITIAL_POSITION_TIMEOUT_MS,
useInitialPositionTransition,
} from "./initial-position-transition"
@@ -56,76 +54,76 @@ describe("useInitialPositionTransition", () => {
phase: "revealed",
showSkeleton: false,
contentVisible: true,
- auroraVisible: false,
})
expect(vi.getTimerCount()).toBe(0)
})
- it("skips aurora when position settles before the 800ms threshold", () => {
- expect(INITIAL_POSITION_EFFECT_DELAY_MS).toBe(800)
+ it("crossfades as soon as position settles", () => {
const renderer = render(React.createElement(Probe, pending()))
expect(latest.phase).toBe("positioning")
- act(() => vi.advanceTimersByTime(80))
- expect(latest.phase).toBe("positioning")
- act(() => vi.advanceTimersByTime(719))
+ act(() => vi.advanceTimersByTime(799))
expect(latest.phase).toBe("positioning")
renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
expect(latest).toMatchObject({
- phase: "revealed",
+ phase: "revealing",
contentVisible: true,
contentInteractive: true,
- auroraVisible: false,
})
- act(() => vi.runAllTimers())
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
expect(latest.phase).toBe("revealed")
})
- it("holds a shown aurora through its entrance and crossfades for 300ms", () => {
- expect(INITIAL_POSITION_MINIMUM_EFFECT_MS).toBeGreaterThanOrEqual(INITIAL_POSITION_CROSSFADE_MS)
+ it("does not let the timeout expose content before position settlement", () => {
const renderer = render(React.createElement(Probe, pending()))
- act(() => vi.advanceTimersByTime(799))
- expect(latest.phase).toBe("positioning")
- act(() => vi.advanceTimersByTime(1))
- expect(latest).toMatchObject({ phase: "aurora", contentVisible: false, auroraVisible: true })
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_TIMEOUT_MS))
+ expect(latest).toMatchObject({
+ phase: "positioning",
+ contentVisible: false,
+ contentInteractive: false,
+ })
renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_MINIMUM_EFFECT_MS - 1))
- expect(latest.phase).toBe("aurora")
- act(() => vi.advanceTimersByTime(1))
- expect(latest).toMatchObject({ phase: "revealing", contentVisible: true, auroraVisible: true })
+ act(() => vi.advanceTimersByTime(0))
+ expect(latest).toMatchObject({
+ phase: "revealing",
+ contentVisible: true,
+ contentInteractive: true,
+ })
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS - 1))
- expect(latest.phase).toBe("revealing")
- act(() => vi.advanceTimersByTime(1))
- expect(latest).toMatchObject({ phase: "revealed", auroraVisible: false })
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
+ expect(latest).toMatchObject({ phase: "revealed", showSkeleton: false })
})
- it("times out to best-known content and ignores every late readiness change", () => {
+ it("preserves the crossfade when settlement arrives after the timeout window", () => {
const renderer = render(React.createElement(Probe, pending()))
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_TIMEOUT_MS))
- expect(latest).toMatchObject({ phase: "revealing", contentVisible: true })
+ act(() => vi.advanceTimersByTime(
+ INITIAL_POSITION_TIMEOUT_MS + INITIAL_POSITION_CROSSFADE_MS,
+ ))
+ expect(latest).toMatchObject({
+ phase: "positioning",
+ contentVisible: false,
+ contentInteractive: false,
+ })
renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
- renderer.rerender(React.createElement(Probe, {
- firstWindowReady: false,
- authoritativeEmpty: false,
- positionSettled: false,
- }))
- expect(latest.phase).toBe("revealing")
-
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
- expect(latest).toMatchObject({ phase: "revealed", showSkeleton: false })
+ act(() => vi.advanceTimersByTime(0))
+ expect(latest).toMatchObject({
+ phase: "revealing",
+ contentVisible: true,
+ contentInteractive: true,
+ })
- renderer.rerender(React.createElement(Probe, pending()))
- act(() => vi.runAllTimers())
- expect(latest).toMatchObject({ phase: "revealed", auroraVisible: false })
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS - 1))
+ expect(latest.phase).toBe("revealing")
+ act(() => vi.advanceTimersByTime(1))
+ expect(latest).toMatchObject({ phase: "revealed" })
})
- it("cleans delayed effect and timeout timers when a keyed mount leaves", () => {
+ it("cleans the timeout timer when a keyed mount leaves", () => {
const renderer = render(React.createElement(Probe, pending()))
- expect(vi.getTimerCount()).toBe(2)
+ expect(vi.getTimerCount()).toBe(1)
renderer.unmount()
expect(vi.getTimerCount()).toBe(0)
})
diff --git a/src/web/src/components/community/messages/initial-position-transition.ts b/src/web/src/components/community/messages/initial-position-transition.ts
index b48ea49d9..c155dd290 100644
--- a/src/web/src/components/community/messages/initial-position-transition.ts
+++ b/src/web/src/components/community/messages/initial-position-transition.ts
@@ -2,15 +2,12 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react"
-export const INITIAL_POSITION_EFFECT_DELAY_MS = 800
-export const INITIAL_POSITION_MINIMUM_EFFECT_MS = 300
export const INITIAL_POSITION_CROSSFADE_MS = 300
export const INITIAL_POSITION_TIMEOUT_MS = 2_000
export type InitialPositionPhase =
| "skeleton"
| "positioning"
- | "aurora"
| "revealing"
| "revealed"
@@ -29,21 +26,24 @@ export function useInitialPositionTransition({
))
const revealedRef = useRef(initiallyRevealed)
const startedAtRef = useRef<number | null>(null)
- const auroraStartedAtRef = useRef<number | null>(null)
useLayoutEffect(() => {
if (revealedRef.current) return
if (!firstWindowReady) {
startedAtRef.current = null
- auroraStartedAtRef.current = null
setPhase("skeleton")
return
}
- if (authoritativeEmpty || (positionSettled && phase !== "aurora")) {
+ if (authoritativeEmpty) {
revealedRef.current = true
setPhase("revealed")
return
}
+ if (positionSettled) {
+ revealedRef.current = true
+ setPhase("revealing")
+ return
+ }
if (startedAtRef.current === null) startedAtRef.current = Date.now()
if (phase === "skeleton") setPhase("positioning")
}, [authoritativeEmpty, firstWindowReady, phase, positionSettled])
@@ -65,45 +65,11 @@ export function useInitialPositionTransition({
INITIAL_POSITION_TIMEOUT_MS - (Date.now() - startedAt),
)
const timeoutTimer = window.setTimeout(() => {
- if (revealedRef.current) return
+ if (revealedRef.current || !positionSettled) return
revealedRef.current = true
setPhase("revealing")
}, timeoutRemaining)
- if (phase === "positioning") {
- const delayRemaining = Math.max(
- 0,
- INITIAL_POSITION_EFFECT_DELAY_MS - (Date.now() - startedAt),
- )
- const auroraTimer = window.setTimeout(() => {
- if (revealedRef.current || positionSettled) return
- auroraStartedAtRef.current = Date.now()
- setPhase("aurora")
- }, delayRemaining)
- return () => {
- window.clearTimeout(auroraTimer)
- window.clearTimeout(timeoutTimer)
- }
- }
-
- if (phase === "aurora" && positionSettled) {
- const auroraStartedAt = auroraStartedAtRef.current ?? Date.now()
- auroraStartedAtRef.current = auroraStartedAt
- const minimumRemaining = Math.max(
- 0,
- INITIAL_POSITION_MINIMUM_EFFECT_MS - (Date.now() - auroraStartedAt),
- )
- const minimumTimer = window.setTimeout(() => {
- if (revealedRef.current) return
- revealedRef.current = true
- setPhase("revealing")
- }, minimumRemaining)
- return () => {
- window.clearTimeout(minimumTimer)
- window.clearTimeout(timeoutTimer)
- }
- }
-
return () => window.clearTimeout(timeoutTimer)
}, [authoritativeEmpty, firstWindowReady, phase, positionSettled])
@@ -120,8 +86,9 @@ export function useInitialPositionTransition({
return {
phase: renderedPhase,
showSkeleton: renderedPhase === "skeleton",
- contentVisible: renderedPhase === "revealing" || renderedPhase === "revealed",
- contentInteractive: renderedPhase === "revealing" || renderedPhase === "revealed",
- auroraVisible: renderedPhase === "aurora" || renderedPhase === "revealing",
+ contentVisible: (authoritativeEmpty || positionSettled)
+ && (renderedPhase === "revealing" || renderedPhase === "revealed"),
+ contentInteractive: (authoritativeEmpty || positionSettled)
+ && (renderedPhase === "revealing" || renderedPhase === "revealed"),
}
}
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 1a55156f5..0dc2a20a8 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
@@ -104,6 +104,12 @@ vi.mock("@/hooks/community/mutations", () => ({
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: mocks.toastApiError }))
+vi.mock("@/lib/community-db/projections", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/community-db/projections")>(
+ "@/lib/community-db/projections",
+ )
+ return { ...actual, useCanonicalMessagesById: () => undefined }
+})
import {
MessageContextSheet,
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 b1ab02c04..cdf28f057 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -32,6 +32,16 @@ import type { OpenProfile } from "@/components/community/social/profile-types"
import { useHoverCapable } from "@/hooks/use-hover-capable"
import { channelHref } from "@/lib/community/community-route"
import { communityKeys } from "@/lib/query-keys"
+import {
+ materializeCanonicalMessage,
+ materializeCanonicalMessages,
+ useCanonicalMessagesById,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ patchCanonicalCommunityMessage,
+ publishCommunityEmbeddedMessages,
+} from "@/lib/community-db/sync"
export type ReplyTarget = { id: string; authorName: string; text: string }
@@ -79,6 +89,38 @@ type SheetCache = {
messages?: Msg[]
}
+export function messageContextQueryFn(
+ type: ScopeType,
+ channelId: string,
+ targetSeq: number,
+ queryClient: ReturnType<typeof useQueryClient>,
+) {
+ return async ({ signal }: { signal?: AbortSignal } = {}): Promise<SheetCache> => {
+ const publicationToken = captureCommunityLiveSnapshotToken(queryClient)
+ let lookup: { id: string }
+ try {
+ lookup = await apiFetch<{ id: string }>(
+ seqLookupUrl(type, channelId, targetSeq),
+ { signal },
+ )
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) return { notFound: true }
+ throw error
+ }
+ const page = await apiFetchProfiles<MessagesPage>(
+ anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),
+ (response) => messageProfilePatches(response.messages),
+ { signal },
+ )
+ const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
+ publishCommunityEmbeddedMessages(queryClient, {
+ entries: messages.map((message) => ({ channelId, message })),
+ proof: { token: publicationToken, signal },
+ })
+ return { notFound: false, anchorId: lookup.id, messages }
+ }
+}
+
// Apply a reaction toggle to the sheet's own cache — mirrors the reducer
// `togglePageCacheReaction` in mutations/messages.ts but on this hook's flat
// `messages[]` shape instead of the main list's PageCache-of-pages shape.
@@ -125,15 +167,11 @@ function toggleSheetReaction(
* of `<MessageRow>` rows (no MessageList, no virtualization), centers the
* target row on open.
*
- * **Self-contained by design** — reactions, pin, copy, thread, and image
- * preview all live INSIDE the sheet and operate on the sheet's own
- * TanStack cache (a separate query key from the main channel). The main
- * channel's cache is deliberately untouched to avoid re-render storms in the
- * underlying `<MessageList>` and to avoid injecting mid-history rows into the
- * main window that the user would then have to scroll past. The trade-off is
- * that a reaction added here won't show in the main list until the WS event
- * patches it (which already happens on the main cache) — a moment's
- * inconsistency, but the sheet is transient, so it's the right cost.
+ * **Self-contained transport, shared entities** — the sheet keeps its own
+ * anchor/window Query payload, but publishes embedded messages into the same
+ * canonical account collection as every other surface. Actions patch those
+ * canonical rows without injecting mid-history items into the main list's
+ * pagination cache.
*
* Reply is the ONE action that intentionally crosses back into the main
* surface: since the sheet has no composer, clicking Reply on a preview row
@@ -187,6 +225,7 @@ export function MessageContextSheet({
const toggleMark = useToggleMark()
const toggleReactionApi = useToggleReactionApi()
const addReactionApi = useAddReactionApi()
+ const canonicalMessages = useCanonicalMessagesById()
const queryKey = useMemo(
() => communityKeys.messageContext(type, channelId, targetSeq),
@@ -197,31 +236,13 @@ export function MessageContextSheet({
const query = useQuery({
queryKey,
enabled: open && !!channelId && !!targetSeq,
- queryFn: async ({ signal }): Promise<SheetCache> => {
- let lookup: { id: string }
- try {
- lookup = await apiFetch<{ id: string }>(
- seqLookupUrl(type, channelId, targetSeq!),
- { signal },
- )
- } catch (e) {
- if (e instanceof ApiError && e.status === 404) return { notFound: true }
- throw e
- }
- const page = await apiFetchProfiles<MessagesPage>(
- anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),
- (response) => messageProfilePatches(response.messages),
- { signal },
- )
- const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
- return { notFound: false, anchorId: lookup.id, messages }
- },
+ queryFn: messageContextQueryFn(type, channelId, targetSeq!, queryClient),
staleTime: 30_000,
})
const renderRows = useMemo<RenderMsg[]>(() => {
if (!query.data || query.data.notFound || !query.data.messages) return []
- const src = query.data.messages
+ const src = materializeCanonicalMessages(query.data.messages, canonicalMessages)
// Same grouping heuristic the main list uses (adjacent same-author within
// ~5 min → collapse header). Inlined here rather than sharing the util
// because the excerpt is small enough that the extra dep isn't worth the
@@ -238,14 +259,19 @@ export function MessageContextSheet({
new Date(m.createdAt).getTime() - new Date(prev.createdAt).getTime() < 5 * 60_000
return { ...m, grouped }
})
- }, [query.data])
+ }, [canonicalMessages, query.data])
const anchorId = query.data && !query.data.notFound ? (query.data.anchorId ?? null) : null
// ── Sheet-local actions ──────────────────────────────────────────────────
const findMessage = useCallback(
- (id: string): Msg | undefined => query.data?.messages?.find((m) => m.id === id),
- [query.data],
+ (id: string): Msg | undefined => {
+ const transport = (canonicalMessages === undefined
+ ? queryClient.getQueryData<SheetCache>(queryKey)?.messages
+ : query.data?.messages)?.find((message) => message.id === id)
+ return transport ? materializeCanonicalMessage(transport, canonicalMessages) : undefined
+ },
+ [canonicalMessages, query.data, queryClient, queryKey],
)
const runReactionIntent = useCallback((
@@ -253,8 +279,7 @@ export function MessageContextSheet({
messageId: string,
emoji: string,
) => {
- const msg = queryClient.getQueryData<SheetCache>(queryKey)
- ?.messages?.find((message) => message.id === messageId)
+ const msg = findMessage(messageId)
if (!msg) return
const currentMe = msg.reactions?.find((r) => r.emoji === emoji)?.me ?? false
intent({
@@ -265,13 +290,28 @@ export function MessageContextSheet({
currentMe,
skipDefaultCache: true,
syncReactionState: (me) => {
- queryClient.setQueryData<SheetCache>(queryKey, (c) =>
- toggleSheetReaction(c, messageId, emoji, currentUser.id, me),
- )
+ if (canonicalMessages === undefined) {
+ queryClient.setQueryData<SheetCache>(queryKey, (cache) =>
+ toggleSheetReaction(cache, messageId, emoji, currentUser.id, me),
+ )
+ } else {
+ patchCanonicalCommunityMessage(queryClient, messageId, (message) => (
+ {
+ ...message,
+ reactions: toggleSheetReaction(
+ { messages: [message] },
+ messageId,
+ emoji,
+ currentUser.id,
+ me,
+ )?.messages?.[0]?.reactions,
+ }
+ ))
+ }
},
onError: (error) => toastApiError(error, "Failed to update reaction"),
})
- }, [channelId, currentUser.id, queryClient, queryKey, type])
+ }, [canonicalMessages, channelId, currentUser.id, findMessage, queryClient, queryKey, type])
const toggleReaction = useCallback((messageId: string, emoji: string) => {
runReactionIntent(toggleReactionApi, messageId, emoji)
diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
index 450eb4d29..cb8d2afe7 100644
--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
@@ -6,6 +6,7 @@ import { act, render as rtlRender } from "@/test/react-dom-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { useMessageListController, type MessageListController } from "./message-list-controller"
import type { ResolvedMessageListProps } from "./message-list-types"
+import { INITIAL_POSITION_CROSSFADE_MS } from "./initial-position-transition"
const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")
const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "utf8")
@@ -245,7 +246,6 @@ describe("useMessageListController", () => {
phase: "revealed",
showSkeleton: false,
contentVisible: true,
- auroraVisible: false,
},
})
expect(vi.getTimerCount()).toBe(0)
@@ -264,10 +264,11 @@ describe("useMessageListController", () => {
}).onInitialPositionSettled
act(() => settle())
expect(latest.initialPosition).toMatchObject({
- phase: "revealed",
+ phase: "revealing",
contentVisible: true,
- auroraVisible: false,
})
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
+ expect(latest.initialPosition.phase).toBe("revealed")
})
it("passes every pagination/anchor input through and gives jump mode server-count precedence", () => {
@@ -399,6 +400,8 @@ describe("useMessageListController", () => {
runNextFrame()
expect(latest.initialPosition.phase).toBe("positioning")
runNextFrame()
+ expect(latest.initialPosition.phase).toBe("revealing")
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
expect(latest.initialPosition.phase).toBe("revealed")
act(() => {
latest.onEnterSelectId("m2")
@@ -603,7 +606,7 @@ describe("useMessageListController", () => {
})
const pendingFrames = [...frameCallbacks.keys()]
expect(pendingFrames).toHaveLength(2)
- expect(vi.getTimerCount()).toBe(2)
+ expect(vi.getTimerCount()).toBe(1)
act(() => renderer!.unmount())
for (const frame of pendingFrames) expect(cancelFrame).toHaveBeenCalledWith(frame)
@@ -622,6 +625,8 @@ describe("useMessageListController", () => {
act(() => (mocks.scrollInputs.at(-1) as {
onInitialPositionSettled: () => void
}).onInitialPositionSettled())
+ expect(latest.initialPosition.phase).toBe("revealing")
+ act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
expect(latest.initialPosition.phase).toBe("revealed")
act(() => latest.jumpTo("m1", "auto"))
for (let index = 0; index < 120; index += 1) runNextFrame()
diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
index fb231fddd..afe8c93ee 100644
--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts
@@ -7,10 +7,6 @@ import * as facade from "./message-list"
import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
-vi.mock("./initial-position-aurora.module.css", () => ({
- default: new Proxy({}, { get: (_target, key) => String(key) }),
-}))
-
type ExpectedMessageListProps = {
channel: string
messages: Msg[]
diff --git a/src/web/src/components/community/messages/message-list-view.dom.test.ts b/src/web/src/components/community/messages/message-list-view.dom.test.ts
index ed493a46b..151b27e6f 100644
--- a/src/web/src/components/community/messages/message-list-view.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-view.dom.test.ts
@@ -31,10 +31,6 @@ vi.mock("./message-share-dialog", () => ({ MessageShareDialog: vi.fn(() => null)
vi.mock("@/components/ui/number-ticker", () => ({
NumberTicker: ({ value }: { value: number }) => React.createElement("ticker", { value }),
}))
-vi.mock("./initial-position-aurora.module.css", () => ({
- default: new Proxy({}, { get: (_target, key) => String(key) }),
-}))
-
const mockedRail = vi.mocked(ComposerAccessoryRail)
const mockedShareDialog = vi.mocked(MessageShareDialog)
@@ -46,7 +42,6 @@ function initialPosition(
showSkeleton: false,
contentVisible: true,
contentInteractive: true,
- auroraVisible: false,
...overrides,
}
}
@@ -167,61 +162,60 @@ describe("renderMessageListView", () => {
expect(content).not.toHaveClass("transition-opacity", "duration-300")
expect(mockedRail).not.toHaveBeenCalled()
const skeleton = renderer.container.querySelector("[data-message-positioning-skeleton]")!
- expect(skeleton).toHaveClass("absolute", "inset-0", "pointer-events-none", "opacity-100")
+ expect(skeleton).toHaveClass(
+ "absolute", "inset-0", "z-20", "pointer-events-none", "opacity-100",
+ )
expect(skeleton.querySelector('[data-slot="skeleton"]')).toBeInTheDocument()
- expect(skeleton.parentElement).toBe(content.parentElement?.parentElement)
})
- it("crossfades content against the pointer-transparent aurora without changing geometry", () => {
+ it("keeps the typed positioning skeleton through a timeout until settlement", () => {
const renderer = render(renderMessageListView(
props({ loading: false }),
controller({
initialPosition: initialPosition({
- phase: "aurora",
+ phase: "positioning",
contentVisible: false,
contentInteractive: false,
- auroraVisible: true,
}),
}),
() => React.createElement("virtual-rows"),
))
const content = () => renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
expect(content()).toHaveClass("opacity-0")
- expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toHaveClass("opacity-100")
expect(content()).not.toHaveClass("transition-opacity", "duration-300")
- expect(renderer.getByTestId("community-initial-position-aurora"))
- .toHaveAttribute("data-phase", "aurora")
+ expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toHaveClass("opacity-100")
+ expect(renderer.container.querySelector("[data-message-positioning-skeleton]"))
+ .toBeInTheDocument()
renderer.rerender(renderMessageListView(
props({ loading: false }),
controller({
initialPosition: initialPosition({
phase: "revealing",
- auroraVisible: true,
+ contentVisible: false,
+ contentInteractive: false,
}),
}),
() => React.createElement("virtual-rows"),
))
- expect(content()).toHaveClass("opacity-100", "transition-opacity", "duration-300", "ease-linear")
- expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toHaveClass("opacity-0", "transition-opacity")
+ expect(content()).toHaveClass("opacity-0")
+ expect(content()).not.toHaveClass("transition-opacity", "duration-300")
const boundary = renderer.container.querySelector("[data-message-scroller-boundary]")!
expect(boundary).toHaveClass("isolate")
expect(renderer.getByTestId("community-message-scroller")).toHaveClass("relative", "z-10")
- expect(boundary.querySelector("accessory-rail")).toBeInTheDocument()
- expect(renderer.getByTestId("community-initial-position-aurora").parentElement).toBe(boundary)
- expect(content()).toHaveAttribute("aria-hidden", "false")
- expect(content()).not.toHaveAttribute("inert")
- expect(renderer.getByTestId("community-initial-position-aurora"))
- .toHaveAttribute("data-phase", "revealing")
+ expect(boundary.querySelector("accessory-rail")).not.toBeInTheDocument()
+ expect(content()).toHaveAttribute("aria-hidden", "true")
+ expect(content()).toHaveAttribute("inert")
renderer.rerender(renderMessageListView(
props({ loading: false }),
- controller({ initialPosition: initialPosition({ phase: "revealed" }) }),
+ controller({ initialPosition: initialPosition({ phase: "revealing" }) }),
() => React.createElement("virtual-rows"),
))
- expect(content()).toHaveClass("opacity-100")
- expect(content()).not.toHaveClass("transition-opacity", "duration-300")
- expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).not.toBeInTheDocument()
+ expect(content()).toHaveClass("opacity-100", "transition-opacity", "duration-300")
+ expect(content()).toHaveAttribute("aria-hidden", "false")
+ expect(content()).not.toHaveAttribute("inert")
+ expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toHaveClass("opacity-0")
})
it("keeps typing ownership out of the message list", () => {
diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsx
index e235cda7c..d775f02d8 100644
--- a/src/web/src/components/community/messages/message-list-view.tsx
+++ b/src/web/src/components/community/messages/message-list-view.tsx
@@ -4,7 +4,6 @@ import { Skeleton } from "@/components/ui/skeleton"
import { tid } from "@/lib/community/testids"
import { ChannelIcon } from "../channels/channel-icon"
import { ComposerAccessoryRail, MessageSelectionFooter } from "./composer-accessory-rail"
-import { InitialPositionAurora } from "./initial-position-aurora"
import { MessageShareDialog } from "./message-share-dialog"
import type { MessageListController } from "./message-list-controller"
import type { ResolvedMessageListProps } from "./message-list-types"
@@ -51,7 +50,7 @@ export function renderMessageListView(
aria-hidden={!controller.initialPosition.showSkeleton && !controller.initialPosition.contentVisible}
inert={!controller.initialPosition.showSkeleton && !controller.initialPosition.contentInteractive}
className={`flex min-h-full flex-col justify-end px-4 pb-4 pt-8 sm:pb-6 ${
- controller.initialPosition.phase === "revealing"
+ controller.initialPosition.phase === "revealing" && controller.initialPosition.contentVisible
? "opacity-100 transition-opacity duration-300 ease-linear motion-reduce:transition-opacity"
: controller.initialPosition.showSkeleton || controller.initialPosition.contentVisible
? "opacity-100"
@@ -116,7 +115,6 @@ export function renderMessageListView(
</div>
</div>
)}
- <InitialPositionAurora phase={controller.initialPosition.phase} />
</div>
</div>
)
diff --git a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
index 63e08fcdb..193de19d7 100644
--- a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
@@ -43,10 +43,6 @@ vi.mock("./message-row", () => ({
}))
vi.mock("./message-share-dialog", () => ({ MessageShareDialog: () => null }))
vi.mock("./typing-indicator", () => ({ TypingIndicator: () => null }))
-vi.mock("./initial-position-aurora.module.css", () => ({
- default: new Proxy({}, { get: (_target, key) => String(key) }),
-}))
-
const target = {
id: "m_target",
type: "chat" as const,
diff --git a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
index ac91b1de1..1f4080a61 100644
--- a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
@@ -6,10 +6,6 @@ import { render } from "@/test/react-dom-harness"
vi.mock("@/components/ui/number-ticker", () => ({
NumberTicker: ({ value }: { value: number }) => React.createElement("span", null, value),
}))
-vi.mock("./initial-position-aurora.module.css", () => ({
- default: new Proxy({}, { get: (_target, key) => String(key) }),
-}))
-
let scrollToDescriptor: PropertyDescriptor | undefined
// Confirms Phase 4's core claim with an automated test rather than relying
@@ -77,6 +73,8 @@ describe("MessageList — loading→loaded mount identity (Phase 4)", () => {
expect(positionedContent).toHaveAttribute("aria-hidden", "true")
expect(positionedContent).toHaveAttribute("inert")
expect(positionedContent).toHaveClass("pointer-events-none", "opacity-0")
+ expect(renderer.container.querySelector("[data-message-positioning-skeleton]"))
+ .toBeInTheDocument()
renderer.rerender(
React.createElement(MessageList, {
diff --git a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
index 035dd319d..bf6abdd29 100644
--- a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
@@ -7,10 +7,6 @@ import { MessageList } from "./message-list"
vi.mock("@/components/ui/number-ticker", () => ({
NumberTicker: ({ value }: { value: number }) => React.createElement("span", null, value),
}))
-vi.mock("./initial-position-aurora.module.css", () => ({
- default: new Proxy({}, { get: (_target, key) => String(key) }),
-}))
-
let scrollTopDescriptor: PropertyDescriptor | undefined
let scrollToDescriptor: PropertyDescriptor | undefined
diff --git a/src/web/src/components/community/messages/message-reactions.dom.test.ts b/src/web/src/components/community/messages/message-reactions.dom.test.ts
index 5325d5d0b..dcf6c2985 100644
--- a/src/web/src/components/community/messages/message-reactions.dom.test.ts
+++ b/src/web/src/components/community/messages/message-reactions.dom.test.ts
@@ -17,8 +17,8 @@ vi.mock("@/hooks/community/use-reaction-details", () => ({
isLoading: false,
}),
}))
-vi.mock("@/stores/community/ws", () => ({
- useCommunityProfile: () => undefined,
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalCommunityProfile: () => undefined,
}))
vi.mock("@/components/ui/dialog", () => ({
Dialog: ({ open, children, ...props }: { open: boolean; children: React.ReactNode }) => {
@@ -218,13 +218,13 @@ describe("MessageReactions", () => {
expect(text).toContain("#0001")
})
- it("keeps an unauthorized actor on the Unknown member fallback", () => {
+ it("keeps an unauthorized actor on the unavailable-member fallback", () => {
vi.useFakeTimers()
const unknownReactions = [{ emoji: "👀", count: 1, me: false, userIds: ["user_3"] }]
const { renderer } = renderReactions(vi.fn(), unknownReactions)
openDetails(renderer, "👀")
const text = byTestId(renderer, tid.reactionMember("user_3")).textContent
- expect(text).toContain("Unknown member")
+ expect(text).toContain("Member unavailable")
expect(text).not.toContain("#000")
})
diff --git a/src/web/src/components/community/messages/message-reactions.tsx b/src/web/src/components/community/messages/message-reactions.tsx
index 0b682c21e..65c9b7a75 100644
--- a/src/web/src/components/community/messages/message-reactions.tsx
+++ b/src/web/src/components/community/messages/message-reactions.tsx
@@ -19,7 +19,7 @@ import {
type ReactionDetailsProfile,
useReactionDetails,
} from "@/hooks/community/use-reaction-details"
-import { useCommunityProfile } from "@/stores/community/ws"
+import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import {
HorizontalOverflowFadeOverlays,
useHorizontalOverflowRail,
@@ -48,8 +48,8 @@ function ReactionMemberRow({
userId: string
authorizedProfile: ReactionDetailsProfile | null | undefined
}) {
- const liveProfile = useCommunityProfile(authorizedProfile ? userId : null)
- const name = authorizedProfile ? (liveProfile?.name ?? authorizedProfile.name) : "Unknown member"
+ const liveProfile = useCanonicalCommunityProfile(authorizedProfile ? userId : null)
+ const name = authorizedProfile ? (liveProfile?.name ?? authorizedProfile.name) : "Member unavailable"
return (
<li data-testid={tid.reactionMember(userId)} className="flex min-h-11 items-center gap-3 rounded-lg px-2 py-2">
<MemberIdentityRow
diff --git a/src/web/src/components/community/messages/message-row.tsx b/src/web/src/components/community/messages/message-row.tsx
index 013f0f885..c9d15d47b 100644
--- a/src/web/src/components/community/messages/message-row.tsx
+++ b/src/web/src/components/community/messages/message-row.tsx
@@ -14,8 +14,7 @@ import type { OpenProfile } from "@/components/community/social/profile-types"
// (which are reference-stable — see MessageList's useCallback bundle) plus the
// message, and binds the per-row (no-arg / emoji-only) handlers ONCE via
// `useCallback` keyed on the id. So `Message` receives stable callbacks and its
-// custom-comparator memo can actually bail out. See
-// plans/community-switch-perf-optimization.md (WS3).
+// custom-comparator memo can actually bail out.
export interface MessageRowProps {
m: RenderMsg
viewerUserId?: string
diff --git a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
index e939947b4..1e8d7f99a 100644
--- a/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.dom.test.ts
@@ -27,8 +27,8 @@ const sessionMocks = vi.hoisted(() => ({
capture: vi.fn(),
}))
-vi.mock("@/stores/community/ws", () => ({
- useProfilesByUserId: () => profileState.map,
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalProfilesByUserId: () => profileState.map,
}))
vi.mock("@/lib/community/share-image-session", () => {
class ShareImageSessionError extends Error {
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index 032d56a6d..ff57ef354 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -17,7 +17,7 @@ import { applyHighlightToRange, clearHighlights, hasHighlights } from "@/lib/com
import { formatMessageTime } from "@/lib/community/format-time"
import type { RenderMsg } from "@/lib/community/models/message"
import { displayReplyContent } from "@/lib/community/reply-content"
-import { useProfilesByUserId } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import { AnimatedAlookLogo } from "@/components/community/shell/animated-alook-logo"
import {
@@ -112,7 +112,7 @@ export function MessageShareDialog({ m, open, onClose }: {
}) {
const messages = useMemo(() => (Array.isArray(m) ? m : [m]), [m])
const mobileNative = isTauri() && isMobile()
- const profilesByUserId = useProfilesByUserId()
+ const profilesByUserId = useCanonicalProfilesByUserId()
const profilesByUserIdRef = useRef(profilesByUserId)
const messagesRef = useRef(messages)
const previewRef = useRef<HTMLDivElement>(null)
@@ -435,7 +435,7 @@ export function MessageShareDialog({ m, open, onClose }: {
: (
<div data-share-identity-id={msg.authorId} className="size-10 shrink-0">
<Avatar
- label={author?.name ?? msg.authorName ?? "Unknown"}
+ label={author?.name ?? msg.authorName ?? "Deleted user"}
src={author?.avatar}
seed={msg.authorId}
size={40}
diff --git a/src/web/src/components/community/messages/message.render.dom.test.ts b/src/web/src/components/community/messages/message.render.dom.test.ts
index 5a67dbe0b..d68728207 100644
--- a/src/web/src/components/community/messages/message.render.dom.test.ts
+++ b/src/web/src/components/community/messages/message.render.dom.test.ts
@@ -18,7 +18,11 @@ import {
} from "./message"
import { EmojiPickerPopover } from "./emoji-picker"
import type { RenderMsg } from "@/lib/community/models/message"
-import { useCommunityWsStore } from "@/stores/community/ws"
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalCommunityProfile: (userId: string | null | undefined) => userId === "u1"
+ ? { userId, name: "Alice", discriminator: "", avatar: "A", avatarVersion: 0 }
+ : undefined,
+}))
vi.mock("./emoji-picker", async () => {
const ReactModule = await import("react")
@@ -182,7 +186,7 @@ vi.mock("@/components/ui/number-ticker", () => ({
React.createElement("span", null, value),
}))
-// WS3 render-behavior tests (see plans/community-switch-perf-optimization.md):
+// Message-row render-behavior tests:
// - the custom memo comparator bails out despite the per-render `m` clone,
// - but does NOT drop legit content/reaction/thread updates,
// - and overlay roots are lazily mounted (bare row until activated).
@@ -339,13 +343,6 @@ function textContent(node: DomTestInstance): string {
beforeEach(() => {
renderCount = 0
- useCommunityWsStore.getState().reset()
- useCommunityWsStore.getState().activateProfileAccount("viewer")
- const profiles = useCommunityWsStore.getState()
- profiles.seedProfiles(profiles.beginProfileSnapshot(), [{
- id: "u1",
- identityAbout: { name: "Alice" },
- }])
const g = globalThis as unknown as { ResizeObserver: unknown; IntersectionObserver: unknown }
g.ResizeObserver = class { observe() {} disconnect() {} unobserve() {} }
g.IntersectionObserver = class { observe() {} disconnect() {} unobserve() {} }
@@ -384,7 +381,7 @@ describe("Message memo comparator", () => {
act(() => renderer!.unmount())
})
- it("keeps the strict Unknown fallback for unresolved live authors", () => {
+ it("keeps the precise deleted-user fallback for unresolved live authors", () => {
let renderer: DomRenderer
act(() => {
renderer = render(makeTree({
@@ -396,7 +393,7 @@ describe("Message memo comparator", () => {
}), { createNodeMock: () => genericMock })
})
- expect(textContent(renderer!.root)).toContain("Unknown")
+ expect(textContent(renderer!.root)).toContain("Deleted user")
expect(textContent(renderer!.root)).not.toContain("Static fixture name")
})
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index 72cc33238..051fdd5d4 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -39,7 +39,7 @@ import {
type MobileReplyGesture,
} from "./mobile-message-gesture"
import { useMobileAvatarMention } from "./use-mobile-avatar-mention"
-import { useCommunityProfile } from "@/stores/community/ws"
+import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import { MessageReactions } from "./message-reactions"
import { RemoteContentImage, RemoteIdentityImage } from "@/components/remote-image/remote-image"
@@ -216,17 +216,17 @@ function MessageImpl({
// default without subscribing at all.
hoverCapable?: boolean
}) {
- const authorProfile = useCommunityProfile(m.authorId)
- const replyAuthorProfile = useCommunityProfile(m.replyTo?.authorId)
+ const authorProfile = useCanonicalCommunityProfile(m.authorId)
+ const replyAuthorProfile = useCanonicalCommunityProfile(m.replyTo?.authorId)
const authorName = m.authorId
- ? (authorProfile?.name ?? "Unknown")
- : (m.authorName ?? "Unknown")
+ ? (authorProfile?.name ?? "Deleted user")
+ : (m.authorName ?? "Deleted user")
const authorAvatar = m.authorId
? (authorProfile?.avatar ?? avatarInitial(authorName))
: (m.authorAvatar ?? avatarInitial(authorName))
const replyAuthorName = m.replyTo?.authorId
- ? (replyAuthorProfile?.name ?? "Unknown")
- : (m.replyTo?.authorName ?? "Unknown")
+ ? (replyAuthorProfile?.name ?? "Deleted user")
+ : (m.replyTo?.authorName ?? "Deleted user")
const visibleContent = displayReplyContent(m.content ?? "", m.replyTo)
// keep the hover toolbar pinned open while its ⋯ dropdown is open
const [toolbarOpen, setToolbarOpen] = useState(false)
@@ -263,8 +263,8 @@ function MessageImpl({
const { data: markedData } = useMessageMarked(m.id, markMenuOpen)
// Lazy-mount the row's Base UI overlay roots (ContextMenu / DropdownMenu /
// EmojiPicker Popover / reaction Tooltips). Eagerly mounting them per visible
- // row was the bulk of the switch re-render storm (FloatingTree/MenuRoot ×1000s
- // — see plans/community-switch-perf-optimization.md). Activate on the first
+ // row was the bulk of the switch re-render storm (FloatingTree/MenuRoot ×1000s).
+ // Activate on the first
// hover OR focus OR keydown/contextmenu — focus/keydown are required for a11y
// (keyboard context menu / Tab-to-row have no pointerenter).
const [activated, setActivated] = useState(false)
diff --git a/src/web/src/components/community/messages/thread-opener.dom.test.ts b/src/web/src/components/community/messages/thread-opener.dom.test.ts
index 2f398ef1e..6961b0774 100644
--- a/src/web/src/components/community/messages/thread-opener.dom.test.ts
+++ b/src/web/src/components/community/messages/thread-opener.dom.test.ts
@@ -6,8 +6,8 @@ const useMessageMock = vi.fn()
vi.mock("@/hooks/community/use-message", () => ({
useMessage: (...args: unknown[]) => useMessageMock(...args),
}))
-vi.mock("@/stores/community/ws", () => ({
- useCommunityProfile: (userId?: string) => userId
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalCommunityProfile: (userId?: string) => userId
? { id: userId, name: "Alice", avatar: "A" }
: undefined,
}))
@@ -49,6 +49,8 @@ describe("ThreadOpener image attachment layout", () => {
renderer = render(
React.createElement(ThreadOpener, {
parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
viewerUserId: "viewer_1",
})
)
@@ -79,6 +81,8 @@ describe("ThreadOpener image attachment layout", () => {
renderer = render(
React.createElement(ThreadOpener, {
parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
viewerUserId: "viewer_1",
onToggleReaction,
})
@@ -114,6 +118,8 @@ describe("ThreadOpener image attachment layout", () => {
renderer = render(
React.createElement(ThreadOpener, {
parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
viewerUserId: "viewer_1",
})
)
@@ -152,7 +158,12 @@ describe("ThreadOpener image attachment layout", () => {
let renderer: ReturnType<typeof render>
act(() => {
renderer = render(
- React.createElement(ThreadOpener, { parentMessageId: "opener_1", onPreviewImage })
+ React.createElement(ThreadOpener, {
+ parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
+ onPreviewImage,
+ })
)
})
const image = renderer!.container.querySelector("img")!
@@ -187,7 +198,12 @@ describe("ThreadOpener image attachment layout", () => {
let renderer: ReturnType<typeof render>
act(() => {
renderer = render(
- React.createElement(ThreadOpener, { parentMessageId: "opener_1", onPreviewAttachment })
+ React.createElement(ThreadOpener, {
+ parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
+ onPreviewAttachment,
+ })
)
})
const card = renderer!.getByTestId("community-attachment-card-notes.md")
@@ -216,7 +232,11 @@ describe("ThreadOpener image attachment layout", () => {
let renderer: ReturnType<typeof render>
act(() => {
renderer = render(
- React.createElement(ThreadOpener, { parentMessageId: "opener_1" })
+ React.createElement(ThreadOpener, {
+ parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
+ })
)
})
@@ -246,6 +266,8 @@ describe("ThreadOpener image attachment layout", () => {
act(() => {
renderer = render(React.createElement(ThreadOpener, {
parentMessageId: "opener_1",
+ parentChannelId: "parent_1",
+ serverId: "server_1",
viewerUserId: "viewer_1",
onOpenProfile,
resolveAuthorMentionText: () => "@Alice#0042",
diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsx
index f05b00521..69fa83584 100644
--- a/src/web/src/components/community/messages/thread-opener.tsx
+++ b/src/web/src/components/community/messages/thread-opener.tsx
@@ -14,7 +14,7 @@ import type { OpenProfile } from "@/components/community/social/profile-types"
import { AttachmentCard } from "./attachment-card"
import { displayReplyContent } from "@/lib/community/reply-content"
import { useMobileAvatarMention } from "./use-mobile-avatar-mention"
-import { useCommunityProfile } from "@/stores/community/ws"
+import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import { useHoverCapable } from "@/hooks/use-hover-capable"
import { MessageReactions } from "./message-reactions"
import { RemoteContentImage } from "@/components/remote-image/remote-image"
@@ -35,6 +35,8 @@ import { RemoteContentImage } from "@/components/remote-image/remote-image"
// reflect here without a page reload once the mutation invalidates this key.
export function ThreadOpener({
parentMessageId,
+ parentChannelId,
+ serverId,
viewerUserId,
onOpenProfile,
onPreviewImage,
@@ -46,6 +48,8 @@ export function ThreadOpener({
onInsertMentionText,
}: {
parentMessageId: string
+ parentChannelId: string | null
+ serverId: string
viewerUserId: string
onOpenProfile?: OpenProfile
onPreviewImage?: (image: ImagePreview) => void
@@ -59,8 +63,11 @@ export function ThreadOpener({
onJump?: () => void
}) {
const hoverCapable = useHoverCapable()
- const { message: msg, isLoading, isError } = useMessage(parentMessageId)
- const authorProfile = useCommunityProfile(msg?.authorId)
+ const { message: msg, isLoading, isError } = useMessage(parentMessageId, {
+ ...(parentChannelId ? { channelId: parentChannelId } : {}),
+ serverId,
+ })
+ const authorProfile = useCanonicalCommunityProfile(msg?.authorId)
const mentionText = msg ? resolveAuthorMentionText?.(msg.authorId) ?? null : null
const avatarMention = useMobileAvatarMention({
onMention: mentionText && onInsertMentionText
@@ -69,8 +76,8 @@ export function ThreadOpener({
onProfileClick: (event) => {
if (msg) {
const name = msg.authorId
- ? (authorProfile?.name ?? "Unknown")
- : (msg.authorName ?? "Unknown")
+ ? (authorProfile?.name ?? msg.authorName ?? "Deleted user")
+ : (msg.authorName ?? "Deleted user")
onOpenProfile?.(name, event, undefined, msg.authorId)
}
},
@@ -94,8 +101,8 @@ export function ThreadOpener({
}
const authorName = msg.authorId
- ? (authorProfile?.name ?? "Unknown")
- : (msg.authorName ?? "Unknown")
+ ? (authorProfile?.name ?? msg.authorName ?? "Deleted user")
+ : (msg.authorName ?? "Deleted user")
const avatarLabel = msg.authorId
? (authorProfile?.avatar ?? avatarInitial(authorName))
: (msg.authorAvatar ?? avatarInitial(authorName))
diff --git a/src/web/src/components/community/shell/community-connecting-indicator.tsx b/src/web/src/components/community/shell/community-connecting-indicator.tsx
index efcd0f579..fd29c15f5 100644
--- a/src/web/src/components/community/shell/community-connecting-indicator.tsx
+++ b/src/web/src/components/community/shell/community-connecting-indicator.tsx
@@ -2,38 +2,23 @@
import { AlookLoading } from "@/components/brand/alook-loading/AlookLoading"
-const CONNECTING_LABEL = "Connecting…"
-
export function CommunityConnectingIndicator({ titleId }: { titleId?: string }) {
return (
<div
role="status"
+ aria-label="Loading"
aria-live="polite"
aria-atomic="true"
- data-slot="text-loader"
- data-variant="default"
className="community-ws-connecting-loader"
>
- {/* Adapted from OpensourceUI's TextLoader. See ../../home/opensourceui-mockups.LICENSE.txt. */}
- <div aria-hidden="true" data-connecting-motion="" className="flex h-36 w-44 items-center justify-center sm:h-40 sm:w-48">
- <AlookLoading size={192} className="scale-90 sm:scale-100" />
- </div>
- <h2
+ <div
id={titleId}
- aria-label={CONNECTING_LABEL}
- className="community-ws-connecting-text justify-center font-heading text-base font-medium"
+ aria-hidden="true"
+ data-connecting-motion=""
+ className="flex h-36 w-44 items-center justify-center sm:h-40 sm:w-48"
>
- {CONNECTING_LABEL.split("").map((letter, index) => (
- <span
- key={`${letter}-${index}`}
- aria-hidden="true"
- className="community-ws-connecting-letter"
- style={{ animationDelay: `${index * 0.09}s` }}
- >
- {letter}
- </span>
- ))}
- </h2>
+ <AlookLoading size={192} className="scale-90 sm:scale-100" />
+ </div>
</div>
)
}
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index 053d05cec..a85a80a6d 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -21,7 +21,7 @@ import {
import { selectUnreadPresentation } from "@/hooks/community/unread-presentation"
import { tid } from "@/lib/community/testids"
import type { CommunityProfile } from "@/lib/community/models/people"
-import { useProfilesByUserId } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
useLayoutEffect,
@@ -165,6 +165,17 @@ function UnreadsTab({ friendRequests, servers, dms, loading, onOpenFriendRequest
</div>
{friendRequests.map((item) => {
const request = item.row
+ if (request.pendingIdentity) {
+ return (
+ <div key={request.id} data-testid={tid.inboxFriendRequest(request.id)} className="flex items-center gap-2 rounded-md px-2 py-2">
+ <Skeleton className="size-7 shrink-0 rounded-full" />
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
+ <Skeleton className="h-3.5 w-28 rounded" />
+ <Skeleton className="h-3 w-40 rounded" />
+ </div>
+ </div>
+ )
+ }
const profile = readCommunityProfile(
profilesByUserId.get(request.userId),
request.userId,
@@ -306,6 +317,17 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProj
{loading && visibleMentions.length === 0 && <InboxRowsSkeleton />}
{!loading && visibleMentions.length === 0 && <EmptyState icon={Inbox} label="No mentions" />}
{visibleMentions.map((mn) => {
+ if (mn.pending) {
+ return (
+ <div key={mn.id} className="flex items-start gap-3 rounded-md p-2" aria-busy="true">
+ <Skeleton className="size-9 shrink-0 rounded-full" />
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
+ <Skeleton className="h-3.5 w-2/5 rounded" />
+ <Skeleton className="h-3 w-3/4 rounded" />
+ </div>
+ </div>
+ )
+ }
const author = readCommunityProfile(
mn.m.authorId ? profilesByUserId.get(mn.m.authorId) : undefined,
mn.m.authorId ?? "",
@@ -474,7 +496,7 @@ export function InboxPopover({
onScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void
surface?: "desktop" | "mobile" | "extension"
}) {
- const profilesByUserId = useProfilesByUserId()
+ const profilesByUserId = useCanonicalProfilesByUserId()
const hasUnreads = hasProjectedUnreads
const hasMentions = hasProjectedMentions
const showUnreadDot = selectUnreadPresentation({
diff --git a/src/web/src/components/community/shell/community-panel.tsx b/src/web/src/components/community/shell/community-panel.tsx
index 6bbfad851..450366f74 100644
--- a/src/web/src/components/community/shell/community-panel.tsx
+++ b/src/web/src/components/community/shell/community-panel.tsx
@@ -18,7 +18,7 @@ import type { RightPanel } from "@/components/community/shell/panel-types"
import type { Msg, RenderMsg, Thread } from "@/lib/community/models/message"
import type { Member } from "@/lib/community/models/people"
import type { CommunityProfile } from "@/lib/community/models/people"
-import { useProfilesByUserId } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
export type CommunityPanelProps = {
@@ -53,7 +53,7 @@ export type CommunityPanelProps = {
export function CommunityPanel(props: CommunityPanelProps) {
const { open, onOpenChange, kind } = props
const { icon: Icon, label } = panelHeading(kind)
- const profilesByUserId = useProfilesByUserId()
+ const profilesByUserId = useCanonicalProfilesByUserId()
return (
<CommunitySheet
diff --git a/src/web/src/components/community/shell/community-pending-frame.dom.test.ts b/src/web/src/components/community/shell/community-pending-frame.dom.test.ts
index 07786e2cf..3a0abe9ee 100644
--- a/src/web/src/components/community/shell/community-pending-frame.dom.test.ts
+++ b/src/web/src/components/community/shell/community-pending-frame.dom.test.ts
@@ -31,8 +31,9 @@ vi.mock("@/components/community/channels/dm-loading-frame", () => ({
}),
}))
vi.mock("@/components/community/channels/conversation-resolution-pending-frame", () => ({
- ConversationResolutionPendingFrame: () => createElement("main", {
+ ConversationResolutionPendingFrame: ({ subtype = "unknown" }: { subtype?: string }) => createElement("main", {
"data-testid": "conversation-resolution",
+ "data-subtype": subtype,
"aria-label": "Resolving conversation",
"aria-busy": "true",
}),
@@ -111,6 +112,17 @@ describe("CommunityPendingFrame", () => {
expect(screen.getByLabelText("Loading server")).toHaveAttribute("aria-busy", "true")
})
+ it("forwards a known navigation subtype without changing route ownership", () => {
+ const rendered = render(createElement(CommunityPendingFrame, {
+ href: "/c/channels/s1/c1",
+ conversationSubtype: "forum",
+ }))
+ expect(screen.getByTestId("conversation-resolution"))
+ .toHaveAttribute("data-subtype", "forum")
+ expect(rendered.container.querySelector('[data-community-main-kind="server-conversation"]'))
+ .toBeInTheDocument()
+ })
+
it("uses a neutral route-resolution frame for malformed paths", () => {
const rendered = renderFrame(["/c/channels/s1/c1", "extra"].join("/"))
expect(screen.getByLabelText("Resolving community route")).toBeInTheDocument()
diff --git a/src/web/src/components/community/shell/community-pending-frame.tsx b/src/web/src/components/community/shell/community-pending-frame.tsx
index 233baf08b..51cdf6bf7 100644
--- a/src/web/src/components/community/shell/community-pending-frame.tsx
+++ b/src/web/src/components/community/shell/community-pending-frame.tsx
@@ -38,10 +38,12 @@ export function CommunityPendingFrame({
href,
reserveBackSlot = false,
plan: suppliedPlan,
+ conversationSubtype,
}: {
href: string
reserveBackSlot?: boolean
plan?: CommunityModulePlan
+ conversationSubtype?: "text" | "forum" | "thread"
}) {
const plan = suppliedPlan ?? resolveCommunityModulePlan(href)
const reserveMeBackSlot = reserveBackSlot || (
@@ -68,7 +70,7 @@ export function CommunityPendingFrame({
content = <ServerLandingPendingFrame />
break
case "server-conversation":
- content = <ConversationResolutionPendingFrame />
+ content = <ConversationResolutionPendingFrame subtype={conversationSubtype} />
break
case "route-resolution":
content = <RouteResolutionPendingFrame />
@@ -80,6 +82,12 @@ export function CommunityPendingFrame({
<div
data-testid={tid.pendingMain(plan.main.kind)}
data-community-main-kind={plan.main.kind}
+ role={plan.main.kind === "server-conversation" ? "status" : undefined}
+ aria-label={
+ plan.main.kind === "server-conversation" && conversationSubtype
+ ? "Resolving conversation"
+ : undefined
+ }
className="flex min-h-0 min-w-0 flex-1 flex-col"
>
{content}
diff --git a/src/web/src/components/community/shell/community-restore-bootstrap.dom.test.tsx b/src/web/src/components/community/shell/community-restore-bootstrap.dom.test.tsx
new file mode 100644
index 000000000..4f5173bb4
--- /dev/null
+++ b/src/web/src/components/community/shell/community-restore-bootstrap.dom.test.tsx
@@ -0,0 +1,97 @@
+import React from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { render, screen } from "@/test/react-dom-harness"
+import { CommunityRestoreBoundary } from "./community-restore-bootstrap"
+
+const restoring = vi.hoisted(() => ({ current: false }))
+const restored = vi.hoisted(() => ({ dataExists: false }))
+const queryClient = vi.hoisted(() => ({
+ getQueryData: vi.fn<() => unknown>(() => undefined),
+}))
+
+vi.mock("@tanstack/react-query", () => ({
+ useIsRestoring: () => restoring.current,
+ useQueryClient: () => queryClient,
+}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useOptionalCommunityDbRegistry: () => ({
+ hasRestoredData: () => restored.dataExists,
+ }),
+}))
+
+beforeEach(() => {
+ restoring.current = false
+ restored.dataExists = false
+ queryClient.getQueryData.mockReset()
+ queryClient.getQueryData.mockReturnValue(undefined)
+})
+
+describe("CommunityRestoreBoundary", () => {
+ it("keeps region-owned skeletons mounted while IndexedDB restore is unresolved", () => {
+ restoring.current = true
+ const renderer = render(React.createElement(
+ CommunityRestoreBoundary,
+ null,
+ React.createElement(
+ "div",
+ { "data-testid": "content" },
+ React.createElement("div", {
+ "data-slot": "skeleton",
+ className: "animate-pulse rounded-md bg-muted",
+ }),
+ ),
+ ))
+
+ const content = screen.getByTestId("content")
+ expect(renderer.container.querySelector('[data-slot="community-restore-bootstrap"]')).toBeNull()
+ expect(renderer.container.querySelector('[data-slot="skeleton"]')).toHaveClass(
+ "animate-pulse",
+ "bg-muted",
+ )
+
+ restoring.current = false
+ renderer.rerender(React.createElement(
+ CommunityRestoreBoundary,
+ null,
+ React.createElement(
+ "div",
+ { "data-testid": "content" },
+ React.createElement("div", { "data-slot": "skeleton" }),
+ ),
+ ))
+ expect(screen.getByTestId("content")).toBe(content)
+ })
+
+ it("marks restore, cached paint, and stable geometry in lifecycle order", () => {
+ const marks: string[] = []
+ vi.spyOn(performance, "mark").mockImplementation((name) => {
+ marks.push(name)
+ return {} as PerformanceMark
+ })
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
+ callback(0)
+ return 1
+ })
+ restored.dataExists = true
+ restoring.current = true
+ const renderer = render(React.createElement(
+ CommunityRestoreBoundary,
+ null,
+ React.createElement("div", { "data-testid": "content" }),
+ ))
+
+ restoring.current = false
+ renderer.rerender(React.createElement(
+ CommunityRestoreBoundary,
+ null,
+ React.createElement("div", { "data-testid": "content" }),
+ ))
+
+ expect(marks).toEqual([
+ "alook:restore:start",
+ "alook:restore:complete",
+ "alook:restore:first-cached-paint",
+ "alook:restore:stable",
+ ])
+ })
+})
diff --git a/src/web/src/components/community/shell/community-restore-bootstrap.tsx b/src/web/src/components/community/shell/community-restore-bootstrap.tsx
new file mode 100644
index 000000000..557e9154a
--- /dev/null
+++ b/src/web/src/components/community/shell/community-restore-bootstrap.tsx
@@ -0,0 +1,30 @@
+"use client"
+
+import { useIsRestoring } from "@tanstack/react-query"
+import { useLayoutEffect, useRef, type ReactNode } from "react"
+import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
+
+export function CommunityRestoreBoundary({ children }: { children: ReactNode }) {
+ const isRestoring = useIsRestoring()
+ const communityDb = useOptionalCommunityDbRegistry()
+ const restoreStarted = useRef(false)
+
+ useLayoutEffect(() => {
+ if (isRestoring && !restoreStarted.current) {
+ restoreStarted.current = true
+ performance.mark("alook:restore:start")
+ return
+ }
+ if (isRestoring || !restoreStarted.current) return
+ performance.mark("alook:restore:complete")
+ const restoredDataExists = communityDb?.hasRestoredData() === true
+ if (restoredDataExists) performance.mark("alook:restore:first-cached-paint")
+ const frame = requestAnimationFrame(() => performance.mark("alook:restore:stable"))
+ return () => cancelAnimationFrame(frame)
+ }, [communityDb, isRestoring])
+
+ // PersistQueryClientProvider keeps network queries paused during restore.
+ // Mount route consumers immediately so each region can either paint its
+ // trusted cache or reuse its existing local skeleton while data is absent.
+ return children
+}
diff --git a/src/web/src/components/community/shell/community-shell-layout.tsx b/src/web/src/components/community/shell/community-shell-layout.tsx
index 9a1e3f913..028214a3c 100644
--- a/src/web/src/components/community/shell/community-shell-layout.tsx
+++ b/src/web/src/components/community/shell/community-shell-layout.tsx
@@ -8,8 +8,10 @@ import {
type CSSProperties,
type ReactNode,
} from "react"
+import { flushSync } from "react-dom"
import {
useDefaultLayout,
+ type GroupImperativeHandle,
type PanelImperativeHandle,
type PanelSize,
} from "react-resizable-panels"
@@ -24,9 +26,13 @@ import type { CommunitySurface } from "@/lib/community/community-route"
import { cn } from "@/lib/utils"
import {
COMMUNITY_RAIL_WIDTH,
+ COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE,
+ COMMUNITY_LAYOUT_PREPAINT_SIDEBAR_WIDTH,
+ COMMUNITY_LAYOUT_PREPAINT_USER_BAR_WIDTH,
COMMUNITY_SIDEBAR_DEFAULT_WIDTH,
COMMUNITY_SIDEBAR_MAX_WIDTH,
COMMUNITY_SIDEBAR_MIN_WIDTH,
+ COMMUNITY_SEPARATOR_WIDTH,
COMMUNITY_USER_BAR_HEIGHT_CSS,
desktopSidebarRestoreTarget,
desktopUserBarInitialOverlayCssWidth,
@@ -36,6 +42,7 @@ import { Shell } from "./shell"
import { useHydratedClient } from "./use-hydrated-client"
const SHELL_SURFACE_CLASS = "rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none"
+const DESKTOP_PREPAINT_MEDIA_QUERY = "(min-width: 640px)"
const communityLayoutStorage: Pick<Storage, "getItem" | "setItem"> = {
getItem: (key) => typeof localStorage === "undefined" ? null : localStorage.getItem(key),
setItem: (key, value) => {
@@ -61,7 +68,26 @@ type CommunityShellLayoutProps = {
type PendingDesktopRestore = {
target: number | string
- resizeRequested: boolean
+ animationFrame: number | null
+}
+
+const DESKTOP_RESTORE_PIXEL_EPSILON = 1 + (1 / 64)
+const DESKTOP_RESTORE_PERCENTAGE_EPSILON = 0.01
+
+function constrainDesktopGeometry(target: number | string) {
+ const root = document.documentElement
+ if (typeof target === "number") {
+ root.style.setProperty(COMMUNITY_LAYOUT_PREPAINT_SIDEBAR_WIDTH, `${target}px`)
+ root.style.setProperty(
+ COMMUNITY_LAYOUT_PREPAINT_USER_BAR_WIDTH,
+ `${desktopUserBarOverlayWidth(target)}px`,
+ )
+ }
+ root.setAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE, "")
+}
+
+function releaseDesktopGeometryConstraint() {
+ document.documentElement.removeAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE)
}
/** The single geometry owner for authenticated and session-pending community shells. */
@@ -90,15 +116,24 @@ export function CommunityShellLayout({
? defaultLayout?.sidebar
: undefined
const sidebarPanelRef = useRef<HTMLDivElement>(null)
+ const panelGroupHandleRef = useRef<GroupImperativeHandle | null>(null)
const sidebarPanelHandleRef = useRef<PanelImperativeHandle | null>(null)
+ const resizeHandleRef = useRef<HTMLDivElement>(null)
const userBarOverlayRef = useRef<HTMLDivElement>(null)
const committedBreakpointRef = useRef<Breakpoint>(breakpoint)
const renderedBreakpointRef = useRef<Breakpoint>(breakpoint)
const desktopSidebarWidthRef = useRef<number | undefined>(undefined)
const pendingDesktopRestoreRef = useRef<PendingDesktopRestore | null>(null)
+ const hydratedLayoutAppliedRef = useRef(false)
useInsertionEffect(() => {
renderedBreakpointRef.current = breakpoint
+ if (breakpoint === "mobile" && pendingDesktopRestoreRef.current !== null) {
+ const { animationFrame } = pendingDesktopRestoreRef.current
+ if (animationFrame !== null) cancelAnimationFrame(animationFrame)
+ pendingDesktopRestoreRef.current = null
+ releaseDesktopGeometryConstraint()
+ }
if (
committedBreakpointRef.current === "mobile"
&& breakpoint === "desktop"
@@ -109,8 +144,9 @@ export function CommunityShellLayout({
desktopSidebarWidthRef.current,
persistedSidebarPercentage,
),
- resizeRequested: false,
+ animationFrame: null,
}
+ constrainDesktopGeometry(pendingDesktopRestoreRef.current.target)
}
}, [breakpoint, persistedSidebarPercentage])
@@ -132,6 +168,90 @@ export function CommunityShellLayout({
desktopSidebarWidthRef.current = sidebarWidth
setDesktopUserBarWidth(sidebarWidth)
}, [setDesktopUserBarWidth])
+ const persistDoubleClickReset = useCallback(() => {
+ const sidebarPanelHandle = sidebarPanelHandleRef.current
+ if (!sidebarPanelHandle) return
+ sidebarPanelHandle.resize(COMMUNITY_SIDEBAR_DEFAULT_WIDTH)
+ queueMicrotask(() => {
+ const layout = panelGroupHandleRef.current?.getLayout()
+ if (!layout || Object.keys(layout).length === 0) return
+ onLayoutChanged(layout, { isUserInteraction: true })
+ })
+ }, [onLayoutChanged])
+
+ useLayoutEffect(() => {
+ const onDoubleClick = (event: MouseEvent) => {
+ const resizeHandle = resizeHandleRef.current
+ if (!resizeHandle) return
+ const rect = resizeHandle.getBoundingClientRect()
+ const hitPadding = 10
+ if (
+ event.clientX >= rect.left - hitPadding
+ && event.clientX <= rect.right + hitPadding
+ && event.clientY >= rect.top
+ && event.clientY <= rect.bottom
+ ) persistDoubleClickReset()
+ }
+ document.addEventListener("dblclick", onDoubleClick, true)
+ return () => document.removeEventListener("dblclick", onDoubleClick, true)
+ }, [persistDoubleClickReset])
+
+ useLayoutEffect(() => {
+ if (
+ defaultLayout === undefined
+ || hydratedLayoutAppliedRef.current
+ ) return
+
+ const panelGroupHandle = panelGroupHandleRef.current
+ if (!panelGroupHandle) return
+ const prepaintSidebarWidth = document.documentElement.hasAttribute(
+ COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE,
+ ) && window.matchMedia(DESKTOP_PREPAINT_MEDIA_QUERY).matches
+ ? sidebarPanelRef.current?.getBoundingClientRect().width
+ : undefined
+ const panelGroupWidth = breakpoint === "desktop"
+ ? sidebarPanelRef.current
+ ?.closest<HTMLElement>('[data-slot="resizable-panel-group"]')
+ ?.getBoundingClientRect().width
+ : undefined
+ const restoredSidebarWidth = panelGroupWidth && panelGroupWidth > COMMUNITY_SEPARATOR_WIDTH
+ ? Math.min(
+ COMMUNITY_SIDEBAR_MAX_WIDTH,
+ Math.max(
+ COMMUNITY_SIDEBAR_MIN_WIDTH,
+ defaultLayout.sidebar / 100 * (panelGroupWidth - COMMUNITY_SEPARATOR_WIDTH),
+ ),
+ )
+ : prepaintSidebarWidth
+ hydratedLayoutAppliedRef.current = true
+ panelGroupHandle.setLayout(defaultLayout)
+ if (restoredSidebarWidth && restoredSidebarWidth > 0) {
+ sidebarPanelHandleRef.current?.resize(restoredSidebarWidth)
+ desktopSidebarWidthRef.current = restoredSidebarWidth
+ setDesktopUserBarWidth(restoredSidebarWidth)
+ } else {
+ userBarOverlayRef.current?.style.setProperty(
+ "--community-desktop-user-bar-width",
+ desktopUserBarInitialOverlayCssWidth(defaultLayout.sidebar),
+ )
+ }
+ }, [breakpoint, defaultLayout, setDesktopUserBarWidth])
+
+ useLayoutEffect(() => {
+ if (
+ busy
+ || defaultLayout === undefined
+ || !hydratedLayoutAppliedRef.current
+ || pendingDesktopRestoreRef.current !== null
+ || !window.matchMedia(DESKTOP_PREPAINT_MEDIA_QUERY).matches
+ ) return
+ // The session-pending shell keeps owning the exact prepaint geometry. Once
+ // the loaded shell has applied the saved layout, retain the constraint for
+ // this commit so the panel library cannot expose its default for one frame.
+ requestAnimationFrame(() => {
+ releaseDesktopGeometryConstraint()
+ })
+ }, [breakpoint, busy, defaultLayout])
useLayoutEffect(() => {
committedBreakpointRef.current = breakpoint
@@ -139,32 +259,108 @@ export function CommunityShellLayout({
if (
breakpoint !== "desktop"
|| pendingRestore === null
- || pendingRestore.resizeRequested
) return
const panelHandle = sidebarPanelHandleRef.current
if (!panelHandle) return
-
- pendingRestore.resizeRequested = true
- panelHandle.resize(pendingRestore.target)
- queueMicrotask(() => {
+ let cancelled = false
+ const restore = () => {
if (
- pendingDesktopRestoreRef.current !== pendingRestore
+ cancelled
+ || pendingDesktopRestoreRef.current !== pendingRestore
|| renderedBreakpointRef.current !== "desktop"
) return
- const imperativeWidth = panelHandle.getSize().inPixels
- const measuredWidth = sidebarPanelRef.current?.getBoundingClientRect().width
- const appliedWidth = imperativeWidth > 0
- ? imperativeWidth
- : measuredWidth && measuredWidth > 0
- ? measuredWidth
+ const groupWidth = sidebarPanelRef.current
+ ?.closest<HTMLElement>('[data-slot="resizable-panel-group"]')
+ ?.getBoundingClientRect().width
+ const panelTrackWidth = groupWidth && groupWidth > COMMUNITY_SEPARATOR_WIDTH
+ ? groupWidth - COMMUNITY_SEPARATOR_WIDTH
+ : undefined
+ const expectedPercentage = typeof pendingRestore.target === "string"
+ ? Number.parseFloat(pendingRestore.target)
+ : panelTrackWidth
+ ? pendingRestore.target / panelTrackWidth * 100
: undefined
- if (appliedWidth === undefined) return
+ // Let the library observe its unconstrained panel geometry while applying
+ // the canonical layout. If it is not ready yet, the constraint is put
+ // back synchronously before the browser can paint.
+ flushSync(() => {
+ releaseDesktopGeometryConstraint()
+ if (expectedPercentage !== undefined) {
+ const groupHandle = panelGroupHandleRef.current
+ const currentKeys = Object.keys(groupHandle?.getLayout() ?? {})
+ const keyOrders = currentKeys.length === 2
+ ? [currentKeys, currentKeys.toReversed()]
+ : [["main", "sidebar"], ["sidebar", "main"]]
+ for (const keys of keyOrders) {
+ const candidate = Object.fromEntries(keys.map((key) => [
+ key,
+ key === "sidebar" ? expectedPercentage : 100 - expectedPercentage,
+ ]))
+ const applied = groupHandle?.setLayout(candidate)
+ if (
+ applied?.sidebar !== undefined
+ && Math.abs(applied.sidebar - expectedPercentage)
+ <= DESKTOP_RESTORE_PERCENTAGE_EPSILON
+ ) break
+ }
+ } else {
+ panelHandle.resize(pendingRestore.target)
+ }
+ })
+ const size = panelHandle.getSize()
+ const expectedWidth = typeof pendingRestore.target === "number"
+ ? pendingRestore.target
+ : panelTrackWidth && expectedPercentage !== undefined
+ ? Math.min(
+ COMMUNITY_SIDEBAR_MAX_WIDTH,
+ Math.max(
+ COMMUNITY_SIDEBAR_MIN_WIDTH,
+ expectedPercentage / 100 * panelTrackWidth,
+ ),
+ )
+ : undefined
+ const appliedPercentage = panelGroupHandleRef.current?.getLayout()?.sidebar
+ ?? size.asPercentage
+ const storeRestored = expectedPercentage === undefined
+ ? expectedWidth !== undefined
+ && Math.abs(size.inPixels - expectedWidth) <= DESKTOP_RESTORE_PIXEL_EPSILON
+ : Math.abs(appliedPercentage - expectedPercentage)
+ <= DESKTOP_RESTORE_PERCENTAGE_EPSILON
+ if (!storeRestored) {
+ constrainDesktopGeometry(pendingRestore.target)
+ pendingRestore.animationFrame = requestAnimationFrame(restore)
+ return
+ }
+
+ const measuredWidth = sidebarPanelRef.current?.getBoundingClientRect().width
+ const appliedWidth = measuredWidth && measuredWidth > 0
+ ? measuredWidth
+ : size.inPixels
+ if (
+ expectedWidth !== undefined
+ && Math.abs(appliedWidth - expectedWidth) > DESKTOP_RESTORE_PIXEL_EPSILON
+ ) {
+ constrainDesktopGeometry(pendingRestore.target)
+ pendingRestore.animationFrame = requestAnimationFrame(restore)
+ return
+ }
desktopSidebarWidthRef.current = appliedWidth
setDesktopUserBarWidth(appliedWidth)
pendingDesktopRestoreRef.current = null
- })
- }, [breakpoint, setDesktopUserBarWidth])
+ }
+ queueMicrotask(restore)
+ return () => {
+ cancelled = true
+ if (pendingRestore.animationFrame !== null) {
+ cancelAnimationFrame(pendingRestore.animationFrame)
+ }
+ if (pendingDesktopRestoreRef.current === pendingRestore) {
+ pendingDesktopRestoreRef.current = null
+ releaseDesktopGeometryConstraint()
+ }
+ }
+ }, [breakpoint, defaultLayout, setDesktopUserBarWidth])
const isDesktop = breakpoint === "desktop"
const isMobileList = breakpoint === "mobile" && surface === "list"
@@ -218,8 +414,8 @@ export function CommunityShellLayout({
)}
>
<ResizablePanelGroup
- key={hydratedClient ? "persisted-layout" : "ssr-layout"}
id="community-shell"
+ groupRef={panelGroupHandleRef}
orientation="horizontal"
disabled={!isDesktop}
className={cn(
@@ -256,7 +452,11 @@ export function CommunityShellLayout({
{sidebar}
</div>
</ResizablePanel>
- <ResizableHandle className={cn("bg-transparent", !isDesktop && "hidden")} />
+ <ResizableHandle
+ className={cn("bg-transparent", !isDesktop && "hidden")}
+ disableDoubleClick
+ elementRef={resizeHandleRef}
+ />
<ResizablePanel
id="main"
groupResizeBehavior="preserve-relative-size"
diff --git a/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts b/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts
index 85e763ed9..af5cad3af 100644
--- a/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts
+++ b/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts
@@ -1,6 +1,6 @@
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, fireEvent, render as renderDom, screen, within } from "@/test/react-dom-harness"
+import { act, fireEvent, render as renderDom, screen } from "@/test/react-dom-harness"
import { tid } from "@/lib/community/testids"
import { useCommunityWsStore } from "@/stores/community/ws"
import { CommunityWsReconnectBoundary } from "./community-ws-reconnect-overlay"
@@ -31,26 +31,6 @@ describe("CommunityWsReconnectBoundary", () => {
return { renderer, focus }
}
- function expectAppEdgeFade(overlay: HTMLElement) {
- const fade = overlay.querySelector<HTMLElement>('[data-slot="app-edge-fade"]')!
- expect(fade).toHaveAttribute("aria-hidden", "true")
- expect(fade).toHaveClass("pointer-events-none", "absolute", "inset-0")
- expect(fade.querySelectorAll("[data-app-edge]")).toHaveLength(2)
- expect(fade.querySelector('[data-app-edge="top"]')).toHaveClass(
- "top-0",
- "h-(--app-edge-fade-size)",
- "from-(--app-bg)",
- "to-transparent",
- )
- expect(fade.querySelector('[data-app-edge="bottom"]')).toHaveClass(
- "bottom-0",
- "h-(--app-edge-fade-size)",
- "from-transparent",
- "to-(--app-bg)",
- )
- expect(fade.querySelectorAll("button, a, input, [tabindex]")).toHaveLength(0)
- }
-
it("leaves connected content interactive without rendering an overlay", () => {
const { renderer } = render()
const content = renderer.container.querySelector(".contents")!
@@ -59,57 +39,32 @@ describe("CommunityWsReconnectBoundary", () => {
expect(screen.queryByTestId(tid.wsReconnectOverlay)).not.toBeInTheDocument()
})
- it("blocks the content and announces a reconnecting state", () => {
+ it("keeps cached content interactive while connecting or reconnecting", () => {
const { renderer, focus } = render()
act(() => useCommunityWsStore.getState().setConnectionStatus("reconnecting"))
const content = renderer.container.querySelector(".contents")!
- expect(content).toHaveAttribute("inert")
- expect(content).toHaveAttribute("aria-hidden", "true")
- const overlay = screen.getByTestId(tid.wsReconnectOverlay)
- expect(overlay).toHaveAttribute("data-ws-status", "reconnecting")
- expect(overlay).toHaveAttribute("aria-modal", "true")
- expect(overlay).toHaveAttribute("tabindex", "-1")
- expect(overlay).toHaveClass(
- "fixed",
- "inset-0",
- "community-ws-reconnect-overlay",
- "z-2147483647",
- "backdrop-blur-sm",
- )
- expect(overlay).toHaveClass("bg-background/60", "supports-backdrop-filter:bg-background/45")
- expectAppEdgeFade(overlay)
- expect(screen.getByRole("status")).toHaveAttribute("aria-atomic", "true")
- expect(screen.getByRole("status")).toHaveAttribute("aria-live", "polite")
- expect(screen.getByRole("status")).toHaveAttribute("data-slot", "text-loader")
- expect(screen.getByRole("status")).toHaveAttribute("data-variant", "default")
- expect(screen.getByRole("heading", { name: "Connecting…" })).toBeInTheDocument()
- const motion = overlay.querySelector<HTMLElement>("[data-connecting-motion]")!
- expect(motion).toHaveAttribute("aria-hidden", "true")
- expect(motion).toHaveClass("h-36", "w-44", "sm:h-40", "sm:w-48", "items-center")
- expect(motion.querySelectorAll("svg")).toHaveLength(5)
- expect(motion.querySelector("[role=status]")).toHaveClass("scale-90", "sm:scale-100")
- expect(motion.querySelector("[role=status]")).toHaveStyle({ width: "192px", height: "192px" })
- expect(overlay.querySelector(".community-ws-connecting-text")).toHaveClass("font-heading")
- expect(overlay.querySelectorAll(".community-ws-connecting-letter")).toHaveLength(11)
- expect(overlay.querySelector(".community-ws-connecting-text")).toHaveTextContent("Connecting…")
- expect(screen.queryByTestId(tid.wsRetry)).not.toBeInTheDocument()
- expect(focus).toHaveBeenCalledOnce()
+ expect(content).not.toHaveAttribute("inert")
+ expect(content).not.toHaveAttribute("aria-hidden")
+ expect(screen.queryByTestId(tid.wsReconnectOverlay)).not.toBeInTheDocument()
+ expect(focus).not.toHaveBeenCalled()
})
- it("shows an accessible mobile-sized Retry action and restores immediately", () => {
+ it("shows a non-modal Retry status without disabling cached content", () => {
const reconnectNow = vi.fn()
useCommunityWsStore.getState().bindReconnectNow(reconnectNow)
const { renderer } = render()
act(() => useCommunityWsStore.getState().setConnectionStatus("failed"))
- const alert = screen.getByRole("alert")
- expect(alert).toHaveAttribute("aria-atomic", "true")
- expect(alert).toHaveAttribute("aria-live", "assertive")
- expect(within(alert).getByRole("heading", { name: "Connection lost" })).toBeInTheDocument()
- expectAppEdgeFade(screen.getByTestId(tid.wsReconnectOverlay))
+ const status = screen.getByRole("status")
+ expect(status).toHaveAttribute("aria-atomic", "true")
+ expect(status).toHaveAttribute("aria-live", "polite")
+ expect(status).not.toHaveAttribute("aria-modal")
+ expect(status).toHaveTextContent("Connection lost")
+ expect(status).toHaveTextContent("Cached content is still available.")
+ expect(renderer.container.querySelector(".contents")).not.toHaveAttribute("inert")
const retry = screen.getByTestId(tid.wsRetry)
- expect(retry).toHaveClass("h-11", "sm:h-10")
+ expect(retry).toHaveClass("h-11", "sm:h-9")
fireEvent.click(retry)
expect(reconnectNow).toHaveBeenCalledOnce()
diff --git a/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx b/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx
index 95dd80b47..f2adde77e 100644
--- a/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx
+++ b/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx
@@ -1,8 +1,6 @@
"use client"
-import { useEffect, useRef, type ReactNode } from "react"
-import { CommunityConnectingIndicator } from "./community-connecting-indicator"
-import { AppEdgeFade } from "@/components/ui/app-edge-fade"
+import type { ReactNode } from "react"
import { WifiOff } from "lucide-react"
import { Button } from "@/components/ui/button"
import { tid } from "@/lib/community/testids"
@@ -11,74 +9,36 @@ import { useCommunityWsStore } from "@/stores/community/ws"
export function CommunityWsReconnectBoundary({ children }: { children: ReactNode }) {
const connectionStatus = useCommunityWsStore((state) => state.connectionStatus)
const reconnectNow = useCommunityWsStore((state) => state.reconnectNow)
- const blocked = connectionStatus !== "connected"
- const dialogRef = useRef<HTMLDivElement>(null)
-
- useEffect(() => {
- if (!blocked) return
- const dialog = dialogRef.current
- dialog?.focus()
- if (typeof document === "undefined") return
- const keepFocusInDialog = (event: FocusEvent) => {
- if (!dialog || dialog.contains(event.target as Node)) return
- dialog.focus()
- }
- document.addEventListener("focusin", keepFocusInDialog)
- return () => document.removeEventListener("focusin", keepFocusInDialog)
- }, [blocked, connectionStatus])
+ const failed = connectionStatus === "failed"
return (
<>
- <div
- className="contents"
- inert={blocked ? true : undefined}
- aria-hidden={blocked ? true : undefined}
- >
- {children}
- </div>
- {blocked && (
+ <div className="contents">{children}</div>
+ {failed && (
<div
- ref={dialogRef}
- role="dialog"
- aria-modal="true"
- aria-labelledby="community-ws-reconnect-title"
- tabIndex={-1}
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
data-testid={tid.wsReconnectOverlay}
data-ws-status={connectionStatus}
- className="community-ws-reconnect-overlay fixed inset-0 z-2147483647 grid place-items-center bg-background/60 px-4 outline-none backdrop-blur-sm supports-backdrop-filter:bg-background/45 motion-safe:animate-in motion-safe:fade-in-0 motion-safe:duration-150"
+ className="fixed bottom-4 right-4 z-50 flex max-w-xs items-center gap-3 rounded-lg border bg-popover p-3 text-popover-foreground shadow-(--e2)"
>
- <AppEdgeFade />
- <div className="relative z-20 flex w-full max-w-xs flex-col items-center text-center text-foreground">
- {connectionStatus === "failed" ? (
- <>
- <div
- role="alert"
- aria-live="assertive"
- aria-atomic="true"
- >
- <div
- aria-hidden="true"
- className="mx-auto mb-4 grid size-10 place-items-center rounded-md bg-destructive/10 text-destructive"
- >
- <WifiOff className="size-5" />
- </div>
- <h2 id="community-ws-reconnect-title" className="font-heading text-base font-medium">
- Connection lost
- </h2>
- </div>
- <Button
- type="button"
- data-testid={tid.wsRetry}
- onClick={reconnectNow}
- className="mt-4 h-11 w-full sm:h-10 sm:w-auto sm:min-w-24"
- >
- Retry
- </Button>
- </>
- ) : (
- <CommunityConnectingIndicator titleId="community-ws-reconnect-title" />
- )}
+ <div aria-hidden="true" className="grid size-9 shrink-0 place-items-center rounded-md bg-warning/10 text-warning">
+ <WifiOff className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="font-heading text-sm font-medium">Connection lost</p>
+ <p className="text-xs text-muted-foreground">Cached content is still available.</p>
</div>
+ <Button
+ type="button"
+ variant="secondary"
+ data-testid={tid.wsRetry}
+ onClick={reconnectNow}
+ className="h-11 shrink-0 sm:h-9"
+ >
+ Retry
+ </Button>
</div>
)}
</>
diff --git a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts b/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
index 3bc0a3f1d..a55a540a0 100644
--- a/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
+++ b/src/web/src/components/community/shell/server-rail.pending.dom.test.ts
@@ -219,6 +219,18 @@ describe("ServerRail one-in-flight structural guard", () => {
expect(homeIndicator()).not.toHaveClass("group-hover:h-5", "group-focus-within:h-5")
})
+ it("does not reconcile again for equivalent canonical projection references", () => {
+ const renderer = render(railElement())
+ mocks.railFolderProps.mockClear()
+
+ renderer.rerender(railElement(folders.map((folder) => ({
+ ...folder,
+ servers: folder.servers.map((server) => ({ ...server })),
+ }))))
+
+ expect(mocks.railFolderProps).toHaveBeenCalledTimes(1)
+ })
+
it.each(["top-level", "folder"] as const)(
"keeps a retained %s Server activation on the latest settled navigation semantics",
async (placement) => {
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index 9d56c5e5a..704db2dc3 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -224,9 +224,10 @@ export const ServerRail = memo(function ServerRail({
}, [])
useLayoutEffect(() => {
+ if (stateDataIdentity === railDataIdentity) return
setState((current) => railStateFromData(serverIds, folders, current.expanded))
setStateDataIdentity(railDataIdentity)
- }, [folders, railDataIdentity, serverIds])
+ }, [folders, railDataIdentity, serverIds, stateDataIdentity])
useLayoutEffect(() => {
serverActivationRef.current = { onServer, onServerNavigate }
diff --git a/src/web/src/components/community/shell/shell-frame-geometry.test.ts b/src/web/src/components/community/shell/shell-frame-geometry.test.ts
index 5e39a1c77..56467e407 100644
--- a/src/web/src/components/community/shell/shell-frame-geometry.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-geometry.test.ts
@@ -48,7 +48,7 @@ describe("desktop community shell geometry", () => {
it("keeps persisted percentages constrained to the panel bounds", () => {
expect(desktopUserBarInitialOverlayCssWidth(24)).toBe(
- `calc(clamp(${COMMUNITY_SIDEBAR_MIN_WIDTH}px, calc(24% - 0.48px), ${COMMUNITY_SIDEBAR_MAX_WIDTH}px) + 58px)`,
+ `calc(clamp(${COMMUNITY_SIDEBAR_MIN_WIDTH}px, calc(24% - 0.72px), ${COMMUNITY_SIDEBAR_MAX_WIDTH}px) + 58px)`,
)
expect(desktopUserBarOverlayCssWidth(24, false)).toBe(
"calc(calc(24% - 0.24px) + 57px)",
diff --git a/src/web/src/components/community/shell/shell-frame-geometry.ts b/src/web/src/components/community/shell/shell-frame-geometry.ts
index 36b276125..665a89bc9 100644
--- a/src/web/src/components/community/shell/shell-frame-geometry.ts
+++ b/src/web/src/components/community/shell/shell-frame-geometry.ts
@@ -9,6 +9,52 @@ export const COMMUNITY_SIDEBAR_MAX_WIDTH = 360
export const COMMUNITY_USER_BAR_BASE_HEIGHT = 60
export const COMMUNITY_USER_BAR_HEIGHT_CSS =
`calc(${COMMUNITY_USER_BAR_BASE_HEIGHT}px + var(--app-safe-area-bottom))`
+export const COMMUNITY_LAYOUT_STORAGE_KEY = "react-resizable-panels:community-shell"
+export const COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE = "data-community-shell-layout"
+export const COMMUNITY_LAYOUT_PREPAINT_SIDEBAR_WIDTH = "--community-shell-prepaint-sidebar-width"
+export const COMMUNITY_LAYOUT_PREPAINT_USER_BAR_WIDTH = "--community-shell-prepaint-user-bar-width"
+
+export const communityShellLayoutBootstrapScript = `
+try {
+ const raw = localStorage.getItem(${JSON.stringify(COMMUNITY_LAYOUT_STORAGE_KEY)});
+ if (raw) {
+ const parsed = JSON.parse(raw);
+ let sidebar = parsed && parsed.sidebar;
+ let main = parsed && parsed.main;
+ if (!Number.isFinite(sidebar) || !Number.isFinite(main)) {
+ const entries = parsed && typeof parsed === "object" ? Object.entries(parsed) : [];
+ if (entries.length === 1) {
+ const ids = entries[0][0].split(",");
+ const layout = entries[0][1] && entries[0][1].layout;
+ if (Array.isArray(layout) && layout.length === ids.length) {
+ sidebar = layout[ids.indexOf("sidebar")];
+ main = layout[ids.indexOf("main")];
+ }
+ }
+ }
+ if (
+ Number.isFinite(sidebar)
+ && Number.isFinite(main)
+ && sidebar >= 0
+ && sidebar <= 100
+ && main >= 0
+ && main <= 100
+ ) {
+ const viewportTrackCorrection = Number((sidebar * ${COMMUNITY_RAIL_WIDTH + (COMMUNITY_SURFACE_BORDER_WIDTH * 2) + COMMUNITY_SEPARATOR_WIDTH} / 100).toFixed(6));
+ const root = document.documentElement;
+ root.style.setProperty(
+ ${JSON.stringify(COMMUNITY_LAYOUT_PREPAINT_SIDEBAR_WIDTH)},
+ "clamp(${COMMUNITY_SIDEBAR_MIN_WIDTH}px, calc(" + sidebar + "vw - " + viewportTrackCorrection + "px), ${COMMUNITY_SIDEBAR_MAX_WIDTH}px)",
+ );
+ root.style.setProperty(
+ ${JSON.stringify(COMMUNITY_LAYOUT_PREPAINT_USER_BAR_WIDTH)},
+ "calc(var(${COMMUNITY_LAYOUT_PREPAINT_SIDEBAR_WIDTH}) + ${COMMUNITY_RAIL_WIDTH + COMMUNITY_SURFACE_BORDER_WIDTH + COMMUNITY_SEPARATOR_WIDTH}px)",
+ );
+ root.setAttribute(${JSON.stringify(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE)}, "");
+ }
+ }
+} catch {}
+`
export function mobileInboxAvailableHeight(
viewportHeight: number,
@@ -36,8 +82,9 @@ export function desktopUserBarOverlayCssWidth(
constrainToPanelBounds: boolean,
) {
const percentage = Math.min(100, Math.max(0, sidebarPercentage))
- const panelTrackInset = COMMUNITY_SURFACE_BORDER_WIDTH
- + (constrainToPanelBounds ? COMMUNITY_SEPARATOR_WIDTH : 0)
+ const panelTrackInset = constrainToPanelBounds
+ ? (COMMUNITY_SURFACE_BORDER_WIDTH * 2) + COMMUNITY_SEPARATOR_WIDTH
+ : COMMUNITY_SURFACE_BORDER_WIDTH
const percentageTrackCorrection = Number(
(percentage * panelTrackInset / 100).toFixed(6),
)
diff --git a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
index aa6048e55..a55b12076 100644
--- a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
@@ -2,20 +2,36 @@ import { createElement, useLayoutEffect, useState, type ReactNode } from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, render } from "@/test/react-dom-harness"
import { ShellFrameView } from "./shell-frame-view"
+import { CommunitySessionPendingFrame } from "./community-session-pending-frame"
import type { CommunityCheckpointPlan, CommunitySurface } from "@/lib/community/community-route"
+import {
+ COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE,
+ desktopUserBarInitialOverlayCssWidth,
+} from "./shell-frame-geometry"
const mocks = vi.hoisted(() => ({
onLayoutChanged: vi.fn(),
defaultLayout: {
current: undefined as { sidebar: number; main: number } | undefined,
},
+ hydratedClient: {
+ current: true,
+ },
defaultLayoutOptions: vi.fn(),
groupProps: vi.fn(),
+ handleProps: vi.fn(),
panelProps: vi.fn(),
sidebarPanelHandle: {
getSize: vi.fn(),
resize: vi.fn(),
},
+ panelGroupHandle: {
+ getLayout: vi.fn(),
+ setLayout: vi.fn(),
+ },
+ sidebarElement: {
+ current: null as HTMLElement | null,
+ },
railProps: vi.fn(),
overlayProps: vi.fn(),
pendingProps: vi.fn(),
@@ -31,8 +47,20 @@ vi.mock("react-resizable-panels", () => ({
}
},
}))
+vi.mock("./use-hydrated-client", () => ({
+ useHydratedClient: () => mocks.hydratedClient.current,
+}))
+vi.mock("@/hooks/use-mobile", () => ({
+ useBreakpoint: () => "desktop",
+}))
vi.mock("@/components/ui/resizable", () => ({
ResizablePanelGroup: ({ children, ...props }: Record<string, unknown>) => {
+ useLayoutEffect(() => {
+ const groupRef = props.groupRef as { current: unknown } | undefined
+ if (!groupRef) return
+ groupRef.current = mocks.panelGroupHandle
+ return () => { groupRef.current = null }
+ }, [props.groupRef])
mocks.groupProps(props)
return createElement("div", { "data-panel-group": "", className: props.className }, children as ReactNode)
},
@@ -46,6 +74,11 @@ vi.mock("@/components/ui/resizable", () => ({
}, [props.id, props.panelRef])
mocks.panelProps(props)
return createElement("div", {
+ ref: (node: HTMLDivElement | null) => {
+ if (props.id !== "sidebar") return
+ mocks.sidebarElement.current = node
+ if (node && !node.style.width) node.style.width = "317px"
+ },
"data-slot": "resizable-panel",
"data-testid": props.id,
"data-mobile-active": props["data-mobile-active"],
@@ -54,7 +87,17 @@ vi.mock("@/components/ui/resizable", () => ({
className: props.className,
}, children as ReactNode)
},
- ResizableHandle: (props: Record<string, unknown>) => createElement("div", { "data-panel-handle": "", className: props.className }),
+ ResizableHandle: (props: Record<string, unknown>) => {
+ mocks.handleProps(props)
+ return createElement("div", {
+ "data-panel-handle": "",
+ className: props.className,
+ ref: (node: HTMLDivElement | null) => {
+ const elementRef = props.elementRef as { current: HTMLDivElement | null }
+ elementRef.current = node
+ },
+ })
+ },
}))
vi.mock("@/components/ui/app-surface", () => ({
AppSurface: ({ children, ...props }: Record<string, unknown>) => createElement("div", { ...props, "data-app-surface": "" }, children as ReactNode),
@@ -67,9 +110,11 @@ vi.mock("./server-rail", () => ({
mocks.railProps(props)
return createElement("div", { "data-server-rail": "" })
},
+ ServerRailPending: () => createElement("div", { "data-server-rail-pending": "" }),
}))
vi.mock("./user-bar", () => ({
UserBar: () => createElement("div", { "data-user-bar": "" }),
+ UserBarSkeleton: () => createElement("div", { "data-user-bar-skeleton": "" }),
}))
vi.mock("./community-inbox-popover", () => ({
InboxPopover: () => createElement("div", { "data-inbox-popover": "" }),
@@ -163,7 +208,9 @@ let animateDescriptor: PropertyDescriptor | undefined
describe("ShellFrameView", () => {
beforeEach(() => {
vi.unstubAllGlobals()
+ mocks.onLayoutChanged.mockClear()
mocks.groupProps.mockClear()
+ mocks.handleProps.mockClear()
mocks.panelProps.mockClear()
mocks.sidebarPanelHandle.getSize.mockReset()
mocks.sidebarPanelHandle.getSize.mockReturnValue({
@@ -171,17 +218,22 @@ describe("ShellFrameView", () => {
inPixels: 317,
})
mocks.sidebarPanelHandle.resize.mockReset()
+ mocks.panelGroupHandle.getLayout.mockReset()
+ mocks.panelGroupHandle.setLayout.mockReset()
+ mocks.sidebarElement.current = null
mocks.defaultLayoutOptions.mockClear()
mocks.railProps.mockClear()
mocks.overlayProps.mockClear()
mocks.pendingProps.mockClear()
mocks.channelSkeletonProps.mockClear()
mocks.defaultLayout.current = undefined
+ mocks.hydratedClient.current = true
animateDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "animate")
vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false })))
})
afterEach(() => {
+ document.documentElement.removeAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE)
if (animateDescriptor) Object.defineProperty(HTMLElement.prototype, "animate", animateDescriptor)
else delete (HTMLElement.prototype as unknown as Record<string, unknown>).animate
vi.restoreAllMocks()
@@ -199,18 +251,14 @@ describe("ShellFrameView", () => {
profile,
inbox,
}, createElement("main-content")))
- expect(renderer.container.querySelectorAll("[data-channel-loading-frame]")).toHaveLength(1)
- expect(latestProps(mocks.pendingProps)).toMatchObject({
- href: "/c/me/dm_1",
- reserveBackSlot: true,
- })
+ expect(renderer.container.querySelectorAll("[data-channel-loading-frame]")).toHaveLength(0)
const initialRailWrapper = renderer.container.querySelector('[class*="hidden sm:contents"]')!
expect(initialRailWrapper.className).toContain("min-h-0")
expect(renderer.container.querySelectorAll("sidebar-content")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-user-bar]")).toHaveLength(1)
expect(renderer.container.querySelector('[data-slot="community-user-bar-overlay"]')?.className)
.toContain("max-sm:hidden")
- expect(renderer.container.querySelectorAll("main-content")).toHaveLength(0)
+ expect(renderer.container.querySelectorAll("main-content")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-shell-overlays]")).toHaveLength(0)
expect(latestProps(mocks.panelProps, "sidebar")["data-mobile-hidden"]).toBe(true)
expect(latestProps(mocks.panelProps, "main")["data-mobile-active"]).toBe(true)
@@ -237,8 +285,8 @@ describe("ShellFrameView", () => {
expect(renderer.container.querySelectorAll("[data-server-rail]")).toHaveLength(1)
expect(renderer.container.querySelectorAll("sidebar-content")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-user-bar]")).toHaveLength(1)
- expect(renderer.container.querySelectorAll("[data-channel-loading-frame]")).toHaveLength(1)
- expect(renderer.container.querySelectorAll("main-content")).toHaveLength(0)
+ expect(renderer.container.querySelectorAll("[data-channel-loading-frame]")).toHaveLength(0)
+ expect(renderer.container.querySelectorAll("main-content")).toHaveLength(1)
expect(latestProps(mocks.panelProps, "sidebar")["data-mobile-active"]).toBe(true)
expect(latestProps(mocks.panelProps, "main")["data-mobile-hidden"]).toBe(true)
})
@@ -371,10 +419,151 @@ describe("ShellFrameView", () => {
expect(renderer.container.querySelector<HTMLElement>(
'[data-slot="community-user-bar-overlay"]',
)!.style.getPropertyValue("--community-desktop-user-bar-width")).toBe(
- "calc(clamp(100px, calc(18.75% - 0.375px), 360px) + 58px)",
+ "calc(clamp(100px, calc(18.75% - 0.5625px), 360px) + 58px)",
)
})
+ it("applies persisted layout after hydration without replacing the sidebar tree", async () => {
+ mocks.hydratedClient.current = false
+ const common = {
+ ...extensionProps,
+ breakpoint: "desktop" as const,
+ checkpoint: committedCheckpoint("/c/me", "list"),
+ sidebar: () => createElement("sidebar-content"),
+ cancelPendingNavigation: vi.fn(),
+ rail,
+ profile,
+ inbox,
+ }
+ const renderer = render(createElement(
+ ShellFrameView,
+ common,
+ createElement("main-content"),
+ ))
+ const sidebarBeforeHydration = renderer.container.querySelector("sidebar-content")
+
+ mocks.defaultLayout.current = { sidebar: 18.75, main: 81.25 }
+ mocks.hydratedClient.current = true
+ await act(async () => {
+ renderer.rerender(createElement(
+ ShellFrameView,
+ common,
+ createElement("main-content"),
+ ))
+ })
+
+ expect(renderer.container.querySelector("sidebar-content")).toBe(sidebarBeforeHydration)
+ expect(mocks.panelGroupHandle.setLayout).toHaveBeenCalledOnce()
+ expect(mocks.panelGroupHandle.setLayout).toHaveBeenCalledWith({
+ sidebar: 18.75,
+ main: 81.25,
+ })
+
+ renderer.unmount()
+ })
+
+ it("persists the library double-click reset as a user interaction", async () => {
+ const resetLayout = { sidebar: 26, main: 74 }
+ mocks.panelGroupHandle.getLayout.mockReturnValue(resetLayout)
+ const renderer = render(createElement(ShellFrameView, {
+ ...extensionProps,
+ breakpoint: "desktop",
+ checkpoint: committedCheckpoint("/c/me", "list"),
+ sidebar: () => createElement("sidebar-content"),
+ cancelPendingNavigation: vi.fn(),
+ rail,
+ profile,
+ inbox,
+ }, createElement("main-content")))
+
+ await act(async () => {
+ renderer.container.querySelector<HTMLElement>("[data-panel-handle]")!
+ .dispatchEvent(new MouseEvent("dblclick", { bubbles: true }))
+ })
+
+ expect(mocks.sidebarPanelHandle.resize).toHaveBeenCalledOnce()
+ expect(mocks.sidebarPanelHandle.resize).toHaveBeenCalledWith(317)
+ expect(mocks.onLayoutChanged).toHaveBeenCalledOnce()
+ expect(mocks.onLayoutChanged).toHaveBeenCalledWith(
+ resetLayout,
+ { isUserInteraction: true },
+ )
+ renderer.unmount()
+ })
+
+ it.each([100, 160, 240, 350, 360])(
+ "keeps session-pending and loaded shells at the saved %ipx width from the first animation frame",
+ async (savedWidth) => {
+ const savedPercentage = savedWidth / 10
+ mocks.hydratedClient.current = false
+ mocks.defaultLayout.current = {
+ sidebar: savedPercentage,
+ main: 100 - savedPercentage,
+ }
+ mocks.panelGroupHandle.setLayout.mockImplementation((layout: { sidebar: number }) => {
+ const width = Math.min(360, Math.max(100, layout.sidebar * 10))
+ if (mocks.sidebarElement.current) {
+ mocks.sidebarElement.current.style.width = `${width}px`
+ }
+ })
+ const animationFrames: FrameRequestCallback[] = []
+ vi.stubGlobal("requestAnimationFrame", vi.fn((callback: FrameRequestCallback) => {
+ animationFrames.push(callback)
+ return animationFrames.length
+ }))
+ const frames: Array<{ sidebar: number; userBar: string }> = []
+ const captureNextFrame = async () => {
+ requestAnimationFrame(() => {
+ frames.push({
+ sidebar: Number.parseFloat(mocks.sidebarElement.current?.style.width ?? "0"),
+ userBar: renderer.container.querySelector<HTMLElement>(
+ '[data-slot="community-user-bar-overlay"]',
+ )?.style.getPropertyValue("--community-desktop-user-bar-width") ?? "",
+ })
+ })
+ await act(async () => {
+ for (const callback of animationFrames.splice(0)) callback(0)
+ })
+ }
+ const common = {
+ ...extensionProps,
+ breakpoint: "desktop" as const,
+ sidebar: () => createElement("loaded-sidebar"),
+ cancelPendingNavigation: vi.fn(),
+ rail,
+ profile,
+ inbox,
+ }
+ const renderer = render(createElement(
+ CommunitySessionPendingFrame,
+ { pathname: "/c/channels/s2/c2" },
+ ))
+ expect(renderer.container.querySelector("[data-channel-sidebar-skeleton]"))
+ .not.toBeNull()
+ await captureNextFrame()
+
+ mocks.hydratedClient.current = true
+ renderer.rerender(createElement(
+ ShellFrameView,
+ { ...common, checkpoint: committedCheckpoint("/c/channels/s2/c2", "detail") },
+ createElement("loaded-main"),
+ ))
+ await captureNextFrame()
+
+ expect(frames).toEqual([
+ {
+ sidebar: savedWidth,
+ userBar: desktopUserBarInitialOverlayCssWidth(savedPercentage),
+ },
+ {
+ sidebar: savedWidth,
+ userBar: desktopUserBarInitialOverlayCssWidth(savedPercentage),
+ },
+ ])
+ renderer.unmount()
+ },
+ )
+
it("composes the server-root list surface with desktop rail, sidebar, and landing content", async () => {
const sidebar = vi.fn(() => createElement("sidebar-content"))
const renderer = render(createElement(ShellFrameView, {
@@ -544,6 +733,10 @@ describe("ShellFrameView", () => {
))
expect(animate).not.toHaveBeenCalled()
expect(renderer.container.querySelector("[data-channel-loading-frame]")).not.toBeNull()
+ expect(mocks.pendingProps).toHaveBeenLastCalledWith(expect.objectContaining({
+ href: "/c/channels/s1/c2",
+ conversationSubtype: undefined,
+ }))
expect(renderer.container.querySelector("[data-community-mobile-transition]")).toBeNull()
renderer.rerender(createElement(
@@ -552,6 +745,30 @@ describe("ShellFrameView", () => {
createElement("main-content", { "data-href": "/c/channels/s1/c2" }),
))
expect(animate).not.toHaveBeenCalled()
+
+ renderer.rerender(createElement(
+ ShellFrameView,
+ {
+ ...common,
+ checkpoint: {
+ mode: "same-scope-leaf",
+ surface: "detail",
+ targetHref: "/c/channels/s1/c3",
+ rail: { kind: "keep" },
+ sidebar: { kind: "keep" },
+ main: {
+ kind: "target-skeleton",
+ href: "/c/channels/s1/c3",
+ conversationSubtype: "thread",
+ },
+ },
+ },
+ createElement("main-content"),
+ ))
+ expect(mocks.pendingProps).toHaveBeenLastCalledWith(expect.objectContaining({
+ href: "/c/channels/s1/c3",
+ conversationSubtype: "thread",
+ }))
renderer.rerender(createElement(
ShellFrameView,
{
@@ -721,6 +938,36 @@ describe("ShellFrameView", () => {
it("restores a saved mobile-first percentage without writing storage", async () => {
mocks.defaultLayout.current = { sidebar: 25, main: 75 }
+ document.documentElement.setAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE, "")
+ let desktopGeometry = false
+ let appliedLayout = { sidebar: 91.817, main: 8.183 }
+ mocks.panelGroupHandle.getLayout.mockImplementation(() => appliedLayout)
+ mocks.panelGroupHandle.setLayout.mockImplementation((layout) => {
+ appliedLayout = Object.keys(layout)[0] === "main"
+ ? layout as typeof appliedLayout
+ : { sidebar: 70.54, main: 29.46 }
+ return appliedLayout
+ })
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function () {
+ const isGroup = this.hasAttribute("data-panel-group")
+ const isSidebar = this.closest('[data-testid="sidebar"]') !== null
+ const width = isGroup
+ ? desktopGeometry ? 1_223 : 583
+ : isSidebar
+ ? desktopGeometry ? 305.5 : 583
+ : 0
+ return {
+ bottom: 844,
+ height: 844,
+ left: 56,
+ right: 56 + width,
+ top: 0,
+ width,
+ x: 56,
+ y: 0,
+ toJSON: () => ({}),
+ }
+ })
mocks.sidebarPanelHandle.getSize.mockReturnValue({
asPercentage: 25,
inPixels: 305.5,
@@ -728,7 +975,7 @@ describe("ShellFrameView", () => {
const storageWrite = vi.spyOn(Storage.prototype, "setItem")
const common = {
...extensionProps,
- checkpoint: committedCheckpoint("/c/me/dm_1", "detail"),
+ checkpoint: committedCheckpoint("/c/me", "list"),
sidebar: () => createElement("sidebar-content"),
cancelPendingNavigation: vi.fn(),
rail,
@@ -741,6 +988,7 @@ describe("ShellFrameView", () => {
createElement("main-content"),
))
+ desktopGeometry = true
await act(async () => {
renderer.rerender(createElement(
ShellFrameView,
@@ -748,16 +996,22 @@ describe("ShellFrameView", () => {
createElement("main-content"),
))
})
- expect(mocks.sidebarPanelHandle.resize).toHaveBeenLastCalledWith("25%")
+ expect(mocks.panelGroupHandle.setLayout).toHaveBeenCalledWith({
+ main: 75,
+ sidebar: 25,
+ })
+ expect(mocks.sidebarPanelHandle.resize).not.toHaveBeenCalled()
expect(renderer.container.querySelector<HTMLElement>(
'[data-slot="community-user-bar-overlay"]',
)?.style.getPropertyValue("--community-desktop-user-bar-width")).toBe("363.5px")
+ desktopGeometry = false
renderer.rerender(createElement(
ShellFrameView,
{ ...common, breakpoint: "mobile" },
createElement("main-content"),
))
+ desktopGeometry = true
await act(async () => {
renderer.rerender(createElement(
ShellFrameView,
@@ -765,12 +1019,62 @@ describe("ShellFrameView", () => {
createElement("main-content"),
))
})
- expect(mocks.sidebarPanelHandle.resize).toHaveBeenLastCalledWith(305.5)
+ expect(mocks.panelGroupHandle.setLayout).toHaveBeenLastCalledWith({
+ main: 75,
+ sidebar: 25,
+ })
expect(storageWrite).not.toHaveBeenCalled()
renderer.unmount()
})
+ it("releases a pending desktop geometry constraint on mobile cancel and unmount", async () => {
+ mocks.defaultLayout.current = { sidebar: 25, main: 75 }
+ mocks.panelGroupHandle.getLayout.mockReturnValue({ sidebar: 91.817, main: 8.183 })
+ mocks.panelGroupHandle.setLayout.mockReturnValue({ sidebar: 91.817, main: 8.183 })
+ const common = {
+ ...extensionProps,
+ checkpoint: committedCheckpoint("/c/me", "list"),
+ sidebar: () => createElement("sidebar-content"),
+ cancelPendingNavigation: vi.fn(),
+ rail,
+ profile,
+ inbox,
+ }
+ const renderer = render(createElement(
+ ShellFrameView,
+ { ...common, breakpoint: "mobile" },
+ createElement("main-content"),
+ ))
+
+ await act(async () => {
+ renderer.rerender(createElement(
+ ShellFrameView,
+ { ...common, breakpoint: "desktop" },
+ createElement("main-content"),
+ ))
+ })
+ expect(document.documentElement).toHaveAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE)
+
+ renderer.rerender(createElement(
+ ShellFrameView,
+ { ...common, breakpoint: "mobile" },
+ createElement("main-content"),
+ ))
+ expect(document.documentElement).not.toHaveAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE)
+
+ await act(async () => {
+ renderer.rerender(createElement(
+ ShellFrameView,
+ { ...common, breakpoint: "desktop" },
+ createElement("main-content"),
+ ))
+ })
+ expect(document.documentElement).toHaveAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE)
+ renderer.unmount()
+ expect(document.documentElement).not.toHaveAttribute(COMMUNITY_LAYOUT_PREPAINT_ATTRIBUTE)
+ })
+
it("keeps committed content mounted while same-scope navigation is pending", async () => {
const sidebar = vi.fn(() => createElement("sidebar-content"))
const common = {
diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsx
index d29f06a7a..d831c07a7 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -94,10 +94,11 @@ export function ShellFrameView({
: checkpoint.sidebar.kind === "me-skeleton"
? <DmSidebarSkeleton />
: breakpoint === "desktop" ? sidebar() : sidebar({ noHeader: false })}
- main={checkpoint.main.kind === "target-skeleton" || isInitial ? (
+ main={checkpoint.main.kind === "target-skeleton" ? (
<CommunityPendingFrame
href={checkpoint.targetHref}
reserveBackSlot={surface === "detail"}
+ conversationSubtype={checkpoint.main.conversationSubtype}
/>
) : children}
userBar={(
diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.ts
index 28d8d62a2..b78f66878 100644
--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts
@@ -22,7 +22,8 @@ const mocks = vi.hoisted(() => {
? { id: key.at(-1) }
: undefined,
},
- structuralSnapshot: { current: null as null | Record<string, unknown> },
+ projectedServer: { current: undefined as undefined | Record<string, unknown> },
+ projectedChannel: { current: undefined as undefined | Record<string, unknown> },
breakpoint: { current: "desktop" },
onboardingState: { current: null as Record<string, unknown> | null },
replace: vi.fn(),
@@ -93,14 +94,9 @@ vi.mock("@/stores/community/ws", () => ({
vi.mock("@/contexts/community/current-user", () => ({
useCurrentUser: () => ({ id: "viewer" }),
}))
-vi.mock("@/hooks/community/use-structural-snapshot", () => ({
- useStructuralSnapshot: () => mocks.structuralSnapshot.current,
- hasStructuralServerTree: (server: {
- categories: unknown[]
- channels: unknown[]
- } | null | undefined) => Boolean(
- server && (server.categories.length > 0 || server.channels.length > 0),
- ),
+vi.mock("@/lib/community-db/projections", () => ({
+ useServerTreeProjection: () => mocks.projectedServer.current,
+ useRouteChannelProjection: () => mocks.projectedChannel.current,
}))
vi.mock("./use-shell-rail-controller", () => ({
useShellRailController: (options: unknown) => {
@@ -144,7 +140,8 @@ describe("ShellFrame orchestration", () => {
mocks.pendingHref.current = null
mocks.navigationPending.current = false
mocks.serverCache.clear()
- mocks.structuralSnapshot.current = null
+ mocks.projectedServer.current = undefined
+ mocks.projectedChannel.current = undefined
mocks.breakpoint.current = "desktop"
mocks.onboardingState.current = null
mocks.registerUiHandlers.mockClear()
@@ -253,13 +250,13 @@ describe("ShellFrame orchestration", () => {
}))
})
- it("does not promote a rail-only structural identity to a warm server target", () => {
+ it("uses the canonical server-tree projection as a warm server target", () => {
mocks.currentHref.current = "/c/channels/s1/c1"
mocks.pendingHref.current = "/c/channels/s2"
mocks.navigationPending.current = true
- mocks.structuralSnapshot.current = {
- serverOrder: ["s2"],
- servers: [{ id: "s2", categories: [], channels: [] }],
+ mocks.projectedServer.current = {
+ id: "s2",
+ categories: [{ channels: [{ id: "c2" }] }],
}
render(createElement(ShellFrame, {
@@ -268,23 +265,16 @@ describe("ShellFrame orchestration", () => {
}))
expect(checkpoint()).toMatchObject({
- mode: "cold-scope",
- sidebar: { kind: "server-skeleton", serverId: "s2" },
+ mode: "warm-scope",
+ main: { kind: "keep" },
})
})
- it("uses a captured structural tree as a warm server target", () => {
+ it("carries the canonical target subtype through the navigation checkpoint", () => {
mocks.currentHref.current = "/c/channels/s1/c1"
- mocks.pendingHref.current = "/c/channels/s2"
+ mocks.pendingHref.current = "/c/channels/s1/c2"
mocks.navigationPending.current = true
- mocks.structuralSnapshot.current = {
- serverOrder: ["s2"],
- servers: [{
- id: "s2",
- categories: [],
- channels: [{ id: "c2", name: "cached", type: "text", categoryId: null }],
- }],
- }
+ mocks.projectedChannel.current = { id: "c2", type: "forum" }
render(createElement(ShellFrame, {
...baseProps,
@@ -292,8 +282,12 @@ describe("ShellFrame orchestration", () => {
}))
expect(checkpoint()).toMatchObject({
- mode: "warm-scope",
- main: { kind: "keep" },
+ mode: "same-scope-leaf",
+ main: {
+ kind: "target-skeleton",
+ href: "/c/channels/s1/c2",
+ conversationSubtype: "forum",
+ },
})
})
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index 85ceec60a..f56202ed5 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -8,6 +8,7 @@ import {
advanceCommunityCommittedFrame,
normalizeCommunityHref,
resolveCommunityCheckpointPlan,
+ resolveCommunityModulePlan,
resolveCommunityRoute,
type CommunityCommittedFrame,
} from "@/lib/community/community-route"
@@ -21,10 +22,6 @@ import { useShellProfileController } from "./use-shell-profile-controller"
import { useShellInboxController } from "./use-shell-inbox-controller"
import { useCommunityNavigationController } from "./use-community-navigation-controller"
import type { ShellFrameProps } from "./shell-frame-types"
-import {
- hasStructuralServerTree,
- useStructuralSnapshot,
-} from "@/hooks/community/use-structural-snapshot"
import {
initialUserBarExtensionState,
userBarExtensionReducer,
@@ -36,6 +33,10 @@ import {
registerOwnerServerDeleteRoute,
} from "@/lib/community/eject-server"
import { useNativeMobileBack } from "@/hooks/community/use-native-mobile-back"
+import {
+ useRouteChannelProjection,
+ useServerTreeProjection,
+} from "@/lib/community-db/projections"
/** Shared community shell orchestration for the server and DM layouts. */
export function ShellFrame(props: ShellFrameProps) {
@@ -52,7 +53,6 @@ export function ShellFrame(props: ShellFrameProps) {
} = props
const queryClient = useQueryClient()
const currentUser = useCurrentUser()
- const structuralSnapshot = useStructuralSnapshot(currentUser.id, queryClient)
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const breakpoint = useBreakpoint()
const onboardingState = useCommunityOnboarding()
@@ -89,15 +89,26 @@ export function ShellFrame(props: ShellFrameProps) {
? normalizeCommunityHref(navigation.pendingHref)
: null
const targetServerId = target?.scope.kind === "server" ? target.scope.serverId : null
- const structuralTarget = targetServerId
- ? structuralSnapshot?.servers.find((server) => server.id === targetServerId)
+ const targetModulePlan = navigation.pendingHref
+ ? resolveCommunityModulePlan(navigation.pendingHref)
+ : null
+ const targetChannelId = targetModulePlan?.main.kind === "server-conversation"
+ ? targetModulePlan.main.leafId
: null
+ const targetServer = useServerTreeProjection(targetServerId)
+ const targetRouteChannel = useRouteChannelProjection(targetChannelId)
+ const targetChannel = targetServer?.categories
+ ?.flatMap((category) => category.channels)
+ .find((channel) => channel.id === targetChannelId)
+ ?? targetRouteChannel
+ const targetConversationSubtype = targetChannel?.type === "text"
+ || targetChannel?.type === "forum"
+ || targetChannel?.type === "thread"
+ ? targetChannel.type
+ : undefined
const targetReady = targetServerId
? queryClient.getQueryData(communityKeys.server(targetServerId)) !== undefined
- // `replaceServers` can seed a rail-only identity with an empty tree.
- // Only a snapshot containing actual tree structure can replace the
- // target-scoped cold checkpoint.
- || hasStructuralServerTree(structuralTarget)
+ || targetServer !== undefined
: target?.scope.kind === "me"
? queryClient.getQueryData(communityKeys.dms()) !== undefined
: false
@@ -106,6 +117,7 @@ export function ShellFrame(props: ShellFrameProps) {
targetHref: navigation.pendingHref,
pending: navigation.navigationPending,
targetReady,
+ targetConversationSubtype,
})
const projectedView = checkpoint.rail.kind === "target"
? checkpoint.rail.view
diff --git a/src/web/src/components/community/shell/unresolved-main-skeleton.test.ts b/src/web/src/components/community/shell/unresolved-main-skeleton.test.ts
index 736daa3e1..6fa21c9f1 100644
--- a/src/web/src/components/community/shell/unresolved-main-skeleton.test.ts
+++ b/src/web/src/components/community/shell/unresolved-main-skeleton.test.ts
@@ -4,12 +4,13 @@ import { describe, expect, it } from "vitest"
import { UnresolvedMainSkeleton } from "./unresolved-main-skeleton"
describe("UnresolvedMainSkeleton", () => {
- it("shows the shared Connecting indicator on a static app surface with inert edge fades", () => {
+ it("shows only the neutral loading motion on a static app surface with inert edge fades", () => {
const markup = renderToStaticMarkup(createElement(UnresolvedMainSkeleton))
expect(markup).not.toContain('data-slot="skeleton"')
expect(markup).toContain('role="status"')
- expect(markup).toContain('aria-label="Connecting…"')
+ expect(markup).toContain('aria-label="Loading"')
+ expect(markup).not.toContain("Connecting")
expect(markup).not.toContain('role="dialog"')
expect(markup).not.toContain('aria-modal')
expect(markup).not.toContain('community-ws-reconnect-title')
diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.ts
index 58894a944..964cb301e 100644
--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts
@@ -83,8 +83,13 @@ export function useCommunityNavigationController(
cancelActiveConversationNavigationProof(queryClient)
pendingBaselineRevisionRef.current = committedFrame.revision
pendingBaselineLeafRef.current = committedFrame.leafKey
- setNavigationPending(true)
- setPendingHref(href)
+ // Publish the target checkpoint before Next starts the RSC transition.
+ // Otherwise React can leave this event-batched behind a suspended push and
+ // the committed conversation remains visible while the target is pending.
+ flushSync(() => {
+ setNavigationPending(true)
+ setPendingHref(href)
+ })
router.push(href)
}, [committedFrame.leafKey, committedFrame.revision, publishedHref, queryClient, router])
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 c33c776dc..b3f6ccaa8 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
@@ -83,6 +83,7 @@ vi.mock("@/hooks/community/use-inbox", () => ({
isLoading: false,
hasProjectedUnread: false,
hasOutstandingFriendRequest: true,
+ exactAttentionCount: 7,
}),
useInboxMentions: () => ({ mentions: [mention], isLoading: false, hasProjectedMention: false }),
useInboxMarked: (enabled: boolean) => {
@@ -241,6 +242,7 @@ describe("useShellInboxController", () => {
it("includes friend requests in the global dot while keeping navigation and actions read-neutral", async () => {
const hook = await renderController()
expect(hook.current.hasUnread).toBe(true)
+ expect(hook.current.unreadCount).toBe(8)
expect(hook.current.popoverProps.hasProjectedUnreads).toBe(false)
expect(hook.current.popoverProps.friendRequests).toHaveLength(1)
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 42a214cb4..f6345f391 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,7 +1,6 @@
"use client"
import { useCallback, useRef, useState, type ComponentProps } from "react"
-import { inboxUnreadCount } from "@/lib/community/inbox-unread-count"
import { communityKeys } from "@/lib/query-keys"
import { channelHref } from "@/lib/community/community-route"
import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
@@ -36,6 +35,7 @@ import {
import { startConversationNavigationWarmup } from "@/lib/community/conversation-navigation-warmup"
import type { ConversationNavigationTarget } from "@/lib/community/conversation-navigation-proof"
import { cancelConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"
+import { publishCommunityDmSummary } from "@/lib/community-db/sync"
type UnreadChannel = UnreadServer["channels"][number]
type UnreadChild = UnreadChannel["children"][number]
@@ -70,7 +70,10 @@ export function useShellInboxController({
const unreadFeed = inboxUnreads.servers
const unreadDms = inboxUnreads.dms
const mentions = inboxMentions.mentions
- const loading = inboxUnreads.isLoading || inboxMentions.isLoading
+ const loading = inboxUnreads.isLoading
+ || inboxMentions.isLoading
+ || inboxUnreads.isProjectionPending
+ || inboxMentions.isProjectionPending
const [markedTabOpened, setMarkedTabOpened] = useState(false)
const [activeTab, setActiveTab] = useState<InboxTab>("unreads")
const scrollOffsetsRef = useRef<Record<InboxTab, number>>({
@@ -252,12 +255,14 @@ export function useShellInboxController({
expectedSurfaceKind: "dm",
},
() => {
+ const summary = dmSummaryFromInbox(dm)
queryClient.setQueryData(
communityKeys.dms(),
(previous: DmCache | undefined) => (
- upsertDmSummary(previous, dmSummaryFromInbox(dm))
+ upsertDmSummary(previous, summary)
),
)
+ publishCommunityDmSummary(queryClient, summary)
},
() => {
void startDmRouteVerification(queryClient, dmId).catch(() => undefined)
@@ -321,18 +326,12 @@ export function useShellInboxController({
return {
popoverProps,
- unreadCount: inboxUnreadCount({
- servers: unreadFeed,
- dms: unreadDms,
- mentions: inboxMentions.mentions,
- friendRequestCount: friendRequestActions.items.length,
- pendingChannelIds: [...(inboxUnreads.pendingChannelIds ?? []), ...(inboxMentions.pendingChannelIds ?? [])],
- }),
- unreadCountPartial: Boolean(inboxUnreads.data?.truncated || inboxMentions.data?.truncated),
+ unreadCount: (inboxUnreads.exactAttentionCount ?? 0) + inboxUnreads.friendRequests.length,
+ unreadCountPartial: false,
hasUnread:
inboxUnreads.hasProjectedUnread
|| inboxMentions.hasProjectedMention
- || friendRequestActions.items.length > 0,
+ || inboxUnreads.friendRequests.length > 0,
open: inbox.open,
onOpenChange: inbox.onOpenChange,
}
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
index a2517de14..61bbaf75a 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts
@@ -20,9 +20,8 @@ const mocks = vi.hoisted(() => ({
acceptDm: vi.fn(),
updateProfile: vi.fn(),
uploadAvatar: vi.fn(),
- beginProfileSnapshot: vi.fn(),
- commitProfiles: vi.fn(),
- patchProfiles: vi.fn(),
+ beginCommunityProfileSeed: vi.fn(),
+ writeCommunityProfilePatches: vi.fn(),
communityReset: vi.fn(),
wsReset: vi.fn(),
streamReset: vi.fn(),
@@ -58,12 +57,13 @@ vi.mock("@/stores/community/ws", () => ({
useCommunityWsStore: Object.assign(vi.fn(), {
getState: () => ({
reset: mocks.wsReset,
- beginProfileSnapshot: mocks.beginProfileSnapshot,
- commitProfiles: mocks.commitProfiles,
- patchProfiles: mocks.patchProfiles,
}),
}),
}))
+vi.mock("@/lib/community/profile-seed", () => ({
+ beginCommunityProfileSeed: mocks.beginCommunityProfileSeed,
+ writeCommunityProfilePatches: mocks.writeCommunityProfilePatches,
+}))
vi.mock("@/stores/community/message-stream", () => ({
useMessageStreamStore: Object.assign(vi.fn(), {
getState: () => ({
@@ -180,7 +180,7 @@ describe("useShellProfileController", () => {
statusEmoji: "🙂",
statusText: "Here",
})
- mocks.beginProfileSnapshot.mockReturnValue({ viewerId: "self", accountEpoch: 1, revision: 0 })
+ mocks.beginCommunityProfileSeed.mockReturnValue({ registry: "registry", revision: 0 })
mocks.clearCache.mockResolvedValue(undefined)
mocks.signOut.mockResolvedValue(undefined)
})
@@ -452,9 +452,10 @@ describe("useShellProfileController", () => {
statusEmoji: "🌱",
statusText: "Growing",
})
- expect(mocks.commitProfiles).toHaveBeenCalledWith(
- { viewerId: "self", accountEpoch: 1, revision: 0 },
+ expect(mocks.writeCommunityProfilePatches).toHaveBeenCalledWith(
[expect.objectContaining({ id: "self" })],
+ "registry",
+ { snapshot: { registry: "registry", revision: 0 } },
)
await act(async () => hook.current.userSettingsProps.onSave({
@@ -463,9 +464,9 @@ describe("useShellProfileController", () => {
statusEmoji: "🚀",
statusText: "Shipping",
}))
- expect(mocks.commitProfiles).toHaveBeenCalledTimes(2)
+ expect(mocks.writeCommunityProfilePatches).toHaveBeenCalledTimes(2)
await act(async () => hook.current.userSettingsProps.onSave({ aboutMe: "About only" }))
- expect(mocks.commitProfiles).toHaveBeenCalledTimes(3)
+ expect(mocks.writeCommunityProfilePatches).toHaveBeenCalledTimes(3)
const statusError = new Error("status")
mocks.updateProfile.mockRejectedValueOnce(statusError)
@@ -581,8 +582,7 @@ describe("useShellProfileController", () => {
const uploadOptions = mocks.uploadAvatar.mock.calls[0]![1]
await act(async () => uploadOptions.onSuccess({ url: "/avatar.png?v=4", avatarVersion: 4 }))
- expect(mocks.patchProfiles).toHaveBeenCalledWith(
- { viewerId: "self", accountEpoch: 1, revision: 0 },
+ expect(mocks.writeCommunityProfilePatches).toHaveBeenCalledWith(
[{
id: "self",
avatar: { avatar: "/avatar.png?v=4", avatarVersion: 4 },
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index 0ca571b14..ebe19a56e 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -27,6 +27,11 @@ import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"
import { useCommunityStore } from "@/stores/community"
import { useCommunityWsStore } from "@/stores/community/ws"
import { useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ beginCommunityProfileSeed,
+ writeCommunityProfilePatches,
+ type CommunityProfileSeedSnapshot,
+} from "@/lib/community/profile-seed"
import { useCurrentUser } from "@/contexts/community/current-user"
import { useFriends } from "@/hooks/community/use-friends"
import { useServerMembers } from "@/hooks/community/use-server-members"
@@ -40,7 +45,6 @@ import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"
import type { UserSettings } from "@/components/community/settings/user-settings"
import type { ImageCropDialog } from "@/components/community/image-crop-dialog"
import type { QueryClient } from "@tanstack/react-query"
-import type { CommunityProfileSnapshot } from "@/lib/community/models/people"
import type { ShellFrameProps, ShellRouter } from "./shell-frame-types"
export type ShellProfileState = {
@@ -56,11 +60,10 @@ type Options = Pick<ShellFrameProps, "view" | "activeServerId"> & {
}
function commitCanonicalSelfProfile(
- snapshot: CommunityProfileSnapshot,
+ snapshot: CommunityProfileSeedSnapshot,
profile: UpdateProfileResult,
) {
- const profiles = useCommunityWsStore.getState()
- profiles.commitProfiles(snapshot, [{
+ writeCommunityProfilePatches([{
id: profile.id,
identityAbout: {
name: profile.name,
@@ -76,7 +79,7 @@ function commitCanonicalSelfProfile(
statusEmoji: profile.statusEmoji,
statusText: profile.statusText,
},
- }])
+ }], snapshot.registry, { snapshot })
}
export function useShellProfileController({
@@ -224,7 +227,7 @@ export function useShellProfileController({
const updateOwnStatus = async (statusEmoji: string | null, statusText: string | null) => {
try {
- const snapshot = useCommunityWsStore.getState().beginProfileSnapshot()
+ const snapshot = beginCommunityProfileSeed()
const profile = await updateProfile.mutateAsync({ statusEmoji, statusText })
commitCanonicalSelfProfile(snapshot, profile)
} catch (error) {
@@ -285,7 +288,7 @@ export function useShellProfileController({
const onSaveProfile: ComponentProps<typeof UserSettings>["onSave"] = async (data) => {
try {
- const snapshot = useCommunityWsStore.getState().beginProfileSnapshot()
+ const snapshot = beginCommunityProfileSeed()
const profile = await updateProfile.mutateAsync(data)
commitCanonicalSelfProfile(snapshot, profile)
} catch (error) {
@@ -349,8 +352,7 @@ export function useShellProfileController({
{ file },
{
onSuccess: (data) => {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
+ writeCommunityProfilePatches([{
id: currentUser.id,
avatar: { avatar: data.url, avatarVersion: data.avatarVersion },
}])
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 6dd883099..01440cd70 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
@@ -13,8 +13,12 @@ const mocks = vi.hoisted(() => ({
markSwitch: vi.fn(),
toast: vi.fn(),
toastApiError: vi.fn(),
+ lastChannel: { current: null as string | null },
lastMeLeaf: { current: null as string | null },
- structuralSnapshot: null as null | Record<string, unknown>,
+ communityDb: { current: null as null | { collections: {
+ servers: { get: (id: string) => { detailComplete?: boolean } | undefined }
+ channels: { values: () => IterableIterator<Record<string, unknown>> }
+ } } },
}))
vi.mock("sonner", () => ({ toast: mocks.toast }))
@@ -31,8 +35,8 @@ vi.mock("@/hooks/community/use-servers", () => ({
}),
}))
vi.mock("@/hooks/community/use-folders", () => ({ useFolders: () => ({ folders: mocks.folders }) }))
-vi.mock("@/hooks/community/use-structural-snapshot", () => ({
- useStructuralSnapshot: () => mocks.structuralSnapshot,
+vi.mock("@/lib/community-db/projections", () => ({
+ useOptionalCommunityDbRegistry: () => mocks.communityDb.current,
}))
vi.mock("@/hooks/community/mutations", () => ({
useCreateServer: () => ({ mutateAsync: mocks.createServer }),
@@ -44,7 +48,7 @@ vi.mock("@/stores/community", () => ({
selector({ currentServerId: "s1" }),
}))
vi.mock("@/lib/community/last-channel", () => ({
- getLastChannel: () => null,
+ getLastChannel: () => mocks.lastChannel.current,
pickServerLandingHref: (id: string, channelIds: string[]) =>
channelIds[0] ? `/c/channels/${id}/${channelIds[0]}` : `/c/channels/${id}`,
}))
@@ -131,8 +135,9 @@ describe("useShellRailController", () => {
if (typeof mock === "function" && "mockReset" in mock) mock.mockReset()
}
mocks.folders.length = 0
+ mocks.lastChannel.current = null
mocks.lastMeLeaf.current = null
- mocks.structuralSnapshot = null
+ mocks.communityDb.current = null
})
it("commits cold server navigation synchronously without waiting for detail", async () => {
@@ -149,35 +154,6 @@ describe("useShellRailController", () => {
})
- it("renders a structural rail hint while keeping privileged actions disabled", async () => {
- mocks.structuralSnapshot = {
- schemaVersion: 1,
- accountId: "viewer-1",
- capturedAt: Date.now(),
- serverOrder: ["s3"],
- folders: [{ id: "f1", name: "Saved", serverIds: ["s3"] }],
- servers: [{
- id: "s3",
- name: "Hint",
- discriminator: "0003",
- icon: null,
- categories: [],
- channels: [{ id: "c3", name: "cached", type: "text", categoryId: null }],
- childRouteHints: [],
- }],
- }
- const hook = await renderController({ accountId: "viewer-1" })
-
- expect(hook.current.railProps.servers.map((server) => server.id)).toEqual(["s3"])
- expect(hook.current.railProps.folders.map((folder) => folder.id)).toEqual(["f1"])
- expect(hook.current.railProps.onLeaveServer).toBeUndefined()
- expect(hook.current.railProps.onOpenSettings).toBeUndefined()
- expect(hook.current.railProps.onOpenInvitePopover).toBeUndefined()
-
- await act(async () => hook.current.navigate("s3"))
- expect(hook.pushed).toEqual(["/c/channels/s3/c3"])
- })
-
it("projects the pending target for every rail entry without changing committed actions", async () => {
const openSettings = vi.fn()
const hook = await renderController({
@@ -270,16 +246,50 @@ describe("useShellRailController", () => {
hook.cache.set("s1", {
categories: [{ channels: [{ id: "cached", pending: false }] }],
})
+ mocks.lastChannel.current = "cached"
await act(async () => hook.current.railProps.onServerNavigate("s1"))
expect(hook.pushed).toEqual(["/c/channels/s1"])
})
+ it("uses canonical channels only when the restored server detail is complete", async () => {
+ const servers = new Map([
+ ["s1", { id: "s1", detailComplete: true }],
+ ["s2", { id: "s2", detailComplete: false }],
+ ])
+ const channels = new Map([
+ ["pending", { id: "pending", serverId: "s1", type: "text", pending: true }],
+ ["thread", { id: "thread", serverId: "s1", type: "thread", pending: false }],
+ ["canonical", { id: "canonical", serverId: "s1", type: "text", pending: false }],
+ ["foreign", { id: "foreign", serverId: "s2", type: "text", pending: false }],
+ ])
+ mocks.communityDb.current = { collections: {
+ servers: { get: (id) => servers.get(id) },
+ channels: { values: () => channels.values() },
+ } }
+ const hook = await renderController()
+
+ await act(async () => hook.current.navigate("s1"))
+ await act(async () => hook.current.railProps.onServerPrefetch("s1"))
+ await act(async () => hook.current.navigate("s2"))
+ await act(async () => hook.current.railProps.onServerPrefetch("s2"))
+
+ expect(hook.pushed).toEqual([
+ "/c/channels/s1/canonical",
+ "/c/channels/s2",
+ ])
+ expect(hook.prefetched).toEqual([
+ "/c/channels/s1",
+ "/c/channels/s2",
+ ])
+ })
+
it("keeps rail navigation and prefetch on the semantic server root", async () => {
const hook = await renderController()
hook.cache.set("s1", {
categories: [{ channels: [{ id: "pending", pending: true }, { id: "cached", pending: false }] }],
})
+ mocks.lastChannel.current = "cached"
await act(async () => hook.current.railProps.onServerNavigate("s1"))
await act(async () => hook.current.railProps.onServerPrefetch("s1"))
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.ts b/src/web/src/components/community/shell/use-shell-rail-controller.ts
index cf1a0caab..339d67ad3 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.ts
@@ -22,11 +22,7 @@ import type { ShellFrameProps } from "./shell-frame-types"
import type { View } from "./shell-types"
import type { CommunityNavigationController } from "./use-community-navigation-controller"
import type { QueryClient } from "@tanstack/react-query"
-import { useStructuralSnapshot } from "@/hooks/community/use-structural-snapshot"
-import {
- structuralSnapshotFolders,
- structuralSnapshotServers,
-} from "@/lib/community/structural-snapshot"
+import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
type Options = Pick<
ShellFrameProps,
@@ -55,17 +51,12 @@ export function useShellRailController({
onOpenActiveServerInvite,
accountId,
}: Options) {
- const structuralSnapshot = useStructuralSnapshot(accountId ?? null, queryClient)
+ const communityDb = useOptionalCommunityDbRegistry()
const serversQuery = useServers()
const foldersQuery = useFolders()
- const hasLiveServers = serversQuery.data !== undefined || !accountId
- const servers = hasLiveServers
- ? serversQuery.servers
- : structuralSnapshotServers(structuralSnapshot)
- const folders = foldersQuery.data?.folders
- ?? (accountId
- ? structuralSnapshotFolders(structuralSnapshot)
- : foldersQuery.folders)
+ const servers = serversQuery.servers
+ const folders = foldersQuery.folders
+ const hasLiveServers = servers.length > 0 || serversQuery.data !== undefined || !accountId
const currentServerId = useCommunityStore((state) => state.currentServerId)
const { mutateAsync: createServerAsync } = useCreateServer()
const { mutate: leaveServerMutate } = useLeaveServer()
@@ -81,12 +72,16 @@ export function useShellRailController({
const liveChannelIds = detail?.categories.flatMap((category) =>
category.channels.filter((channel) => !channel.pending).map((channel) => channel.id)
)
+ const canonicalDetailComplete = communityDb?.collections.servers.get(id)?.detailComplete === true
const channelIds = liveChannelIds
- ?? structuralSnapshot?.servers.find((server) => server.id === id)
- ?.channels.map((channel) => channel.id)
+ ?? (communityDb && canonicalDetailComplete
+ ? Array.from(communityDb.collections.channels.values())
+ .filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending)
+ .map((channel) => channel.id)
+ : undefined)
?? []
return pickServerLandingHref(id, channelIds, getLastChannel(id))
- }, [queryClient, structuralSnapshot])
+ }, [communityDb, queryClient])
const onServerNavigate = useCallback((id: string) => {
markSwitch("server", id)
navigation.push(`/c/channels/${id}`)
@@ -174,7 +169,7 @@ export function useShellRailController({
servers: railServers,
folders,
activeServerId: projectedActiveServerId,
- serversLoading: serversQuery.isPending && !structuralSnapshot,
+ serversLoading: serversQuery.isPending && servers.length === 0,
view: projectedView,
onHome,
onHomePrefetch,
diff --git a/src/web/src/components/community/social/bot-approval-card.test.ts b/src/web/src/components/community/social/bot-approval-card.test.ts
index d66474d45..60c3457c1 100644
--- a/src/web/src/components/community/social/bot-approval-card.test.ts
+++ b/src/web/src/components/community/social/bot-approval-card.test.ts
@@ -8,8 +8,8 @@ import { BotApprovalCard } from "./bot-approval-card"
import { avatarInitial } from "@/lib/community/avatar"
const profileState = vi.hoisted(() => ({ map: new Map<string, Record<string, unknown>>() }))
-vi.mock("@/stores/community/ws", () => ({
- useCommunityProfile: (id?: string) => id ? profileState.map.get(id) : undefined,
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalCommunityProfile: (id?: string) => id ? profileState.map.get(id) : undefined,
}))
const OTHER = { id: "u_alice", name: "Alice", discriminator: "0042", image: null, avatarVersion: 0 }
diff --git a/src/web/src/components/community/social/bot-approval-card.tsx b/src/web/src/components/community/social/bot-approval-card.tsx
index b453b5e3c..924ca2f77 100644
--- a/src/web/src/components/community/social/bot-approval-card.tsx
+++ b/src/web/src/components/community/social/bot-approval-card.tsx
@@ -5,29 +5,28 @@ import type { FriendApprovalPayload } from "@alook/shared"
import { useOwnerDecision } from "@/hooks/community/mutations/friends"
import { Button } from "@/components/ui/button"
import { ProfileAvatar } from "@/components/avatar"
-import { useCommunityProfile } from "@/stores/community/ws"
+import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
/**
* Inline friend-approval card, rendered in a bot owner's DM with their bot when
* a message carries an `approval` payload. States are driven by the per-viewer
- * projection (`status` × `waitingOn`) — see
- * plans/agent-friendship-approval-gate.md §UI. Only the actionable state
+ * projection (`status` × `waitingOn`). Only the actionable state
* (`pending, waitingOn='you'`) shows Approve/Deny; everything else is a chip.
*/
export function BotApprovalCard({ approval }: { approval: FriendApprovalPayload }) {
const decide = useOwnerDecision()
const { status, waitingOn, otherProfile, botProfile, waitingOnProfile } = approval
const other = readCommunityProfile(
- useCommunityProfile(otherProfile.id),
+ useCanonicalCommunityProfile(otherProfile.id),
otherProfile.id,
)
const bot = readCommunityProfile(
- useCommunityProfile(botProfile.id),
+ useCanonicalCommunityProfile(botProfile.id),
botProfile.id,
)
const waiting = readCommunityProfile(
- useCommunityProfile(waitingOnProfile?.id),
+ useCanonicalCommunityProfile(waitingOnProfile?.id),
waitingOnProfile?.id ?? "",
)
const otherHandle = `${other.name}#${other.discriminator}`
diff --git a/src/web/src/components/community/social/bot-mark-sticker.tsx b/src/web/src/components/community/social/bot-mark-sticker.tsx
index 9d3a872b8..f51c9bd46 100644
--- a/src/web/src/components/community/social/bot-mark-sticker.tsx
+++ b/src/web/src/components/community/social/bot-mark-sticker.tsx
@@ -226,7 +226,7 @@ export function BotMarkSticker({
<div className="w-fit min-w-0 max-w-full">
<div className="flex w-fit min-w-0 max-w-full items-center gap-2 text-xs leading-4">
<span className="min-w-0 truncate font-semibold">
- {mark.m.authorName || "Unknown"}
+ {mark.m.authorName || "Deleted user"}
</span>
{mark.m.createdAt && (
<time dateTime={mark.m.createdAt} className="shrink-0 whitespace-nowrap font-mono text-[9px] tabular-nums text-[#4b3712]">
diff --git a/src/web/src/components/community/social/friends-page.tsx b/src/web/src/components/community/social/friends-page.tsx
index cb594573b..692e94657 100644
--- a/src/web/src/components/community/social/friends-page.tsx
+++ b/src/web/src/components/community/social/friends-page.tsx
@@ -17,7 +17,7 @@ import { hasStatus } from "./status-presets"
import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { isSelfBotFriendship, isPresenceOffline, MIN_SEARCH_LENGTH } from "@alook/shared"
-import { useCommunityWsStore } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import { actionableIncomingRequests, compactRequestCount } from "@/lib/community/friend-requests"
import { useFriendRequestActionState } from "@/hooks/community/use-friend-request-action-state"
@@ -74,7 +74,7 @@ export function FriendsPage({
const [addValue, setAddValue] = useState("")
const [searchResults, setSearchResults] = useState<string[]>([])
- const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)
+ const profilesByUserId = useCanonicalProfilesByUserId()
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)
// Relationship state by user id, so search results can show Friends/Pending/
diff --git a/src/web/src/components/community/social/invite-dialog.test.ts b/src/web/src/components/community/social/invite-dialog.test.ts
index c94fa7bc0..ecbdc4161 100644
--- a/src/web/src/components/community/social/invite-dialog.test.ts
+++ b/src/web/src/components/community/social/invite-dialog.test.ts
@@ -21,8 +21,8 @@ const mocks = vi.hoisted(() => ({
}))
vi.mock("sonner", () => ({ toast: mocks.toastSpy }))
-vi.mock("@/stores/community/ws", () => ({
- useCommunityWsStore: (selector: (state: { profilesByUserId: Map<string, unknown> }) => unknown) => {
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalProfilesByUserId: () => {
const profilesByUserId = new Map(mocks.friendsQuery.friends.flatMap((friend) =>
friend.userId ? [[friend.userId, {
id: friend.userId,
@@ -35,7 +35,7 @@ vi.mock("@/stores/community/ws", () => ({
? "online"
: "offline",
}]] : []))
- return selector({ profilesByUserId })
+ return profilesByUserId
},
}))
vi.mock("@/hooks/community/use-friends", () => ({
diff --git a/src/web/src/components/community/social/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsx
index 8d46deef2..6d9a4d544 100644
--- a/src/web/src/components/community/social/invite-dialog.tsx
+++ b/src/web/src/components/community/social/invite-dialog.tsx
@@ -27,7 +27,7 @@ import {
} from "@/hooks/community/use-dm-message-sender"
import { useCurrentUser } from "@/contexts/community/current-user"
import type { Friend } from "@/lib/community/models/people"
-import { useCommunityWsStore } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
trackHumanInvitationCopied,
@@ -161,7 +161,7 @@ export function InviteDialog({
}) {
const currentUser = useCurrentUser()
useFriendsPresence(open)
- const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)
+ const profilesByUserId = useCanonicalProfilesByUserId()
// Only friends who are NOT already members of `serverId` — server-side
// filter so a stale local members cache can't leak already-joined rows.
const friendsQuery = useInvitableFriends(serverId, open)
@@ -216,7 +216,10 @@ export function InviteDialog({
return friends
.map((friend) => {
const userId = friend.userId ?? friend.id
- const profile = readCommunityProfile(profilesByUserId.get(userId), userId)
+ const canonical = profilesByUserId.get(userId)
+ const profile = canonical
+ ? readCommunityProfile(canonical, userId)
+ : { ...friend, presence: friend.status }
return {
...friend,
name: profile.name,
diff --git a/src/web/src/components/community/social/profile-card.dom.test.ts b/src/web/src/components/community/social/profile-card.dom.test.ts
index b4f9b9e83..fe4380221 100644
--- a/src/web/src/components/community/social/profile-card.dom.test.ts
+++ b/src/web/src/components/community/social/profile-card.dom.test.ts
@@ -23,9 +23,8 @@ const mocks = vi.hoisted(() => ({
interruptAgent: vi.fn(),
}))
-vi.mock("@/stores/community/ws", async (importOriginal) => ({
- ...await importOriginal<typeof import("@/stores/community/ws")>(),
- useCommunityProfile: () => mocks.profile,
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalCommunityProfile: () => mocks.profile,
}))
vi.mock("@/hooks/community/use-community-ws", () => ({
diff --git a/src/web/src/components/community/social/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsx
index e8b0c28bf..2faa61a35 100644
--- a/src/web/src/components/community/social/profile-card.tsx
+++ b/src/web/src/components/community/social/profile-card.tsx
@@ -15,7 +15,7 @@ import type {
Profile,
} from "@/components/community/social/profile-types"
import type { Breakpoint } from "@/hooks/use-mobile"
-import { useCommunityProfile } from "@/stores/community/ws"
+import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"
import { avatarInitial } from "@/lib/community/avatar"
import { tid } from "@/lib/community/testids"
import { communityWsInterruptAgent } from "@/hooks/community/use-community-ws"
@@ -239,7 +239,7 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
const [open, setOpen] = useState(true)
const [interruptPending, setInterruptPending] = useState(false)
const mobile = bp === "mobile"
- const globalProfile = useCommunityProfile(data.userId)
+ const globalProfile = useCanonicalCommunityProfile(data.userId)
const liveStatus = data.userId
? {
statusEmoji: globalProfile?.statusEmoji,
@@ -259,7 +259,9 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
const timer = globalThis.setTimeout(() => setInterruptPending(false), 10_000)
return () => globalThis.clearTimeout(timer)
}, [activityIdle, interruptPending])
- const name = data.userId ? (globalProfile?.name ?? "Unknown") : (data.name ?? "Unknown")
+ const name = data.userId
+ ? (globalProfile?.name ?? data.name ?? "Deleted user")
+ : (data.name ?? "Deleted user")
const avatar = data.userId
? (globalProfile?.avatar ?? avatarInitial(name))
: (data.avatar ?? avatarInitial(name))
diff --git a/src/web/src/components/community/social/status-presets.ts b/src/web/src/components/community/social/status-presets.ts
index cd672bdf7..d087446f7 100644
--- a/src/web/src/components/community/social/status-presets.ts
+++ b/src/web/src/components/community/social/status-presets.ts
@@ -2,7 +2,7 @@
* Preset status terms (emoji + short term) offered by `StatusEditor`, plus
* the shared "is a status set" predicate every display surface uses.
*
- * Tone is deliberately casual/fun, not work-mode — see plans/profile-card.md.
+ * Tone is deliberately casual and fun, not work-mode.
*/
export type StatusPreset = { emoji: string; text: string }
diff --git a/src/web/src/components/home/landing-content.test.ts b/src/web/src/components/home/landing-content.test.ts
index be173a663..8cb5f7254 100644
--- a/src/web/src/components/home/landing-content.test.ts
+++ b/src/web/src/components/home/landing-content.test.ts
@@ -190,6 +190,7 @@ describe("landing content contract", () => {
const authLayout = readFileSync(path.join(root, "src/app/(auth)/layout.tsx"), "utf8")
const signInClient = readFileSync(path.join(root, "src/app/(auth)/sign-in/sign-in-client.tsx"), "utf8")
const communityLayout = readFileSync(path.join(root, "src/app/c/layout.tsx"), "utf8")
+ const communityLayoutClient = readFileSync(path.join(root, "src/app/c/community-layout-client.tsx"), "utf8")
const ogRoute = readFileSync(path.join(root, "src/app/og/route.tsx"), "utf8")
const ogRenderer = readFileSync(path.join(root, "src/app/_og/render-og-image.tsx"), "utf8")
const publicLayout = readFileSync(path.join(root, "src/components/public-layout.tsx"), "utf8")
@@ -259,7 +260,8 @@ describe("landing content contract", () => {
expect(signInClient).toContain('label: "Bring your own agents"')
expect(signInClient).toContain('description: "Use your own computer and existing agent subscriptions."')
expect(signInClient).not.toContain("Bring your own workspaces")
- expect(communityLayout).toContain('<SignupTracker redirectTo="/c/me/machines" />')
+ expect(communityLayout).toContain("await getSession()")
+ expect(communityLayoutClient).toContain('<SignupTracker redirectTo="/c/me/machines" />')
expect(ogRoute).toContain("renderOgImage(BRAND_SLOGAN)")
expect(ogRoute).not.toContain("searchParams")
expect(ogRenderer).toContain('await getCloudflareContext({ async: true })')
diff --git a/src/web/src/components/perf/perf-trace-bootstrap.tsx b/src/web/src/components/perf/perf-trace-bootstrap.tsx
index 93cd28333..45609f03e 100644
--- a/src/web/src/components/perf/perf-trace-bootstrap.tsx
+++ b/src/web/src/components/perf/perf-trace-bootstrap.tsx
@@ -15,7 +15,7 @@ import { installReactScan } from "@/lib/perf/react-scan-install"
* lifetime is the whole tab/page session, and a React effect cleanup (which
* StrictMode double-invokes in dev) must never detach react-scan's commit hook
* — doing so was silently killing all post-mount capture (~300ms in), which is
- * exactly the switch data we need. See plans/community-switch-perf-diagnosis.md.
+ * exactly the switch data we need.
*
* Renders nothing and does nothing when the perf gate is off, so it is inert in
* every real build.
diff --git a/src/web/src/components/runtime-version-gate.tsx b/src/web/src/components/runtime-version-gate.tsx
index d5a7a8d93..cd5eaf008 100644
--- a/src/web/src/components/runtime-version-gate.tsx
+++ b/src/web/src/components/runtime-version-gate.tsx
@@ -117,7 +117,7 @@ export function RuntimeVersionGate() {
{rt.device_info || daemonId.slice(0, 12)}
</div>
<div className="text-xs text-muted-foreground flex items-center gap-2 mt-1">
- <span>v{cliVersion || "unknown"}</span>
+ <span>{cliVersion ? `v${cliVersion}` : "Version unavailable"}</span>
<Badge variant="outline" className="text-[10px] px-2 py-0 text-amber-500 border-amber-500/30">
requires v{minVersion}
</Badge>
diff --git a/src/web/src/contexts/community/current-user.tsx b/src/web/src/contexts/community/current-user.tsx
index 331c5329c..c5cf6909a 100644
--- a/src/web/src/contexts/community/current-user.tsx
+++ b/src/web/src/contexts/community/current-user.tsx
@@ -7,11 +7,13 @@ import {
useMemo,
type ReactNode,
} from "react"
+import { useIsRestoring } from "@tanstack/react-query"
import type { Presence } from "@/lib/community/models/people"
import {
- useCommunityProfile,
- useCommunityWsStore,
-} from "@/stores/community/ws"
+ useCanonicalCommunityProfile,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
+import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
/**
* Thin context that carries the viewer's identity down the community tree.
@@ -53,11 +55,13 @@ export function CurrentUserProvider({
initialUser: CurrentUser
children: ReactNode
}) {
- const current = useCommunityProfile(initialUser.id)
+ const isRestoring = useIsRestoring()
+ const communityDb = useOptionalCommunityDbRegistry()
+ const current = useCanonicalCommunityProfile(initialUser.id)
useLayoutEffect(() => {
+ if (isRestoring) return
if (current?.name !== undefined && current.avatarVersion !== undefined) return
- const profiles = useCommunityWsStore.getState()
- profiles.seedProfiles(profiles.beginProfileSnapshot(), [{
+ writeCommunityProfilePatches([{
id: initialUser.id,
...(current?.name === undefined
? { identityAbout: { name: initialUser.name } }
@@ -68,8 +72,8 @@ export function CurrentUserProvider({
avatarVersion: initialUser.avatarVersion ?? 0,
} }
: {}),
- }])
- }, [current?.avatarVersion, current?.name, initialUser])
+ }], communityDb)
+ }, [communityDb, current?.avatarVersion, current?.name, initialUser, isRestoring])
return (
<CurrentUserContext.Provider value={initialUser}>
{children}
@@ -79,7 +83,7 @@ export function CurrentUserProvider({
export function useCurrentUser(): CurrentUser {
const ctx = useContext(CurrentUserContext)
- const profile = useCommunityProfile(ctx?.id)
+ const profile = useCanonicalCommunityProfile(ctx?.id)
if (!ctx)
throw new Error("useCurrentUser must be used within CurrentUserProvider")
return useMemo(() => ({
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index 9f8d0bdbf..b9fd4dce3 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -28,6 +28,7 @@ interface RuntimeEnv {
declare namespace Cloudflare {
interface Env extends RuntimeEnv {
+ CF_VERSION_METADATA: WorkerVersionMetadata
DB: D1Database
EMAIL_BUCKET: R2Bucket
COMMUNITY_MEDIA: R2Bucket
diff --git a/src/web/src/hooks/community/account-unread-projection.test.ts b/src/web/src/hooks/community/account-unread-projection.test.ts
index 7a2703b06..8ab6a761b 100644
--- a/src/web/src/hooks/community/account-unread-projection.test.ts
+++ b/src/web/src/hooks/community/account-unread-projection.test.ts
@@ -12,6 +12,16 @@ import {
} from "./account-unread-projection"
describe("AccountUnreadProjection", () => {
+ it("treats unknown access as allowed and only denies explicit retirement", () => {
+ const projection = new AccountUnreadProjection("u1")
+
+ expect(projection.allowsAccess({ channelId: "unknown", serverId: "server" })).toBe(true)
+ projection.retireAccessScope({ kind: "server", serverId: "server" })
+ expect(projection.allowsAccess({ channelId: "unknown", serverId: "server" })).toBe(false)
+ projection.dispose()
+ expect(projection.allowsAccess({ channelId: "other" })).toBe(false)
+ })
+
it("enumerates distinct pending conversations using the same read fences as the badge", () => {
const projection = new AccountUnreadProjection("u1")
projection.recordArrival({ channelId: "dm", seq: 1 })
diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.ts
index ff567ac92..0d8c3c9a0 100644
--- a/src/web/src/hooks/community/account-unread-projection.ts
+++ b/src/web/src/hooks/community/account-unread-projection.ts
@@ -310,6 +310,12 @@ export class AccountUnreadProjection {
getSnapshot = () => this.version
+ allowsAccess(source: { channelId?: string; serverId?: string | null }) {
+ if (this.disposed) return false
+ if (source.channelId && this.accessFences.has(`channel:${source.channelId}`)) return false
+ return !source.serverId || !this.accessFences.has(`server:${source.serverId}`)
+ }
+
setReconcileScheduler(reconcile: (() => void) | null) {
if (this.disposed) return
this.reconcile = reconcile
diff --git a/src/web/src/hooks/community/channel-metadata.test.ts b/src/web/src/hooks/community/channel-metadata.test.ts
index a7f282d81..e786a15eb 100644
--- a/src/web/src/hooks/community/channel-metadata.test.ts
+++ b/src/web/src/hooks/community/channel-metadata.test.ts
@@ -20,7 +20,7 @@ beforeEach(() => {
})
describe("canonical channel metadata lifecycle", () => {
- it.each(["account", "parent", "server", "reconnect", "membership"] as const)(
+ it.each(["account", "parent", "server", "membership"] as const)(
"rejects an old successful HTTP response after %s changes",
async (change) => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
@@ -38,8 +38,7 @@ describe("canonical channel metadata lifecycle", () => {
useCommunityWsStore.getState().activateProfileAccount("alice")
} else if (change === "parent") state.revokeChannelAccess("server", "parent")
else if (change === "server") state.revokeServerAccess("server")
- else if (change === "membership") state.beginChannelMembershipChange("server", "child")
- else { state.markAccessDisconnected(); state.markAccessConnected() }
+ else state.beginChannelMembershipChange("server", "child")
release(metadata)
await rejection
expect(client.getQueryData(key)).toBeUndefined()
@@ -48,6 +47,18 @@ describe("canonical channel metadata lifecycle", () => {
},
)
+ it("accepts an authoritative HTTP response across a transport-only reconnect", async () => {
+ let release!: (value: unknown) => void
+ fetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
+ const result = fetchChannelMetadata("server", "child")
+ const state = useCommunityWsStore.getState()
+ state.markAccessConnected()
+ state.markAccessDisconnected()
+ state.markAccessConnected()
+ release(metadata)
+ await expect(result).resolves.toMatchObject({ id: "child", verifiedEpoch: state.accessEpoch })
+ })
+
it("restores readable child and parent only from a current authoritative response", async () => {
const state = useCommunityWsStore.getState()
state.revokeChannelAccess("server", "parent")
diff --git a/src/web/src/hooks/community/community-ws/bundle-events.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.test.ts
index fb9932dc5..71d6f009b 100644
--- a/src/web/src/hooks/community/community-ws/bundle-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/bundle-events.test.ts
@@ -20,12 +20,17 @@ vi.mock("./reconnect", () => ({ reconcileCommunityWsReconnect }))
import {
capturedOnMessage,
capturedQueryClient,
+ canonicalForumSidebar,
cleanupCommunityWsHarness,
forumSidebarFixture,
getCommunityApiFetchMock,
+ hasCanonicalChannelAccess,
+ hasCanonicalChannelNotify,
mountHook,
resetCommunityWsHarness,
+ seedCanonicalForumSidebar,
} from "./test-harness"
+import { getCanonicalCommunityChannels, getCanonicalCommunityMessages } from "@/lib/community-db/sync"
import { useCommunityStore } from "@/stores/community"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import {
@@ -101,22 +106,7 @@ describe("useCommunityWs — operation bundles", () => {
it("applies archive and null-tag sidebar semantics inside committed batches", async () => {
await mountHook()
const baseKey = communityKeys.forumSidebarThreads("s1")
- const metaKey = communityKeys.channelMeta("s1", "post_1")
- const hintKey = communityKeys.forumOpenerHint("s1", "opener-post_1")
- capturedQueryClient.setQueryData(communityKeys.server("s1"), {
- id: "s1",
- categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],
- })
- capturedQueryClient.setQueryData(baseKey, forumSidebarFixture(["post_1", "post_2"]))
- capturedQueryClient.setQueryData(metaKey, {
- id: "post_1",
- parentChannelId: "forum_1",
- parentMessageId: "opener-post_1",
- })
- capturedQueryClient.setQueryData(hintKey, {
- id: "opener-post_1",
- content: "Post one",
- })
+ seedCanonicalForumSidebar("s1", ["post_1", "post_2"])
capturedOnMessage!(await batchFor("forum-archive", [{
type: "community:channel.child_update",
@@ -125,18 +115,13 @@ describe("useCommunityWs — operation bundles", () => {
changes: { tags: ["archived"] },
}]))
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)
- ?.threads.map(({ id }) => id)).toEqual(["post_2"])
- expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })
- expect(capturedQueryClient.getQueryData(hintKey)).toEqual({
- id: "opener-post_1",
- content: "Post one",
- })
- await vi.waitFor(() => {
- expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)
- })
-
- capturedQueryClient.setQueryData(baseKey, forumSidebarFixture(["post_2"]))
+ expect(canonicalForumSidebar("s1").threads.map(({ id }) => id)).toEqual(["post_2"])
+ expect(getCanonicalCommunityChannels(capturedQueryClient)
+ .find(({ id }) => id === "post_1")).toMatchObject({ archived: false })
+ expect(hasCanonicalChannelAccess("post_1", "u_me")).toBe(true)
+ expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(false)
+ expect(getCanonicalCommunityMessages(capturedQueryClient)
+ .find(({ id }) => id === "opener-post_1")).toMatchObject({ content: "title-post_1" })
capturedOnMessage!(await batchFor("forum-unarchive", [{
type: "community:channel.child_update",
parentChannelId: "forum_1",
@@ -144,13 +129,11 @@ describe("useCommunityWs — operation bundles", () => {
changes: { tags: null },
}]))
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)
- ?.threads.map(({ id }) => id)).toEqual(["post_2"])
- expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })
- expect(capturedQueryClient.getQueryData(hintKey)).toEqual({
- id: "opener-post_1",
- content: "Post one",
- })
+ expect(canonicalForumSidebar("s1").threads.map(({ id }) => id).sort())
+ .toEqual(["post_1", "post_2"])
+ expect(getCanonicalCommunityChannels(capturedQueryClient)
+ .find(({ id }) => id === "post_1")).toMatchObject({ archived: false })
+ expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(true)
})
it("merges multiple requests into one queued successor generation", async () => {
diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.test.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.test.ts
index 57c58e7fe..d6b85758b 100644
--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.test.ts
+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.test.ts
@@ -1,9 +1,19 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
import type { CommunityWsEvent } from "@alook/shared"
import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"
import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { ingestServerDetail, projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import {
+ applyForumPostUnitClientEffects,
+ projectChannelScopeEviction,
+} from "./channel-scope-projection"
import {
capturedOnMessage,
capturedQueryClient,
@@ -16,6 +26,41 @@ import {
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
+it("purges canonical rows for authoritative channel and forum-post eviction", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestServerDetail(registry, {
+ id: "server", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer",
+ categories: [{
+ id: "cat", name: "General",
+ channels: [
+ { id: "channel", name: "chat", active: false, unread: false },
+ { id: "forum", name: "forum", active: false, unread: false, type: "forum" },
+ ],
+ }],
+ })
+ projectCommunityWsEventToDb(queryClient, {
+ type: "community:channel.child_create", parentChannelId: "forum", parentMessageId: "opener",
+ channel: { id: "thread", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" },
+ } as CommunityWsEvent)
+ const projection = { project: (callback: () => void) => callback() } as never
+
+ projectChannelScopeEviction(projection, queryClient, "server", "channel")
+ expect(registry.collections.channels.get("channel")).toBeUndefined()
+
+ applyForumPostUnitClientEffects(queryClient, {
+ serverId: "server", forumChannelId: "forum", childChannelId: "thread",
+ openerMessageId: "opener",
+ })
+ expect(registry.collections.channels.get("thread")).toBeUndefined()
+
+ unregister()
+ await registry.cleanup()
+})
+
function seedThreads(serverId: string, parentId: string, children: string[], shape: "text" | "forum") {
if (shape === "text") {
const data: ThreadsResponse = {
diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
index e79b95be8..5dbc97fc8 100644
--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts
@@ -19,7 +19,8 @@ import {
} from "@/hooks/community/use-forum-sidebar-threads"
import type { CommunityWsProjectionTransaction } from "./projection-transaction"
import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
-import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { purgeCommunityChannel } from "@/lib/community-db/sync"
import { collectChannelScopeIds, evictScopeContent } from "./scope-eviction"
export function projectChannelScopeEviction(
@@ -38,11 +39,8 @@ export function projectChannelScopeEviction(
evictChannelScopeQueryCaches(queryClient, serverId, id)
evictScopeContent(queryClient, serverId, id)
}
- updateStructuralSnapshot(queryClient, {
- type: "removeChannel",
- serverId,
- channelId,
- })
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry) purgeCommunityChannel(registry, channelId)
})
}
@@ -107,10 +105,6 @@ export function evictForumPostUnitQueryCaches(
unit.openerMessageId,
),
)
- queryClient.removeQueries({
- queryKey: communityKeys.forumOpenerHint(unit.serverId, unit.openerMessageId),
- exact: true,
- })
queryClient.removeQueries({
queryKey: communityKeys.message(unit.openerMessageId),
exact: true,
@@ -158,11 +152,8 @@ export function applyForumPostUnitClientEffects(
type: "messageRemoved",
messageId: unit.openerMessageId,
})
- updateStructuralSnapshot(queryClient, {
- type: "removeChildHint",
- serverId: unit.serverId,
- channelId: unit.childChannelId,
- })
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry) purgeCommunityChannel(registry, unit.childChannelId)
const store = useCommunityStore.getState()
if (wasCurrent) {
store.setCurrentChannelMeta(null)
diff --git a/src/web/src/hooks/community/community-ws/identity-events.test.ts b/src/web/src/hooks/community/community-ws/identity-events.test.ts
index e98e23360..8dfb21451 100644
--- a/src/web/src/hooks/community/community-ws/identity-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/identity-events.test.ts
@@ -2,18 +2,25 @@ import { beforeEach, describe, expect, it } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
-import type { CommunityWsHandlerContext } from "./handler-context"
-import { handleIdentityUpdate, handleProfileUpdate } from "./identity-events"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import type { ProfileRow } from "@/lib/community-db/schema"
-function harness() {
+async function harness() {
const queryClient = new QueryClient()
- return {
- queryClient,
- context: {
- queryClient,
- wsStore: useCommunityWsStore.getState(),
- } as unknown as CommunityWsHandlerContext,
- }
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ registerCommunityDbRegistry(registry)
+ return { queryClient }
+}
+
+function profile(queryClient: QueryClient, userId: string) {
+ return queryClient.getQueryData<ProfileRow[]>(
+ communityKeys.communityDbCollection("viewer", "profiles"),
+ )?.find((row) => row.userId === userId)
}
beforeEach(() => {
@@ -22,8 +29,8 @@ beforeEach(() => {
})
describe("profile identity events", () => {
- it("updates only the canonical avatar and leaves raw query snapshots untouched", () => {
- const { queryClient, context } = harness()
+ it("updates only the canonical avatar and leaves raw query snapshots untouched", async () => {
+ const { queryClient } = await harness()
const cached = {
id: "m1",
authorId: "u1",
@@ -32,50 +39,50 @@ describe("profile identity events", () => {
}
queryClient.setQueryData(communityKeys.message("m1"), cached)
- handleIdentityUpdate({
+ projectCommunityWsEventToDb(queryClient, {
type: "community:identity.update",
userId: "u1",
avatar: "/avatar?v=4",
avatarVersion: 4,
- }, context)
+ })
expect(queryClient.getQueryData(communityKeys.message("m1"))).toBe(cached)
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
+ expect(profile(queryClient, "u1")).toMatchObject({
avatar: "/avatar?v=4",
avatarVersion: 4,
})
})
- it("retains the current avatar for stale and equal-version conflicting frames", () => {
- const { context } = harness()
- handleIdentityUpdate({
+ it("retains the current avatar for stale and equal-version conflicting frames", async () => {
+ const { queryClient } = await harness()
+ projectCommunityWsEventToDb(queryClient, {
type: "community:identity.update",
userId: "u1",
avatar: "/avatar?v=5",
avatarVersion: 5,
- }, context)
- handleIdentityUpdate({
+ })
+ projectCommunityWsEventToDb(queryClient, {
type: "community:identity.update",
userId: "u1",
avatar: "/stale?v=4",
avatarVersion: 4,
- }, context)
- handleIdentityUpdate({
+ })
+ projectCommunityWsEventToDb(queryClient, {
type: "community:identity.update",
userId: "u1",
avatar: "/conflict?v=5",
avatarVersion: 5,
- }, context)
+ })
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
+ expect(profile(queryClient, "u1")).toMatchObject({
avatar: "/avatar?v=5",
avatarVersion: 5,
})
})
- it("writes authoritative nullable profile fields to the canonical map", () => {
- const { context } = harness()
- handleProfileUpdate({
+ it("writes authoritative nullable profile fields to the canonical map", async () => {
+ const { queryClient } = await harness()
+ projectCommunityWsEventToDb(queryClient, {
type: "community:profile.update",
userId: "bot-1",
name: "Bot",
@@ -84,9 +91,9 @@ describe("profile identity events", () => {
bannerColor: null,
kind: "bot",
ownerUserId: "owner-1",
- }, context)
+ })
- expect(useCommunityWsStore.getState().profilesByUserId.get("bot-1")).toMatchObject({
+ expect(profile(queryClient, "bot-1")).toMatchObject({
name: "Bot",
discriminator: "0042",
aboutMe: "",
diff --git a/src/web/src/hooks/community/community-ws/identity-events.ts b/src/web/src/hooks/community/community-ws/identity-events.ts
index 9a11636fc..ab2a718f7 100644
--- a/src/web/src/hooks/community/community-ws/identity-events.ts
+++ b/src/web/src/hooks/community/community-ws/identity-events.ts
@@ -2,28 +2,13 @@ import type { CommunityIdentityUpdate, CommunityProfileUpdate } from "@alook/sha
import type { CommunityWsHandlerContext } from "@/hooks/community/community-ws/handler-context"
export function handleIdentityUpdate(
- event: CommunityIdentityUpdate,
- { wsStore }: CommunityWsHandlerContext,
+ _event: CommunityIdentityUpdate,
+ _context: CommunityWsHandlerContext,
) {
- wsStore.patchProfiles(wsStore.beginProfileSnapshot(), [{
- id: event.userId,
- avatar: { avatar: event.avatar, avatarVersion: event.avatarVersion },
- }])
}
export function handleProfileUpdate(
- event: CommunityProfileUpdate,
- { wsStore }: CommunityWsHandlerContext,
+ _event: CommunityProfileUpdate,
+ _context: CommunityWsHandlerContext,
) {
- wsStore.patchProfiles(wsStore.beginProfileSnapshot(), [{
- id: event.userId,
- identityAbout: {
- name: event.name,
- discriminator: event.discriminator,
- aboutMe: event.aboutMe,
- bannerColor: event.bannerColor,
- kind: event.kind,
- ownerUserId: event.ownerUserId,
- },
- }])
}
diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.ts
index c21c827a2..080bebf0a 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts
@@ -5,6 +5,10 @@ import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/mes
import type { PresenceResponse } from "@/hooks/community/use-server-panels"
import { communityKeys } from "@/lib/query-keys"
import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
+import {
+ getCanonicalCommunityChannels,
+ patchCanonicalCommunityChannel,
+} from "@/lib/community-db/sync"
import {
subscribeMemberOverlayEvents,
type MemberOverlayEvent,
@@ -12,11 +16,16 @@ import {
import {
capturedOnMessage,
capturedQueryClient,
+ hasCanonicalChannel,
+ hasCanonicalChannelAccess,
+ hasCanonicalChannelNotify,
cleanupCommunityWsHarness,
forumSidebarFixture,
getCommunityApiFetchMock,
mountHook,
resetCommunityWsHarness,
+ seedCanonicalForumSidebar,
+ seedCanonicalThread,
} from "./test-harness"
beforeEach(resetCommunityWsHarness)
@@ -172,12 +181,7 @@ describe("useCommunityWs — member events", () => {
sub: "",
})
const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(useCommunityWsStore.getState().profilesByUserId.get("u_1")).toMatchObject({
- name: "n",
- discriminator: "0000",
- avatar: "N",
- avatarVersion: 0,
- })
+ expect(useCommunityWsStore.getState()).not.toHaveProperty("profilesByUserId")
})
it("exact-refetches only the joined server's active presence seed", async () => {
@@ -483,27 +487,11 @@ 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")
capturedQueryClient.setQueryData(serverKey, {
id: "srv_1",
categories: [{ id: "cat_1", channels: [{ id: "ch_1", type: "text" }] }],
})
- capturedQueryClient.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "u_me",
- capturedAt: Date.now(),
- serverOrder: ["srv_1"],
- folders: [],
- servers: [{
- id: "srv_1",
- name: "Server",
- discriminator: "0001",
- icon: null,
- categories: [{ id: "cat_1", name: "Private" }],
- channels: [{ id: "ch_1", name: "secret", type: "text", categoryId: "cat_1" }],
- childRouteHints: [],
- }],
- })
-
capturedOnMessage!({
type: "community:channel.member_remove",
serverId: "srv_1",
@@ -511,19 +499,18 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
userId: "u_me",
})
- expect(capturedQueryClient.getQueryData<{
- categories: { channels: { id: string }[] }[]
- }>(serverKey)?.categories[0].channels).toEqual([])
- expect(capturedQueryClient.getQueryData<{
- servers: Array<{ channels: Array<{ id: string }> }>
- }>(communityKeys.structuralSnapshot())?.servers[0]?.channels).toEqual([])
+ expect(hasCanonicalChannel("ch_1")).toBe(false)
})
it("adds/removes the viewer's participating child in the forum sidebar", async () => {
await mountHook({ viewerUserId: "u_me" })
const { useCommunityStore } = await import("@/stores/community")
const key = communityKeys.forumSidebarThreads("srv_1")
- capturedQueryClient.setQueryData(key, forumSidebarFixture())
+ seedCanonicalForumSidebar("srv_1", ["post_1", "post_2"])
+ patchCanonicalCommunityChannel(capturedQueryClient, "post_1", (row) => ({
+ ...row,
+ unread: true,
+ }))
useCommunityStore.getState().setCurrentChannelId("post_1")
useCommunityStore.getState().setCurrentChannelMeta({
name: "Private forum title",
@@ -541,19 +528,19 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
channelId: "post_1",
userId: "u_me",
})
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+ expect(hasCanonicalChannelAccess("post_1", "u_me")).toBe(true)
+ expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(false)
+ expect(getCanonicalCommunityChannels(capturedQueryClient)
+ .find(({ id }) => id === "post_1")?.unread).toBe(false)
expect(useCommunityStore.getState().currentChannelMeta?.name).toBe("Private forum title")
- capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
capturedOnMessage!({
type: "community:channel.member_add",
serverId: "srv_1",
channelId: "post_2",
userId: "u_me",
})
- await vi.waitFor(() => {
- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
- })
+ expect(hasCanonicalChannelAccess("post_2", "u_me")).toBe(true)
})
it("does not touch forum resources for a known ordinary text child", async () => {
@@ -563,6 +550,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
const retainedKey = communityKeys.forumSidebarRetained("srv_1", "forum_post")
const metaKey = communityKeys.channelMeta("srv_1", "text_thread")
const hintKey = communityKeys.forumOpenerHint("srv_1", "forum_opener")
+ seedCanonicalThread("srv_1", "text_parent", "text", "text_thread")
capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
id: "srv_1",
categories: [{
@@ -656,7 +644,11 @@ describe("membership metadata and access lifetime", () => {
api.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
await vi.waitFor(() => expect(release).toBeTypeOf("function"))
- const meta = { id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", archived: false }
+ const meta = {
+ id: "child", serverId: "server", name: "Child", type: "thread",
+ parentChannelId: "parent", parentMessageId: "opener", creatorId: null,
+ archived: false, lastMessageAt: null,
+ }
api.mockResolvedValue(meta)
capturedOnMessage!({ type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" })
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.channelMeta("server", "child"))).toMatchObject({ type: "thread" }))
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 c1888388a..1b7e89ecd 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -28,6 +28,7 @@ import type { MembershipEventContext } from "@/hooks/community/community-ws/hand
import { projectChannelScopeEviction } from "./channel-scope-projection"
import { evictServerChannelScopes } from "./scope-eviction"
import { avatarInitial } from "@/lib/community/avatar"
+import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
import {
invalidateChannelRefDirectory,
invalidateInbox,
@@ -42,6 +43,11 @@ import {
removeServerReactionDetails,
} from "./reaction-details-invalidation"
import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityChannelMetadata,
+ setCanonicalCommunityChannelMembership,
+} from "@/lib/community-db/sync"
type ChannelMemberEvent = Extract<
CommunityWsEvent,
@@ -72,6 +78,14 @@ export function handleChannelMemberEvent(
kind: "channel", channelId: event.channelId,
})
removeForumSidebarProjectionExact(queryClient, event.serverId, event.channelId)
+ } else {
+ setCanonicalCommunityChannelMembership(
+ queryClient,
+ event.channelId,
+ "notify",
+ true,
+ { event: true },
+ )
}
void invalidateForumSidebarBaseExact(queryClient, event.serverId).catch(() => undefined)
invalidateInbox(activeProjection)
@@ -84,6 +98,13 @@ export function handleChannelMemberEvent(
})
projectChannelScopeEviction(activeProjection, queryClient, event.serverId, event.channelId)
} else {
+ setCanonicalCommunityChannelMembership(
+ queryClient,
+ event.channelId,
+ "access",
+ true,
+ { event: true },
+ )
useCommunityWsStore.getState().rememberChannelAccess(event.serverId, event.channelId)
getAccountUnreadProjection(queryClient, event.userId).grantAccessScope({
kind: "channel", channelId: event.channelId,
@@ -104,7 +125,15 @@ export function handleChannelMemberEvent(
try {
const meta = await queryClient.fetchQuery({
queryKey: key,
- queryFn: ({ signal }) => fetchChannelMetadata(event.serverId, event.channelId, signal),
+ queryFn: async ({ signal }) => {
+ const liveToken = captureCommunityLiveSnapshotToken(queryClient)
+ const metadata = await fetchChannelMetadata(event.serverId, event.channelId, signal)
+ publishCommunityChannelMetadata(queryClient, {
+ metadata,
+ proof: { token: liveToken, signal },
+ })
+ return metadata
+ },
staleTime: 0,
})
if (!isChannelMetadataTokenCurrent(token)) return
@@ -136,8 +165,8 @@ export function handleMemberJoin(
event: CommunityMemberJoin,
context: MembershipEventContext,
) {
- const { queryClient, viewerUserIdRef, projection, wsStore } = context
- wsStore.patchProfiles(wsStore.beginProfileSnapshot(), [{
+ const { queryClient, viewerUserIdRef, projection } = context
+ writeCommunityProfilePatches([{
id: event.member.userId,
identityAbout: {
name: event.member.name,
@@ -147,7 +176,7 @@ export function handleMemberJoin(
avatar: event.member.avatar ?? avatarInitial(event.member.name),
avatarVersion: event.member.avatarVersion,
},
- }])
+ }], undefined, { event: true })
const key = communityKeys.members(event.serverId)
queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(
key,
diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.ts
index 4060b6bc9..7bc06bc39 100644
--- a/src/web/src/hooks/community/community-ws/message-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts
@@ -7,6 +7,7 @@ import type {
} from "@alook/shared"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import { communityKeys } from "@/lib/query-keys"
+import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"
import {
registerReadSurface,
releaseReadSurface,
@@ -22,14 +23,17 @@ import {
import {
capturedOnMessage,
capturedQueryClient,
+ canonicalForumSidebar,
cleanupCommunityWsHarness,
forumSidebarFixture,
getCommunityApiFetchMock,
+ hasCanonicalChannel,
markReadMutate,
messageCreate,
mountHook,
resetCommunityWsHarness,
resetHookMemoization,
+ seedCanonicalForumSidebar,
} from "./test-harness"
const scheduleGapRepairMock = vi.hoisted(() => vi.fn(() => null))
@@ -93,9 +97,8 @@ describe("useCommunityWs — message.create", () => {
it("patches a loaded forum-sidebar child activity without a refetch", async () => {
await mountHook()
- seedParent("srv_1", "forum_1", "forum")
+ seedCanonicalForumSidebar("srv_1")
const key = communityKeys.forumSidebarThreads("srv_1")
- capturedQueryClient.setQueryData(key, forumSidebarFixture())
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event = {
...messageCreate("post_1"),
@@ -105,7 +108,7 @@ describe("useCommunityWs — message.create", () => {
capturedOnMessage!(event)
- const data = capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)
+ const data = canonicalForumSidebar("srv_1")
expect(data?.threads[0]).toMatchObject({
id: "post_1",
activityAt: "2026-07-03T00:00:00.000Z",
@@ -131,6 +134,59 @@ describe("useCommunityWs — message.create", () => {
})
})
+ it("warms an unknown forum child owner from live message evidence", async () => {
+ await mountHook()
+ seedCanonicalForumSidebar("srv_1")
+ expect(hasCanonicalChannel("post_live")).toBe(false)
+ getCommunityApiFetchMock().mockImplementation(async (url: string) => {
+ if (url === "/api/community/channels/post_live") {
+ return {
+ id: "post_live",
+ serverId: "srv_1",
+ name: "Live post",
+ type: "thread",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener_live",
+ creatorId: "u_other",
+ archived: false,
+ lastMessageAt: "2026-07-01T00:00:00.000Z",
+ createdAt: "2026-07-02T00:00:00.000Z",
+ }
+ }
+ if (url === "/api/community/users/me/read-state") {
+ return { revision: 0, readStates: [] }
+ }
+ throw new Error(`unexpected API fetch: ${url}`)
+ })
+
+ capturedOnMessage!({
+ ...messageCreate("post_live"),
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate)
+
+ await vi.waitFor(() => expect(hasCanonicalChannel("post_live")).toBe(true))
+ expect(getCanonicalCommunityChannels(capturedQueryClient)
+ .find((channel) => channel.id === "post_live")?.lastMessageAt)
+ .toBe("2026-07-03T00:00:00.000Z")
+ expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
+ "/api/community/channels/post_live",
+ { signal: undefined },
+ )
+
+ getCommunityApiFetchMock().mockRejectedValueOnce(new Error("metadata unavailable"))
+ capturedOnMessage!({
+ ...messageCreate("post_unavailable"),
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate)
+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
+ "/api/community/channels/post_unavailable",
+ { signal: undefined },
+ ))
+ expect(hasCanonicalChannel("post_unavailable")).toBe(false)
+ })
+
it.each([false, true])(
"patches retained content without promoting participation (active=%s)",
async (active) => {
@@ -139,14 +195,8 @@ describe("useCommunityWs — message.create", () => {
useCommunityStore.getState().subscribe({ channelId: "post_retained" })
}
await mountHook()
- seedParent("srv_1", "forum_1", "forum")
+ seedCanonicalForumSidebar("srv_1", ["post_retained"])
const key = communityKeys.forumSidebarThreads("srv_1")
- const retainedKey = communityKeys.forumSidebarRetained("srv_1", "post_retained")
- capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
- capturedQueryClient.setQueryData(
- retainedKey,
- forumSidebarFixture(["post_retained"]).threads[0],
- )
capturedOnMessage!({
...messageCreate("post_retained"),
@@ -154,19 +204,16 @@ describe("useCommunityWs — message.create", () => {
parentChannelId: "forum_1",
} satisfies CommunityMessageCreate)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>["threads"][number]>(
- retainedKey,
- )).toMatchObject({
+ expect(canonicalForumSidebar("srv_1").threads[0]).toMatchObject({
activityAt: "2026-07-03T00:00:00.000Z",
expiresAt: "2026-07-06T00:00:00.000Z",
})
await vi.waitFor(() => {
- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated ?? false).toBe(false)
})
- capturedQueryClient.setQueryData(key, forumSidebarFixture(["post_retained"]))
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)
- ?.threads.some((thread) => thread.id === "post_retained")).toBe(true)
+ expect(canonicalForumSidebar("srv_1").threads
+ .some((thread) => thread.id === "post_retained")).toBe(true)
},
)
@@ -954,13 +1001,7 @@ describe("useCommunityWs — message.updated", () => {
approval,
})
const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect([...useCommunityWsStore.getState().profilesByUserId.values()]).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ id: "u_other", name: "Other", avatar: "O" }),
- expect.objectContaining({ id: "bot_1", name: "Bot", avatar: "B" }),
- expect.objectContaining({ id: "waiting_1", name: "Waiting", avatar: "W" }),
- ]),
- )
+ expect(useCommunityWsStore.getState()).not.toHaveProperty("profilesByUserId")
})
it("refreshes approval fields on a focused channel row that exists only in the overlay", async () => {
@@ -1149,7 +1190,7 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>
capturedQueryClient.setQueryData(allKey, forumPage)
capturedQueryClient.setQueryData(bugKey, forumPage)
const sidebarKey = communityKeys.forumSidebarThreads("s1")
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
+ seedCanonicalForumSidebar("s1")
capturedQueryClient.setQueryData(communityKeys.threads("forum_1"), {
parentType: "forum",
serverId: "s1",
@@ -1168,8 +1209,7 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>
expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(allKey)?.pages[0].messages[0].content).toBe("new title")
expect(capturedQueryClient.getQueryData<{ pages: { messages: { content: string }[] }[] }>(bugKey)?.pages[0].messages[0].content).toBe("new title")
expect(capturedQueryClient.getQueryData<{ content: string }>(communityKeys.message("opener-post_1"))?.content).toBe("new title")
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads[0].title)
- .toBe("new title")
+ expect(canonicalForumSidebar("s1").threads[0]?.title).toBe("new title")
invalidateSpy.mockClear()
capturedOnMessage!({
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index dc59dca09..0254aaa1c 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -11,6 +11,7 @@ import { projectCommunityMessageCreate } from "@/lib/community/message-wire"
import { useCommunityStore } from "@/stores/community"
import { useMessageStreamStore } from "@/stores/community/message-stream"
import {
+ hasForumSidebarOwnershipEvidence,
isForumSidebarParent,
patchForumSidebarActivityExact,
} from "@/hooks/community/use-forum-sidebar-threads"
@@ -22,6 +23,7 @@ import { armInboxReadReservationCandidate } from "@/hooks/community/inbox-read-r
import {
approvalProfilePatches,
messageProfilePatches,
+ writeCommunityProfilePatches,
} from "@/lib/community/profile-seed"
import {
projectApprovalCopies,
@@ -33,12 +35,38 @@ import {
invalidateFriends,
invalidatePins,
} from "@/hooks/community/community-ws/invalidation-projections"
+import { fetchChannelMetadata } from "@/hooks/community/channel-metadata"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityChannelMetadata,
+} from "@/lib/community-db/sync"
type CommunityMessageEdited = Extract<
CommunityWsEvent,
{ type: "community:message.edited" }
>
+function warmLiveForumChildOwner(
+ queryClient: MessageEventContext["queryClient"],
+ event: CommunityMessageCreate,
+) {
+ if (
+ !event.serverId
+ || !event.parentChannelId
+ || !isForumSidebarParent(queryClient, event.serverId, event.parentChannelId)
+ || hasForumSidebarOwnershipEvidence(queryClient, event.serverId, event.channelId)
+ ) return
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ void fetchChannelMetadata(event.serverId, event.channelId)
+ .then((metadata) => {
+ publishCommunityChannelMetadata(queryClient, {
+ metadata,
+ proof: { token, signal: undefined },
+ })
+ })
+ .catch(() => undefined)
+}
+
export function handleMessageCreate(
event: CommunityMessageCreate,
{
@@ -51,21 +79,20 @@ export function handleMessageCreate(
projection,
}: MessageEventContext,
) {
+ warmLiveForumChildOwner(queryClient, event)
const viewerId = viewerUserIdRef.current
const hasSeenMessage = wsStore.hasSeenMessage(event.message.id)
const isForeignFocused = event.message.authorId !== viewerId
&& matchesFocus(event)
+ const projected = projectCommunityMessageCreate(event.message)
+ writeCommunityProfilePatches(messageProfilePatches([projected]), undefined, { event: true })
if (isForeignFocused && !hasSeenMessage) {
armInboxReadReservationCandidate(queryClient, {
channelId: event.channelId,
lastMessageAt: event.message.createdAt,
+ seq: event.message.seq,
})
}
- const projected = projectCommunityMessageCreate(event.message)
- wsStore.patchProfiles(
- wsStore.beginProfileSnapshot(),
- messageProfilePatches([projected]),
- )
if (event.channelId === sub.channelId || event.channelId === sub.secondaryChannelId) {
const serverId = useCommunityStore.getState().currentServerId
if (serverId) {
@@ -159,10 +186,7 @@ export function handleMessageUpdated(
event: CommunityMessageUpdated,
context: MessageEventContext,
) {
- context.wsStore.patchProfiles(
- context.wsStore.beginProfileSnapshot(),
- approvalProfilePatches(event.approval),
- )
+ writeCommunityProfilePatches(approvalProfilePatches(event.approval), undefined, { event: true })
projectApprovalCopies(event, context)
// When a card resolves (accepted/denied/superseded), the friend graph
// changed — invalidate friends + pending so the owner's lists reflect
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
index 3bdfb62ef..78ded90b6 100644
--- a/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.test.ts
@@ -23,7 +23,7 @@ beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — presence", () => {
- it("presence.update writes only to the canonical profile map", async () => {
+ it("presence.update writes only to the transient presence map", async () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
capturedQueryClient.setQueryData(communityKeys.friendsPresence(), {
@@ -36,7 +36,7 @@ describe("useCommunityWs — presence", () => {
}
capturedOnMessage!(event)
const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(useCommunityWsStore.getState().profilesByUserId.get("u_pres")?.presence).toBe("online")
+ expect(useCommunityWsStore.getState().presenceByUserId.get("u_pres")).toBe("online")
expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({
online: ["friend_existing"],
})
@@ -54,10 +54,7 @@ describe("useCommunityWs — presence", () => {
online: ["friend_non_member"],
})
const store = useCommunityWsStore.getState()
- store.patchProfiles(store.beginProfileSnapshot(), [{
- id: "friend_non_member",
- presence: "online",
- }])
+ store.setPresence("friend_non_member", "online")
const offline: CommunityPresenceUpdate = {
type: "community:presence.update",
@@ -65,7 +62,7 @@ describe("useCommunityWs — presence", () => {
online: false,
}
capturedOnMessage!(offline)
- expect(useCommunityWsStore.getState().profilesByUserId.get("friend_non_member")?.presence)
+ expect(useCommunityWsStore.getState().presenceByUserId.get("friend_non_member"))
.toBe("offline")
expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence()))
.toEqual({ online: ["friend_non_member"] })
@@ -83,8 +80,8 @@ describe("useCommunityWs — presence", () => {
})
})
-describe("useCommunityWs — status.update → Zustand store, no cache", () => {
- it("status.update writes to useCommunityWsStore only", async () => {
+describe("useCommunityWs — status.update", () => {
+ it("does not create a durable status track in Zustand", async () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event: CommunityStatusUpdate = {
@@ -95,11 +92,8 @@ describe("useCommunityWs — status.update → Zustand store, no cache", () => {
}
capturedOnMessage!(event)
const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(useCommunityWsStore.getState().profilesByUserId.get("u_status")).toMatchObject({
- statusEmoji: "🎧",
- statusText: "Vibing",
- })
- // No cache touched.
+ expect(useCommunityWsStore.getState()).not.toHaveProperty("profilesByUserId")
+ expect(useCommunityWsStore.getState().presenceByUserId.has("u_status")).toBe(false)
expect(spy).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/hooks/community/community-ws/presence-machine-events.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
index d22e31b94..a4dfd9434 100644
--- a/src/web/src/hooks/community/community-ws/presence-machine-events.ts
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.ts
@@ -18,23 +18,13 @@ import type { PresenceMachineEventContext } from "@/hooks/community/community-ws
export function handlePresenceUpdate(
event: CommunityPresenceUpdate,
) {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
- id: event.userId,
- presence: event.online ? "online" : "offline",
- }])
+ useCommunityWsStore.getState().setPresence(
+ event.userId,
+ event.online ? "online" : "offline",
+ )
}
-// Status uses the same WS-store overlay pattern as presence.
-export function handleStatusUpdate(event: CommunityStatusUpdate) {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
- id: event.userId,
- status: {
- statusEmoji: event.statusEmoji,
- statusText: event.statusText,
- },
- }])
+export function handleStatusUpdate(_event: CommunityStatusUpdate) {
}
// Push audit events into the bounded ring; the audit-log hook filters and
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 b46758554..c1703d0f0 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
@@ -73,6 +73,63 @@ describe("account read-state reconciliation", () => {
})
})
+ it("discards an in-flight snapshot superseded by a newer target revision", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), {
+ lastReadMessageId: "m4",
+ lastReadAt: "2026-08-24T00:00:04.000Z",
+ lastReadSeq: 4,
+ })
+ const releases: Array<(snapshot: AccountReadStateSnapshot) => void> = []
+ apiFetch.mockImplementation(() => new Promise<AccountReadStateSnapshot>((resolve) => {
+ releases.push(resolve)
+ }))
+
+ const first = reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })
+ await vi.waitFor(() => expect(releases).toHaveLength(1))
+ const second = reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 6,
+ })
+ releases[0]!({
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m5",
+ lastReadAt: "2026-08-24T00:00:05.000Z",
+ lastReadSeq: 5,
+ }],
+ })
+ await vi.waitFor(() => expect(releases).toHaveLength(2))
+
+ expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
+ .toMatchObject({ revision: 4 })
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ .toMatchObject({ lastReadSeq: 4 })
+
+ releases[1]!({
+ revision: 6,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m6",
+ lastReadAt: "2026-08-24T00:00:06.000Z",
+ lastReadSeq: 6,
+ }],
+ })
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ expect.objectContaining({ revision: 6 }),
+ expect.objectContaining({ revision: 6 }),
+ ])
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ .toMatchObject({ lastReadSeq: 6 })
+ })
+
it("uses all surfaces when options are omitted", async () => {
apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
const invalidate = vi.spyOn(queryClient, "invalidateQueries")
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 f97bf44d0..79083813c 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
@@ -6,6 +6,11 @@ import {
} from "@/lib/query-keys"
import { projectReadCoordinatorSnapshot } from "@/hooks/community/read-coordinator-snapshot-projection"
import { acceptAccountUnreadPrimarySnapshot } from "@/hooks/community/account-unread-projection"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityLiveSnapshot,
+ type CommunityLiveSnapshotToken,
+} from "@/lib/community-db/sync"
type AccountReadState = {
channelId: string
@@ -90,7 +95,19 @@ function projectReadStateRows(queryClient: QueryClient, snapshot: AccountReadSta
function applyAccountReadStateSnapshot(
queryClient: QueryClient,
snapshot: AccountReadStateSnapshot,
+ proof: {
+ token: CommunityLiveSnapshotToken
+ signal: AbortSignal
+ requestGeneration: number
+ currentRequestGeneration: number
+ targetRevision: number | null
+ },
) {
+ const publication = publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "read-state", data: snapshot },
+ proof: { kind: "read-state", ...proof },
+ })
+ if (publication === "superseded") return "superseded" as const
const current = queryClient.getQueryData<AccountReadStateSnapshot>(
communityKeys.accountReadStateSnapshot(),
)
@@ -374,13 +391,22 @@ async function runSnapshotWorker(
const requestGeneration = state.snapshotRequestedGeneration
let snapshot: AccountReadStateSnapshot
try {
- snapshot = await startAccountReadStateRequest(state)
+ const response = await startAccountReadStateRequest(queryClient, state)
+ snapshot = response.snapshot
+ assertReconciliationActive(queryClient, state, epoch)
+ const applied = applyAccountReadStateSnapshot(queryClient, snapshot, {
+ token: response.token,
+ signal: response.signal,
+ requestGeneration,
+ currentRequestGeneration: state.snapshotRequestedGeneration,
+ targetRevision: state.highestPendingTargetRevision,
+ })
+ if (applied === "superseded") continue
} catch (error) {
scheduleReconciliationRetry(queryClient, state, "snapshot")
throw error
}
assertReconciliationActive(queryClient, state, epoch)
- applyAccountReadStateSnapshot(queryClient, snapshot)
state.snapshotCompletedGeneration = Math.max(
state.snapshotCompletedGeneration,
requestGeneration,
@@ -489,13 +515,17 @@ function assertReconciliationActive(
) throw new Error("account read-state reconciliation disposed")
}
-function startAccountReadStateRequest(state: ReconciliationState) {
+function startAccountReadStateRequest(
+ queryClient: QueryClient,
+ state: ReconciliationState,
+) {
const controller = new AbortController()
+ const token = captureCommunityLiveSnapshotToken(queryClient)
state.requestController = controller
return apiFetch<AccountReadStateSnapshot>(
"/api/community/users/me/read-state",
{ signal: controller.signal },
- ).finally(() => {
+ ).then((snapshot) => ({ snapshot, token, signal: controller.signal })).finally(() => {
if (state.requestController === controller) state.requestController = null
})
}
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
index 02fda1252..0c8c28824 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
@@ -13,11 +13,21 @@ import {
} from "./reconnect-messages"
const apiFetchMock = vi.hoisted(() => vi.fn())
+const publicationToken = vi.hoisted(() => ({ canonicalRevision: 7 }))
+const captureCommunityLiveSnapshotTokenMock = vi.hoisted(() => vi.fn(() => publicationToken))
+const publishCommunityMessagesMock = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
+vi.mock("@/lib/community-db/sync", () => ({
+ captureCommunityLiveSnapshotToken: (...args: unknown[]) => (
+ captureCommunityLiveSnapshotTokenMock(...args)
+ ),
+ publishCommunityMessages: (...args: unknown[]) => publishCommunityMessagesMock(...args),
+}))
+
function seedActiveQuery(
queryClient: QueryClient,
queryKey: readonly unknown[],
@@ -83,6 +93,8 @@ function seedEmptyActiveQuery(
beforeEach(() => {
apiFetchMock.mockReset()
+ captureCommunityLiveSnapshotTokenMock.mockClear()
+ publishCommunityMessagesMock.mockReset()
useCommunityWsStore.getState().reset()
})
@@ -140,6 +152,7 @@ describe("focused message reconnect catch-up", () => {
const queryClient = new QueryClient()
const queryKey = communityKeys.channelMessages("ch_gap")
const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ const setQueryDataSpy = vi.spyOn(queryClient, "setQueryData")
apiFetchMock
.mockResolvedValueOnce({
messages: [{
@@ -176,6 +189,20 @@ describe("focused message reconnect catch-up", () => {
expect(second).toBe(first)
await first
expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ expect(captureCommunityLiveSnapshotTokenMock).toHaveBeenCalledOnce()
+ expect(publishCommunityMessagesMock).toHaveBeenCalledWith(queryClient, {
+ channelId: "ch_gap",
+ messages: expect.arrayContaining([
+ expect.objectContaining({ id: "m_2" }),
+ expect.objectContaining({ id: "m_3" }),
+ expect.objectContaining({ id: "m_6" }),
+ ]),
+ proof: { token: publicationToken, signal: undefined },
+ })
+ expect(captureCommunityLiveSnapshotTokenMock.mock.invocationCallOrder[0])
+ .toBeLessThan(apiFetchMock.mock.invocationCallOrder[0]!)
+ expect(publishCommunityMessagesMock.mock.invocationCallOrder[0])
+ .toBeLessThan(setQueryDataSpy.mock.invocationCallOrder[0]!)
unsubscribe()
})
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 b471ae084..33e8ca70a 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -4,6 +4,10 @@ import { ApiError } from "@/lib/errors"
import { captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"
import { communityKeys } from "@/lib/query-keys"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityMessages,
+} from "@/lib/community-db/sync"
import type {
MessagesPage,
MessagesPageParam,
@@ -303,6 +307,7 @@ export async function reconcileFocusedMessageQueries(
})
const token = captureChannelMetadataToken(scopeId)
const operations = queries.map(async (query) => {
+ const publicationToken = captureCommunityLiveSnapshotToken(queryClient)
const isCurrent = () => isChannelMetadataTokenCurrent(token)
&& queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query
// Infinite-query pagination computes its result from the data snapshot at
@@ -338,6 +343,13 @@ export async function reconcileFocusedMessageQueries(
? await fetchCatchUp(scopeId, window.cursor, window.tag)
: null
if (!isCurrent()) return
+ publishCommunityMessages(queryClient, {
+ channelId: scopeId,
+ messages: catchUp
+ ? [...refreshed.messages, ...catchUp.messages]
+ : refreshed.messages,
+ proof: { token: publicationToken, signal: undefined },
+ })
queryClient.setQueryData<MessageCache>(query.queryKey, (current) => (
isMessageCache(current)
? mergeReconciledPages(current, refreshed, catchUp)
diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.ts
index 01874fff3..2f759f13a 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts
@@ -8,6 +8,7 @@ import {
cleanupCommunityWsHarness,
flushEffects,
getCommunityApiFetchMock,
+ forumSidebarFixture,
messageCreate,
mountHook,
resetHookMemoization,
@@ -67,11 +68,6 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
await capturedOnReconnect!({ reconnectDurationMs: 1_000 })
expect(apiFetch).toHaveBeenCalledWith("/api/community/users/self/profile")
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(useCommunityWsStore.getState().profilesByUserId.get("self")).toMatchObject({
- avatar: "/api/community/users/self/avatar?v=7",
- avatarVersion: 7,
- })
})
it("invalidates cached identity surfaces after a reconnect gap", async () => {
@@ -87,18 +83,16 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
const { useCommunityWsStore } = await import("@/stores/community/ws")
const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [
- { id: "self", presence: "online" },
- { id: "peer", presence: "online" },
- ])
+ profiles.setPresence("self", "online")
+ profiles.setPresence("peer", "online")
await reconcileCommunityWsReconnect(capturedQueryClient, 0, {
viewerUserId: "self",
})
- expect(useCommunityWsStore.getState().profilesByUserId.get("self")?.presence)
+ expect(useCommunityWsStore.getState().presenceByUserId.get("self"))
.toBe("online")
- expect(useCommunityWsStore.getState().profilesByUserId.get("peer")?.presence)
+ expect(useCommunityWsStore.getState().presenceByUserId.get("peer"))
.toBe("offline")
})
@@ -312,14 +306,6 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().setCurrentServerId("srv_open")
capturedQueryClient.setQueryData(communityKeys.server("srv_open"), { id: "srv_open" })
- capturedQueryClient.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "viewer",
- capturedAt: Date.now(),
- serverOrder: ["srv_open"],
- folders: [],
- servers: [],
- })
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
// handleReconnect reads currentServerId via getState() at call time.
@@ -350,11 +336,6 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
(k) => JSON.stringify(k) === JSON.stringify(communityKeys.members("srv_open")),
),
).toBe(true)
- expect(
- invalidatedKeys.some(
- (k) => JSON.stringify(k) === JSON.stringify(communityKeys.structuralSnapshot()),
- ),
- ).toBe(false)
})
it("keeps inactive retained/meta/hint data painted while marking it stale", async () => {
@@ -499,10 +480,14 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
communityKeys.members(serverId),
communityKeys.presence(serverId),
communityKeys.invites(serverId),
- communityKeys.forumSidebarThreads(serverId),
]) {
expect(calls).toContainEqual({ queryKey, exact: true, refetchType: "active" })
}
+ expect(calls).toContainEqual({
+ queryKey: communityKeys.forumSidebarThreads(serverId),
+ exact: true,
+ refetchType: "none",
+ })
for (const queryKey of [
communityKeys.forumSidebarRetained(serverId, "child"),
communityKeys.channelMeta(serverId, "child"),
@@ -561,21 +546,47 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(telemetry.complete).toHaveBeenCalledWith(summary)
})
+ it("waits for forum notify reconciliation and reports its reconnect failure", async () => {
+ const { reconcileCommunityWsReconnect } = await import("./reconnect")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_notify"), { id: "srv_notify" })
+ let rejectSidebar!: (error: Error) => void
+ getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
+ if (url === "/api/community/users/me/read-state") {
+ return { revision: 0, readStates: [] }
+ }
+ if (String(url).startsWith("/api/community/servers/srv_notify/channels?")) {
+ return await new Promise((_resolve, reject) => { rejectSidebar = reject })
+ }
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
+
+ let settled = false
+ const pending = reconcileCommunityWsReconnect(capturedQueryClient, 25)
+ .finally(() => { settled = true })
+ await vi.waitFor(() => expect(rejectSidebar).toBeTypeOf("function"))
+ expect(settled).toBe(false)
+ rejectSidebar(new Error("private sidebar transport detail"))
+ const summary = await pending
+
+ expect(summary).toMatchObject({ failureCount: 1, reconnectDurationMs: 25 })
+ expect(telemetry.failure).toHaveBeenCalledWith({
+ policy: "all-cached-servers",
+ reason: "async-rejection",
+ })
+ expect(JSON.stringify(telemetry.failure.mock.calls)).not.toContain("private sidebar transport detail")
+ })
+
it("isolates a policy rejection and reports only the stable policy key", async () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
const { useCommunityWsStore } = await import("@/stores/community/ws")
- const originalPatchProfiles = useCommunityWsStore.getState().patchProfiles
- let patchCallCount = 0
+ const originalSetPresence = useCommunityWsStore.getState().setPresence
+ originalSetPresence("peer", "online")
useCommunityWsStore.setState({
- patchProfiles: (...args) => {
- patchCallCount += 1
- if (patchCallCount === 1) throw new Error("private sync detail")
- return originalPatchProfiles(...args)
- },
+ setPresence: () => { throw new Error("private sync detail") },
})
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)
- useCommunityWsStore.setState({ patchProfiles: originalPatchProfiles })
+ useCommunityWsStore.setState({ setPresence: originalSetPresence })
expect(summary).toMatchObject({ policyCount: 15, successCount: 14, failureCount: 1 })
expect(telemetry.failure).toHaveBeenCalledWith({
@@ -642,22 +653,17 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
}
})
- it("resets presence and status overlays before authoritative invalidation starts", async () => {
+ it("resets the presence overlay before authoritative invalidation starts", async () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
const { useCommunityWsStore } = await import("@/stores/community/ws")
const store = useCommunityWsStore.getState()
- store.patchProfiles(store.beginProfileSnapshot(), [{
- id: "peer",
- presence: "online",
- status: { statusEmoji: "🌱", statusText: "Growing" },
- }])
- const originalPatchProfiles = useCommunityWsStore.getState().patchProfiles
+ store.setPresence("peer", "online")
+ const originalSetPresence = useCommunityWsStore.getState().setPresence
const order: string[] = []
useCommunityWsStore.setState({
- patchProfiles: (_snapshot, patches) => {
- if (patches.some((patch) => patch.presence !== undefined)) order.push("presence-reset")
- if (patches.some((patch) => patch.status !== undefined)) order.push("status-reset")
- return true
+ setPresence: (userId, presence) => {
+ if (userId === "peer" && presence === "offline") order.push("presence-reset")
+ originalSetPresence(userId, presence)
},
})
const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)
@@ -672,11 +678,11 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
await reconcileCommunityWsReconnect(capturedQueryClient)
useCommunityWsStore.setState({
- patchProfiles: originalPatchProfiles,
+ setPresence: originalSetPresence,
})
- expect(order.slice(0, 2)).toEqual(["presence-reset", "status-reset"])
- expect(order.indexOf("authoritative-invalidate")).toBeGreaterThan(1)
+ expect(order[0]).toBe("presence-reset")
+ expect(order.indexOf("authoritative-invalidate")).toBeGreaterThan(0)
})
it("waits for focused route reconciliation before starting background domains", async () => {
@@ -777,6 +783,14 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
it("refetches only active server A and makes inactive forever-fresh server B fetch on mount", async () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
+ const apiFetch = getCommunityApiFetchMock()
+ apiFetch.mockImplementation(async (url: unknown) => {
+ if (url === "/api/community/users/me/read-state") {
+ return { revision: 0, readStates: [] }
+ }
+ if (String(url).includes("/channels?")) return forumSidebarFixture([])
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
})
@@ -787,7 +801,6 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
communityKeys.members(serverId),
communityKeys.presence(serverId),
communityKeys.invites(serverId),
- communityKeys.forumSidebarThreads(serverId),
] as const
const queryFn = (serverId: "srv_a" | "srv_b", queryKey: readonly unknown[]) => async () => {
const name = JSON.stringify(queryKey)
@@ -798,6 +811,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
for (const queryKey of keys(serverId)) {
await queryClient.fetchQuery({ queryKey, queryFn: queryFn(serverId, queryKey) })
}
+ queryClient.setQueryData(communityKeys.forumSidebarThreads(serverId), { seeded: true })
}
queryClient.setQueryData(communityKeys.forumSidebarRetained("srv_b", "private-child"), { stale: true })
queryClient.setQueryData(communityKeys.channelMeta("srv_b", "private-child"), { stale: true })
@@ -827,6 +841,12 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(queryClient.getQueryData(queryKey)).toMatchObject({ version: 2 })
expect(fetches.get(JSON.stringify(queryKey))).toBe(2)
}
+ for (const serverId of ["srv_a", "srv_b"] as const) {
+ expect(queryClient.getQueryData(communityKeys.forumSidebarThreads(serverId)))
+ .toMatchObject({ threads: [], serverNow: "2026-08-01T00:00:00.000Z" })
+ }
+ expect(apiFetch.mock.calls.filter(([url]) => String(url).includes("/channels?")))
+ .toHaveLength(2)
for (const queryKey of [
communityKeys.forumSidebarRetained("srv_b", "private-child"),
communityKeys.channelMeta("srv_b", "private-child"),
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index aeb683e4e..c1c4f5d65 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -6,7 +6,7 @@ import {
} from "@/lib/query-keys"
import { useCommunityStore } from "@/stores/community"
import { useCommunityWsStore } from "@/stores/community/ws"
-import { invalidateForumSidebarBaseExact } from "@/hooks/community/use-forum-sidebar-threads"
+import { reconcileForumSidebarNotifyMemberships } from "@/hooks/community/use-forum-sidebar-threads"
import { clearAllTypingIndicators } from "@/hooks/community/community-ws/typing"
import { communityWsReconnectPolicies } from "@/hooks/community/community-ws/registry"
import { userProfileQueryFn } from "@/hooks/community/use-user-profile"
@@ -117,7 +117,7 @@ async function reconcileCachedServer(queryClient: QueryClient, serverId: string)
exact: true,
refetchType: "active",
}),
- invalidateForumSidebarBaseExact(queryClient, serverId),
+ reconcileForumSidebarNotifyMemberships(queryClient, serverId),
])
if (settled.some((result) => result.status === "rejected")) {
throw new Error("server reconciliation failed")
@@ -204,6 +204,7 @@ function policyExecutors(
},
"inbox-dms": async () => {
const settled = await Promise.allSettled([
+ queryClient.invalidateQueries({ queryKey: communityKeys.accountAttention(), refetchType: "active" }),
queryClient.invalidateQueries({ queryKey: communityKeys.inbox(), refetchType: "active" }),
queryClient.invalidateQueries({ queryKey: communityKeys.dms(), refetchType: "active" }),
])
@@ -228,26 +229,14 @@ function policyExecutors(
await queryClient.invalidateQueries({ queryKey: communityKeys.friends(), refetchType: "active" })
},
"presence-overlay": async () => {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(
- profiles.beginProfileSnapshot(),
- [...profiles.profilesByUserId.values()]
- .filter((profile) => (
- profile.id !== viewerUserId && profile.presence === "online"
- ))
- .map((profile) => ({ id: profile.id, presence: "offline" as const })),
- )
- },
- "status-overlay": async () => {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(
- profiles.beginProfileSnapshot(),
- [...profiles.profilesByUserId.keys()].map((id) => ({
- id,
- status: { statusEmoji: null, statusText: null },
- })),
- )
+ const presence = useCommunityWsStore.getState()
+ for (const [userId, status] of presence.presenceByUserId) {
+ if (userId !== viewerUserId && status === "online") {
+ presence.setPresence(userId, "offline")
+ }
+ }
},
+ "status-overlay": async () => undefined,
"identity-surfaces": async () => {
const hasIdentitySurface = queryClient.getQueryCache().getAll().some((query) => (
query.queryKey[0] === "community"
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index d391e8eaa..bd7e9f1fb 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -49,6 +49,8 @@ import {
handleIdentityUpdate,
handleProfileUpdate,
} from "@/hooks/community/community-ws/identity-events"
+import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import { scheduleAccountAttentionReconcile } from "@/hooks/community/use-account-attention"
type CommunityEventType = CommunityWsEvent["type"]
type CommunityEventFor<T extends CommunityEventType> = Extract<CommunityWsEvent, { type: T }>
@@ -178,6 +180,15 @@ export function dispatchCommunityWsEvents(
if (channelId && serverId) useCommunityWsStore.getState().observeChannelScope(serverId, channelId, parentChannelId)
const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>
entry.handler(event, handlerContext)
+ projectCommunityWsEventToDb(context.queryClient, event)
+ if ([
+ "community:server.delete",
+ "community:channel.delete",
+ "community:channel.member_remove",
+ "community:member.leave",
+ ].includes(event.type)) {
+ scheduleAccountAttentionReconcile(context.queryClient)
+ }
}
})
}
diff --git a/src/web/src/hooks/community/community-ws/scope-eviction.test.ts b/src/web/src/hooks/community/community-ws/scope-eviction.test.ts
index c516be1b1..7b998332d 100644
--- a/src/web/src/hooks/community/community-ws/scope-eviction.test.ts
+++ b/src/web/src/hooks/community/community-ws/scope-eviction.test.ts
@@ -1,6 +1,11 @@
import { QueryClient } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { communityKeys } from "@/lib/query-keys"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { ingestServerDetail } from "@/lib/community-db/sync"
import {
beginOwnerServerDelete,
cancelOwnerServerDelete,
@@ -24,6 +29,23 @@ describe("owner-delete scope eviction", () => {
cancelOwnerServerDelete(otherServerId)
})
+ it("purges the registered canonical server during immediate scope eviction", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestServerDetail(registry, {
+ id: otherServerId, name: "Other", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer", categories: [],
+ })
+
+ expect(evictServerChannelScopes(queryClient, otherServerId)).toBe(true)
+ expect(registry.collections.servers.get(otherServerId)).toBeUndefined()
+
+ unregister()
+ await registry.cleanup()
+ })
+
it("merges mutation and WS eviction until one safe route commit flushes once", () => {
const queryClient = new QueryClient()
queryClient.setQueryData(communityKeys.server(deletedServerId), {
diff --git a/src/web/src/hooks/community/community-ws/scope-eviction.ts b/src/web/src/hooks/community/community-ws/scope-eviction.ts
index 352ca3528..8915ba03c 100644
--- a/src/web/src/hooks/community/community-ws/scope-eviction.ts
+++ b/src/web/src/hooks/community/community-ws/scope-eviction.ts
@@ -4,7 +4,8 @@ import { useCommunityWsStore } from "@/stores/community/ws"
import { useCommunityStore } from "@/stores/community"
import { useMessageStreamStore } from "@/stores/community/message-stream"
import { clearTypingIndicator } from "./typing"
-import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { purgeCommunityServer } from "@/lib/community-db/sync"
import {
claimOwnerServerDeleteScopeFlush,
completeOwnerServerDeleteScopeFlush,
@@ -128,7 +129,8 @@ function evictServerChannelScopesNow(queryClient: QueryClient, serverId: string)
community.setCurrentChannelId(null)
community.setCurrentServerId(null)
}
- updateStructuralSnapshot(queryClient, { type: "removeServer", serverId })
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry) purgeCommunityServer(registry, serverId)
}
export function evictServerChannelScopes(queryClient: QueryClient, serverId: string): boolean {
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index b4351fd80..a61b58506 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -25,17 +25,23 @@ import { removeDmReactionDetails } from "./reaction-details-invalidation"
import { reconcileNotificationSettings } from "@/hooks/community/use-notification-settings"
import { getFriendRequestActionController } from "@/hooks/community/use-friend-request-action-state"
import { communityKeys } from "@/lib/query-keys"
-import type { StructuralSnapshotV1 } from "@/lib/community/structural-snapshot"
import {
resolveDesktopSystemNotificationCandidate,
showDesktopSystemNotification,
} from "@/lib/community/desktop-system-notification"
+import {
+ projectAttentionFriendEvent,
+ projectAttentionMentionHint,
+ projectAttentionUnreadBump,
+} from "@/lib/community-db/sync"
+import { scheduleAccountAttentionReconcile } from "@/hooks/community/use-account-attention"
export function handleReadStateAdvanced(
event: CommunityReadStateAdvanced,
context: SocialEventContext,
) {
applyReadStateEnvelope(event, context)
+ scheduleAccountAttentionReconcile(context.queryClient)
}
function applyReadStateEnvelope(
@@ -60,6 +66,7 @@ export function handleInboxChanged(
void reconcileNotificationSettings(context.queryClient).catch(() => undefined)
}
applyReadStateEnvelope(event, context)
+ scheduleAccountAttentionReconcile(context.queryClient)
}
type CommunityUnreadBump = Extract<
@@ -86,6 +93,8 @@ export function handleUnreadBump(
const viewerId = viewerUserIdRef.current
if (event.userId === viewerId && viewerId) {
const evidence = unreadBumpEvidence?.get(event)
+ projectAttentionUnreadBump(queryClient, event, evidence)
+ scheduleAccountAttentionReconcile(queryClient)
getAccountUnreadProjection(queryClient, viewerId).recordArrival({
channelId: event.channelId,
railChannelId: event.railChannelId,
@@ -103,7 +112,6 @@ export function handleUnreadBump(
event,
viewerId,
queryClient,
- queryClient.getQueryData<StructuralSnapshotV1>(communityKeys.structuralSnapshot()) ?? null,
).then((candidate) => {
if (candidate && viewerUserIdRef.current === viewerId) {
return showDesktopSystemNotification(candidate)
@@ -124,6 +132,8 @@ export function handleFriendEvent(
event: FriendEvent,
{ projection, queryClient }: SocialEventContext,
) {
+ projectAttentionFriendEvent(queryClient, event)
+ scheduleAccountAttentionReconcile(queryClient)
if (event.type === "community:friend.request") {
invalidateFriends(projection)
invalidateInboxUnreads(projection)
@@ -163,6 +173,8 @@ export function handleMentionCreate(
if (viewerId && event.userId === viewerId && event.channelId) {
const candidate = messageEvidenceByChannel?.get(event.channelId)
const evidence = candidate?.messageId === event.messageId ? candidate : undefined
+ projectAttentionMentionHint(queryClient, event, evidence)
+ scheduleAccountAttentionReconcile(queryClient)
getAccountUnreadProjection(queryClient, viewerId).recordMentionArrival({
channelId: event.channelId,
messageId: event.messageId,
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
index d88eccc92..9902b2cb9 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts
@@ -20,13 +20,19 @@ import { getAccountUnreadProjection } from "@/hooks/community/account-unread-pro
import {
capturedOnMessage,
capturedQueryClient,
+ canonicalForumSidebar,
cleanupCommunityWsHarness,
forumSidebarFixture,
+ getCommunityApiFetchMock,
+ hasCanonicalChannelAccess,
+ hasCanonicalChannelNotify,
messageCreate,
mountHook,
resetCommunityWsHarness,
resetHookMemoization,
+ seedCanonicalForumSidebar,
} from "./test-harness"
+import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"
function forumFeedFixture(rows: Array<{ id: string; opener: string; tags: string[] }>) {
return {
@@ -82,32 +88,12 @@ function forumFeedIds(filter: string | null) {
)?.pages.flatMap((page) => page.threads.map((thread) => thread.id)) ?? []
}
-function seedStructuralSnapshot(serverId = "srv_1") {
- capturedQueryClient.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "u_me",
- capturedAt: Date.now(),
- serverOrder: [serverId],
- folders: [],
- servers: [{
- id: serverId,
- name: "old",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [{ id: "ch_old", name: "old", type: "text", categoryId: null }],
- childRouteHints: [],
- }],
- })
-}
-
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — server.update patches server + list caches", () => {
it("applies name and description changes to server(id) and servers()", async () => {
await mountHook()
- seedStructuralSnapshot()
capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
id: "srv_1",
name: "old",
@@ -148,11 +134,6 @@ describe("useCommunityWs — server.update patches server + list caches", () =>
communityKeys.servers(),
)?.servers[0],
).toMatchObject({ name: "new", description: "new description", initial: "N" })
- const structural = capturedQueryClient.getQueryData<{
- servers: Array<Record<string, unknown>>
- }>(communityKeys.structuralSnapshot())
- expect(structural?.servers[0]).toMatchObject({ name: "new" })
- expect(structural?.servers[0]).not.toHaveProperty("description")
})
})
describe("useCommunityWs — child channel events", () => {
@@ -176,78 +157,11 @@ describe("useCommunityWs — child channel events", () => {
expect(keys).not.toContainEqual(communityKeys.channelMessages("ch_1"))
})
- it("projects a background child hint into the server that owns its parent", async () => {
- await mountHook()
- seedStructuralSnapshot("srv_background")
- const { useCommunityStore } = await import("@/stores/community")
- useCommunityStore.getState().setCurrentServerId("srv_foreground")
-
- capturedOnMessage!({
- type: "community:channel.child_create",
- parentChannelId: "ch_old",
- parentMessageId: "opener_1",
- channel: {
- id: "child_1",
- name: "Thread",
- type: "thread",
- createdAt: "2026-09-08T00:00:00.000Z",
- },
- } satisfies CommunityChildChannelCreate)
-
- expect(capturedQueryClient.getQueryData<{
- servers: Array<{ id: string; childRouteHints: Array<{ id: string }> }>
- }>(communityKeys.structuralSnapshot())?.servers[0]).toMatchObject({
- id: "srv_background",
- childRouteHints: [{ id: "child_1" }],
- })
- })
-
- it("renames and archives a persisted child hint from structural events", async () => {
- await mountHook()
- seedStructuralSnapshot()
- capturedQueryClient.setQueryData<any>(
- communityKeys.structuralSnapshot(),
- (current: any) => ({
- ...current,
- servers: current.servers.map((server: any) => ({
- ...server,
- childRouteHints: [{
- id: "child_1",
- name: "Old",
- type: "thread",
- parentChannelId: "ch_old",
- parentMessageId: "opener_1",
- }],
- })),
- }),
- )
-
- capturedOnMessage!({
- type: "community:channel.child_update",
- parentChannelId: "ch_old",
- channelId: "child_1",
- changes: { name: "Renamed" },
- } satisfies CommunityChildChannelUpdate)
- expect(capturedQueryClient.getQueryData<any>(
- communityKeys.structuralSnapshot(),
- ).servers[0].childRouteHints[0].name).toBe("Renamed")
-
- capturedOnMessage!({
- type: "community:channel.child_update",
- parentChannelId: "ch_old",
- channelId: "child_1",
- changes: { archived: true },
- } satisfies CommunityChildChannelUpdate)
- expect(capturedQueryClient.getQueryData<any>(
- communityKeys.structuralSnapshot(),
- ).servers[0].childRouteHints).toEqual([])
- })
})
describe("useCommunityWs — channel.* invalidates server(id)", () => {
it("channel.create invalidates server(serverId)", async () => {
await mountHook()
- seedStructuralSnapshot()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event: CommunityChannelCreate = {
type: "community:channel.create",
@@ -267,59 +181,6 @@ describe("useCommunityWs — channel.* invalidates server(id)", () => {
return Array.isArray(key) && key.includes("srv_1")
}),
).toBe(true)
- expect(capturedQueryClient.getQueryData<{
- servers: Array<{ channels: Array<{ id: string }> }>
- }>(communityKeys.structuralSnapshot())?.servers[0]?.channels.map((channel) => channel.id))
- .toEqual(["ch_new", "ch_old"])
- })
-
- it("projects channel update and canonical reorder fields", async () => {
- await mountHook()
- seedStructuralSnapshot()
-
- capturedOnMessage!({
- type: "community:channel.create",
- serverId: "srv_1",
- channel: {
- id: "ch_second",
- name: "second",
- type: "text",
- categoryId: null,
- position: 1,
- createdAt: "2026-09-08T00:00:00.000Z",
- },
- } satisfies CommunityChannelCreate)
- capturedOnMessage!({
- type: "community:channel.update",
- serverId: "srv_1",
- channelId: "ch_second",
- changes: { name: "updated", type: "forum", categoryId: null },
- } satisfies CommunityChannelUpdate)
- capturedOnMessage!({
- type: "community:channel.update",
- serverId: "srv_1",
- channelId: "ch_second",
- changes: { name: "name-only" },
- } satisfies CommunityChannelUpdate)
- capturedOnMessage!({
- type: "community:channel.reorder",
- serverId: "srv_1",
- channels: [
- { id: "ch_old", position: 2 },
- { id: "ch_second", position: 1 },
- ],
- } satisfies CommunityChannelReorder)
-
- const channels = capturedQueryClient.getQueryData<any>(
- communityKeys.structuralSnapshot(),
- ).servers[0].channels
- expect(channels.map((channel: { id: string }) => channel.id))
- .toEqual(["ch_second", "ch_old"])
- expect(channels[0]).toMatchObject({
- name: "name-only",
- type: "forum",
- categoryId: null,
- })
})
})
@@ -349,43 +210,6 @@ describe("useCommunityWs — category.* invalidates tree projections", () => {
})
})
- it("projects category update, reorder, and delete into the structural tree", async () => {
- await mountHook()
- seedStructuralSnapshot()
-
- for (const [id, position] of [["cat_a", 0], ["cat_b", 1]] as const) {
- capturedOnMessage!({
- type: "community:category.create",
- serverId: "srv_1",
- category: { id, name: id, position, private: false },
- } satisfies CommunityCategoryCreate)
- }
- capturedOnMessage!({
- type: "community:category.update",
- serverId: "srv_1",
- categoryId: "cat_a",
- changes: { name: "Renamed", private: true, position: 1 },
- } satisfies CommunityCategoryUpdate)
- capturedOnMessage!({
- type: "community:category.reorder",
- serverId: "srv_1",
- categories: [
- { id: "cat_a", position: 2 },
- { id: "cat_b", position: 1 },
- ],
- } satisfies CommunityCategoryReorder)
- capturedOnMessage!({
- type: "community:category.delete",
- serverId: "srv_1",
- categoryId: "cat_b",
- } satisfies CommunityCategoryDelete)
-
- expect(capturedQueryClient.getQueryData<any>(
- communityKeys.structuralSnapshot(),
- ).servers[0].categories).toEqual([
- { id: "cat_a", name: "Renamed", private: true },
- ])
- })
})
describe("useCommunityWs — invite.create", () => {
@@ -412,40 +236,18 @@ describe("useCommunityWs — invite.create", () => {
})
describe("useCommunityWs — channel.delete evicts channel-scoped caches", () => {
- it("prunes the structural channel and its child hints after scope eviction", async () => {
+ it("clears ephemeral channel state after scope eviction", async () => {
await mountHook()
- seedStructuralSnapshot()
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.setState({
typingByScope: new Map([["ch:ch_old", new Map([["u_typing", "Typer"]])]]),
})
- capturedQueryClient.setQueryData<{ servers: Array<{
- childRouteHints: Array<Record<string, unknown>>
- }> }>(communityKeys.structuralSnapshot(), (current) => current && ({
- ...current,
- servers: current.servers.map((server) => ({
- ...server,
- childRouteHints: [{
- id: "child_1",
- name: "private title",
- type: "thread",
- parentChannelId: "ch_old",
- parentMessageId: "message_1",
- }],
- })),
- }))
-
capturedOnMessage!({
type: "community:channel.delete",
serverId: "srv_1",
channelId: "ch_old",
} satisfies CommunityChannelDelete)
- const snapshot = capturedQueryClient.getQueryData<{
- servers: Array<{ channels: unknown[]; childRouteHints: unknown[] }>
- }>(communityKeys.structuralSnapshot())
- expect(snapshot?.servers[0]?.channels).toEqual([])
- expect(snapshot?.servers[0]?.childRouteHints).toEqual([])
expect(useCommunityStore.getState().typingByScope.has("ch:ch_old")).toBe(false)
})
@@ -473,7 +275,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
capturedQueryClient.setQueryData(communityKeys.pins("ch_dead"), { pins: [{ id: "p" }] })
capturedQueryClient.setQueryData(communityKeys.threads("ch_dead"), { threads: [{ id: "t" }] })
const sidebarKey = communityKeys.forumSidebarThreads("srv_1")
- capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture(["ch_dead"]))
+ seedCanonicalForumSidebar("srv_1", ["ch_dead"])
const event: CommunityChannelDelete = {
type: "community:channel.delete",
@@ -485,7 +287,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("ch_dead"))).toBeUndefined()
expect(capturedQueryClient.getQueryData(communityKeys.pins("ch_dead"))).toBeUndefined()
expect(capturedQueryClient.getQueryData(communityKeys.threads("ch_dead"))).toBeUndefined()
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads).toEqual([])
+ expect(canonicalForumSidebar("srv_1").threads).toEqual([])
})
it("evicts the deleted row while an active server-tree refetch is pending", async () => {
@@ -586,10 +388,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
}
capturedQueryClient.setQueryData(communityKeys.forumFeed("forum_1", "bug"), forumFeed)
capturedQueryClient.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug"] })
- capturedQueryClient.setQueryData(
- communityKeys.forumSidebarThreads("srv_1"),
- forumSidebarFixture(["post_1", "post_keep"]),
- )
+ seedCanonicalForumSidebar("srv_1", ["post_1", "post_keep"])
capturedQueryClient.setQueryData(
communityKeys.forumOpenerHint("srv_1", "opener-post_1"),
{ id: "opener-post_1", content: "Post" },
@@ -624,12 +423,8 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
?.pages[0].messages.map((message) => message.id)).toEqual(["opener-keep"])
expect(capturedQueryClient.getQueryData<typeof forumFeed>(communityKeys.forumFeed("forum_1", "bug"))
?.pages[0].threads.map((thread) => thread.id)).toEqual(["post_keep"])
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(
- communityKeys.forumSidebarThreads("srv_1"),
- )?.threads.map((thread) => thread.id)).toEqual(["post_keep"])
- expect(capturedQueryClient.getQueryData(
- communityKeys.forumOpenerHint("srv_1", "opener-post_1"),
- )).toBeUndefined()
+ expect(canonicalForumSidebar("srv_1").threads.map((thread) => thread.id))
+ .toEqual(["post_keep"])
expect(getMessageOverlay({ kind: "channel", id: "forum_1", serverId: "srv_1" })
.liveById.has("opener-post_1")).toBe(false)
expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
@@ -859,29 +654,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
const baseKey = communityKeys.forumSidebarThreads("s1")
- const retainedKey = communityKeys.forumSidebarRetained("s1", "post_1")
- const metaKey = communityKeys.channelMeta("s1", "post_1")
- const hintKey = communityKeys.forumOpenerHint("s1", "opener-post_1")
- const fallbackKey = communityKeys.forumSidebarUnreadFallbacks("s1")
- capturedQueryClient.setQueryData(communityKeys.server("s1"), {
- id: "s1",
- categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],
- })
- const base = forumSidebarFixture(["post_1", "post_2"])
- capturedQueryClient.setQueryData(baseKey, base)
- capturedQueryClient.setQueryData(retainedKey, base.threads[0])
- capturedQueryClient.setQueryData(metaKey, {
- id: "post_1",
- parentChannelId: "forum_1",
- parentMessageId: "opener-post_1",
- })
- capturedQueryClient.setQueryData(hintKey, {
- id: "opener-post_1",
- content: "Post one",
- })
- capturedQueryClient.setQueryData(fallbackKey, {
- forum_1: { baseUnread: false, childIds: ["post_1"] },
- })
+ seedCanonicalForumSidebar("s1", ["post_1", "post_2"])
useCommunityStore.getState().setCurrentChannelId("post_1")
useCommunityStore.getState().setCurrentChannelMeta({
name: "Post one",
@@ -896,24 +669,15 @@ describe("useCommunityWs — child_create patches parent thread badge with count
changes: { tags: ["bug", "archived"] },
} satisfies CommunityChildChannelUpdate)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)
- ?.threads.map(({ id }) => id)).toEqual(["post_2"])
- expect(capturedQueryClient.getQueryState(retainedKey)).toBeUndefined()
- expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })
- expect(capturedQueryClient.getQueryData(hintKey)).toEqual({
- id: "opener-post_1",
- content: "Post one",
- })
- expect(capturedQueryClient.getQueryData(fallbackKey)).toEqual({
- forum_1: { baseUnread: false, childIds: ["post_1"] },
- })
+ expect(canonicalForumSidebar("s1").threads.map(({ id }) => id)).toEqual(["post_2"])
+ expect(getCanonicalCommunityChannels(capturedQueryClient)
+ .find(({ id }) => id === "post_1")).toMatchObject({ archived: false })
+ expect(hasCanonicalChannelAccess("post_1", "u_me")).toBe(true)
+ expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(false)
expect(useCommunityStore.getState().currentChannelId).toBe("post_1")
expect(useCommunityStore.getState().currentChannelMeta).toMatchObject({
parentMessageId: "opener-post_1",
})
- await vi.waitFor(() => {
- expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)
- })
})
it.each([
@@ -923,25 +687,8 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
const baseKey = communityKeys.forumSidebarThreads("s1")
- const retainedKey = communityKeys.forumSidebarRetained("s1", "post_1")
- const metaKey = communityKeys.channelMeta("s1", "post_1")
- const hintKey = communityKeys.forumOpenerHint("s1", "opener-post_1")
- capturedQueryClient.setQueryData(communityKeys.server("s1"), {
- id: "s1",
- categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],
- })
- const base = forumSidebarFixture(["post_1", "post_2"])
- capturedQueryClient.setQueryData(baseKey, base)
- capturedQueryClient.setQueryData(retainedKey, base.threads[0])
- capturedQueryClient.setQueryData(metaKey, {
- id: "post_1",
- parentChannelId: "forum_1",
- parentMessageId: "opener-post_1",
- })
- capturedQueryClient.setQueryData(hintKey, {
- id: "opener-post_1",
- content: "Post one",
- })
+ seedCanonicalForumSidebar("s1", ["post_1", "post_2"])
+ const before = canonicalForumSidebar("s1").threads
useCommunityStore.getState().setCurrentChannelId("post_1")
useCommunityStore.getState().setCurrentChannelMeta({
name: "Post one",
@@ -956,17 +703,9 @@ describe("useCommunityWs — child_create patches parent thread badge with count
changes: { tags },
} satisfies CommunityChildChannelUpdate)
- expect(capturedQueryClient.getQueryData(baseKey)).toEqual(base)
- expect(capturedQueryClient.getQueryData(retainedKey)).toEqual(base.threads[0])
- expect(capturedQueryClient.getQueryData(metaKey)).toMatchObject({ id: "post_1" })
- expect(capturedQueryClient.getQueryData(hintKey)).toEqual({
- id: "opener-post_1",
- content: "Post one",
- })
+ expect(canonicalForumSidebar("s1").threads).toEqual(before)
expect(useCommunityStore.getState().currentChannelId).toBe("post_1")
- await vi.waitFor(() => {
- expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)
- })
+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated ?? false).toBe(false)
})
it("child_update rename patches focused child metadata and its cached channel meta", async () => {
@@ -1002,11 +741,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
const key = communityKeys.forumSidebarThreads("s1")
- capturedQueryClient.setQueryData(communityKeys.server("s1"), {
- id: "s1",
- categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],
- })
- capturedQueryClient.setQueryData(key, forumSidebarFixture(["ch_thread"]))
+ seedCanonicalForumSidebar("s1", ["ch_thread"])
useCommunityStore.getState().setCurrentChannelId("ch_thread")
useCommunityStore.getState().setCurrentChannelMeta({
name: "Private title",
@@ -1020,7 +755,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
channelId: "ch_thread",
changes: { archived: true, tags: ["bug"] },
} satisfies CommunityChildChannelUpdate)
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+ expect(canonicalForumSidebar("s1").threads).toEqual([])
expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
capturedOnMessage!({
@@ -1029,9 +764,26 @@ describe("useCommunityWs — child_create patches parent thread badge with count
channelId: "ch_thread",
changes: { archived: false },
} satisfies CommunityChildChannelUpdate)
- await vi.waitFor(() => {
- expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
- })
+ expect(canonicalForumSidebar("s1").threads.map(({ id }) => id)).toEqual(["ch_thread"])
+ })
+
+ it("absorbs a failed unarchive ownership probe", async () => {
+ await mountHook()
+ seedCanonicalForumSidebar("s1", [])
+ getCommunityApiFetchMock().mockRejectedValueOnce(new Error("offline"))
+
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "forum_1",
+ channelId: "missing-post",
+ changes: { archived: false },
+ } satisfies CommunityChildChannelUpdate)
+
+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
+ expect.stringContaining("retainId=missing-post"),
+ expect.anything(),
+ ))
+ await Promise.resolve()
})
it("clears active child metadata synchronously on channel.delete", async () => {
@@ -1230,7 +982,6 @@ describe("useCommunityWs — server.update icon removal", () => {
describe("useCommunityWs — server.delete resets store when focused server dies", () => {
it("fences cached raw Inbox rows from the deleted server", async () => {
await mountHook({ viewerUserId: "u_me" })
- seedStructuralSnapshot("srv_doomed")
const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")
unreadProjection.recordArrival({ channelId: "ch_dead", serverId: "srv_doomed", seq: 1 })
@@ -1240,9 +991,6 @@ describe("useCommunityWs — server.delete resets store when focused server dies
} satisfies CommunityServerDelete)
expect(unreadProjection.projectUnread("inbox-unreads", "ch_dead", true, 1)).toBe(false)
- expect(capturedQueryClient.getQueryData<{
- serverOrder: string[]
- }>(communityKeys.structuralSnapshot())?.serverOrder).toEqual([])
})
it("clears currentServerId + currentChannelId if the deleted server is currently focused", async () => {
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
index 23ecf90e2..68f2b7315 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
@@ -22,10 +22,10 @@ import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/mes
import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
import {
grantForumSidebarChild,
+ hasForumSidebarOwnershipEvidence,
isForumSidebarParent,
patchForumSidebarActivityExact,
reconcileForumSidebarArchiveTag,
- removeForumSidebarThreadExact,
removeForumSidebarUnreadChild,
} from "@/hooks/community/use-forum-sidebar-threads"
import {
@@ -49,22 +49,6 @@ import {
} from "./invalidation-projections"
import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { projectForumFeedWsTags } from "@/hooks/community/forum-feed-tag-transition"
-import {
- updateStructuralSnapshot,
- type StructuralSnapshotV1,
-} from "@/lib/community/structural-snapshot"
-
-function structuralServerIdForParent(
- queryClient: StructureTreeEventContext["queryClient"],
- parentChannelId: string,
-): string | null {
- const snapshot = queryClient.getQueryData<StructuralSnapshotV1>(
- communityKeys.structuralSnapshot(),
- )
- return snapshot?.servers.find((server) =>
- server.channels.some((channel) => channel.id === parentChannelId),
- )?.id ?? null
-}
export function handleChildChannelCreate(
event: CommunityChildChannelCreate,
@@ -137,20 +121,6 @@ export function handleChildChannelCreate(
if (event.parentMessageId && !openerCached) {
invalidateChannelMessages(projection, event.parentChannelId)
}
- const structuralServerId = structuralServerIdForParent(queryClient, event.parentChannelId)
- if (structuralServerId && event.parentMessageId) {
- updateStructuralSnapshot(queryClient, {
- type: "upsertChildHint",
- serverId: structuralServerId,
- child: {
- id: event.channel.id,
- name: event.channel.name,
- type: "thread",
- parentChannelId: event.parentChannelId,
- parentMessageId: event.parentMessageId,
- },
- })
- }
}
export function handleChildChannelUpdate(
@@ -180,7 +150,6 @@ export function handleChildChannelUpdate(
})
}
const sidebarServerId = useCommunityStore.getState().currentServerId
- const structuralServerId = structuralServerIdForParent(queryClient, event.parentChannelId)
if (changes.name !== undefined && sidebarServerId) {
queryClient.setQueryData<Record<string, unknown> | undefined>(
communityKeys.channelMeta(sidebarServerId, event.channelId),
@@ -199,12 +168,21 @@ export function handleChildChannelUpdate(
sidebarServerId &&
isForumSidebarParent(queryClient, sidebarServerId, event.parentChannelId)
) {
- if (changes.archived === true) {
+ if (changes.archived === true || changes.archived === false) {
removeForumSidebarUnreadChild(queryClient, sidebarServerId, event.channelId)
- removeForumSidebarThreadExact(queryClient, sidebarServerId, event.channelId)
- } else if (changes.archived === false) {
- void grantForumSidebarChild(queryClient, sidebarServerId, event.channelId)
- .catch(() => undefined)
+ void reconcileForumSidebarArchiveTag(
+ queryClient,
+ sidebarServerId,
+ event.channelId,
+ changes.archived,
+ )
+ if (
+ changes.archived === false
+ && !hasForumSidebarOwnershipEvidence(queryClient, sidebarServerId, event.channelId)
+ ) {
+ void grantForumSidebarChild(queryClient, sidebarServerId, event.channelId)
+ .catch(() => undefined)
+ }
} else if (changes.tags !== undefined) {
void reconcileForumSidebarArchiveTag(
queryClient,
@@ -290,20 +268,6 @@ export function handleChildChannelUpdate(
}
}
}
- if (structuralServerId) {
- updateStructuralSnapshot(queryClient, changes.archived === true
- ? {
- type: "removeChildHint",
- serverId: structuralServerId,
- channelId: event.channelId,
- }
- : {
- type: "patchChildHint",
- serverId: structuralServerId,
- channelId: event.channelId,
- ...(changes.name !== undefined ? { name: changes.name } : {}),
- })
- }
}
export function handleServerUpdate(
@@ -348,14 +312,6 @@ export function handleServerUpdate(
}
: prev,
)
- updateStructuralSnapshot(queryClient, {
- type: "patchServer",
- serverId: event.serverId,
- changes: {
- ...(event.changes.name !== undefined ? { name: event.changes.name } : {}),
- ...(event.changes.icon !== undefined ? { icon: event.changes.icon } : {}),
- },
- })
}
export function handleServerDelete(
@@ -428,43 +384,6 @@ export function handleChannelEvent(
invalidateChannelMessages(projection, event.parentChannelId)
invalidateThreads(projection, event.parentChannelId)
}
- } else if (event.type === "community:channel.create") {
- if (event.channel.type === "text" || event.channel.type === "forum") {
- updateStructuralSnapshot(queryClient, {
- type: "upsertChannel",
- serverId: event.serverId,
- channel: {
- id: event.channel.id,
- name: event.channel.name,
- type: event.channel.type,
- categoryId: event.channel.categoryId ?? null,
- },
- position: event.channel.position,
- })
- }
- } else if (event.type === "community:channel.update") {
- updateStructuralSnapshot(queryClient, {
- type: "patchChannel",
- serverId: event.serverId,
- channelId: event.channelId,
- changes: {
- ...(event.changes.name !== undefined ? { name: event.changes.name } : {}),
- ...(event.changes.type === "text" || event.changes.type === "forum"
- ? { type: event.changes.type }
- : {}),
- ...(event.changes.categoryId !== undefined
- ? { categoryId: event.changes.categoryId }
- : {}),
- },
- })
- } else {
- updateStructuralSnapshot(queryClient, {
- type: "reorderChannels",
- serverId: event.serverId,
- channelIds: [...event.channels]
- .sort((left, right) => left.position - right.position)
- .map((channel) => channel.id),
- })
}
invalidateServerDetail(projection, event.serverId)
}
@@ -477,45 +396,8 @@ type CategoryEvent =
export function handleCategoryEvent(
event: CategoryEvent,
- { queryClient, projection }: StructureTreeEventContext,
+ { projection }: StructureTreeEventContext,
) {
- if (event.type === "community:category.create") {
- updateStructuralSnapshot(queryClient, {
- type: "upsertCategory",
- serverId: event.serverId,
- category: {
- id: event.category.id,
- name: event.category.name,
- private: event.category.private,
- },
- position: event.category.position,
- })
- } else if (event.type === "community:category.update") {
- updateStructuralSnapshot(queryClient, {
- type: "patchCategory",
- serverId: event.serverId,
- categoryId: event.categoryId,
- changes: {
- ...(event.changes.name !== undefined ? { name: event.changes.name } : {}),
- ...(event.changes.private !== undefined ? { private: event.changes.private } : {}),
- },
- position: event.changes.position,
- })
- } else if (event.type === "community:category.delete") {
- updateStructuralSnapshot(queryClient, {
- type: "removeCategory",
- serverId: event.serverId,
- categoryId: event.categoryId,
- })
- } else {
- updateStructuralSnapshot(queryClient, {
- type: "reorderCategories",
- serverId: event.serverId,
- categoryIds: [...event.categories]
- .sort((left, right) => left.position - right.position)
- .map((category) => category.id),
- })
- }
invalidateChannelRefDirectory(projection)
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 0e49a5841..2ed73c62a 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -3,6 +3,19 @@ import type { CommunityMessageCreate } from "@alook/shared"
import { vi } from "vitest"
import type { UseUserWsOptions, UserWsConnectionPhase } from "@/lib/use-user-ws"
import { useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import {
+ captureCommunityLiveSnapshotToken,
+ ingestServerDetail,
+ ingestServers,
+ publishCommunityChannelMetadata,
+ publishCommunityForumSidebar,
+} from "@/lib/community-db/sync"
+import { getForumSidebarBase } from "@/hooks/community/use-forum-sidebar-threads"
const communityApiFetch = vi.hoisted(() => vi.fn(async (...args: unknown[]) => {
const url = args[0]
@@ -61,6 +74,8 @@ export function flushEffects() {
}
export let capturedQueryClient: QueryClient
+let canonicalRegistry: CommunityDbRegistry | null = null
+let unregisterCanonicalRegistry: (() => void) | null = null
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
return {
@@ -159,6 +174,9 @@ async function resetStore() {
export async function resetCommunityWsHarness() {
resetHarnessState()
+ canonicalRegistry = createCommunityDbRegistry(capturedQueryClient, "u_me")
+ await canonicalRegistry.preload()
+ unregisterCanonicalRegistry = registerCommunityDbRegistry(canonicalRegistry)
await resetStore()
}
@@ -169,6 +187,10 @@ export async function cleanupCommunityWsHarness() {
vi.useRealTimers()
vi.restoreAllMocks()
vi.clearAllMocks()
+ unregisterCanonicalRegistry?.()
+ unregisterCanonicalRegistry = null
+ await canonicalRegistry?.cleanup()
+ canonicalRegistry = null
resetHarnessState()
}
@@ -228,3 +250,111 @@ export function forumSidebarFixture(ids = ["post_1"]) {
})),
}
}
+
+export function seedCanonicalForumSidebar(serverId: string, ids = ["post_1"]) {
+ if (!canonicalRegistry) throw new Error("canonical test registry is not active")
+ ingestServers(canonicalRegistry, { servers: [{
+ id: serverId,
+ name: "Server",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ }] })
+ ingestServerDetail(canonicalRegistry, {
+ id: serverId,
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: `${serverId}-forums`,
+ name: "Forums",
+ channels: [{
+ id: "forum_1",
+ name: "Forum",
+ active: false,
+ unread: false,
+ type: "forum",
+ }],
+ }],
+ })
+ publishCommunityForumSidebar(capturedQueryClient, {
+ serverId,
+ channels: forumSidebarFixture(ids).channels.map((channel) => ({
+ ...channel,
+ serverId,
+ type: "thread",
+ creatorId: "viewer",
+ archived: false,
+ lastMessageAt: channel.activityAt,
+ })),
+ openers: forumSidebarFixture(ids).included.parentMessages.map((message) => ({
+ ...message,
+ channelId: "forum_1",
+ type: "chat" as const,
+ })),
+ proof: {
+ token: captureCommunityLiveSnapshotToken(capturedQueryClient),
+ signal: undefined,
+ },
+ })
+}
+
+export function canonicalForumSidebar(serverId: string) {
+ return getForumSidebarBase(capturedQueryClient, serverId)
+}
+
+export function seedCanonicalThread(
+ serverId: string,
+ parentId: string,
+ parentType: "text" | "forum",
+ childId: string,
+) {
+ if (!canonicalRegistry) throw new Error("canonical test registry is not active")
+ ingestServers(canonicalRegistry, { servers: [{
+ id: serverId, name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "u_me",
+ }] })
+ ingestServerDetail(canonicalRegistry, {
+ id: serverId, name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "u_me", categories: [{
+ id: `${serverId}-category`, name: "Category", channels: [{
+ id: parentId, name: "Parent", active: false, unread: false, type: parentType,
+ }],
+ }],
+ })
+ publishCommunityChannelMetadata(capturedQueryClient, {
+ metadata: {
+ id: childId,
+ serverId,
+ name: "Child",
+ type: "thread",
+ parentChannelId: parentId,
+ parentMessageId: `${childId}-opener`,
+ creatorId: "u_me",
+ archived: false,
+ lastMessageAt: "2026-08-01T00:00:00.000Z",
+ },
+ proof: {
+ token: captureCommunityLiveSnapshotToken(capturedQueryClient),
+ signal: undefined,
+ },
+ })
+}
+
+export function hasCanonicalChannel(channelId: string) {
+ return canonicalRegistry?.collections.channels.has(channelId) ?? false
+}
+
+export function hasCanonicalChannelAccess(channelId: string, userId: string) {
+ return canonicalRegistry?.collections.channelMemberships.has(`${channelId}:${userId}:access`)
+ ?? false
+}
+
+export function hasCanonicalChannelNotify(channelId: string, userId: string) {
+ return canonicalRegistry?.collections.channelMemberships.has(`${channelId}:${userId}:notify`)
+ ?? false
+}
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
index 395ae2671..c2369992f 100644
--- a/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
+++ b/src/web/src/hooks/community/forum-opener-title-reconciliation.test.ts
@@ -1,7 +1,18 @@
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import { reconcileForumOpenerTitle } from "./forum-opener-title-reconciliation"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import {
+ captureCommunityLiveSnapshotToken,
+ getCanonicalCommunityMessages,
+ publishCommunityForumSidebar,
+} from "@/lib/community-db/sync"
+import { getForumSidebarBase } from "./use-forum-sidebar-threads"
const identity = {
serverId: "server_1",
@@ -12,12 +23,35 @@ const identity = {
}
let queryClient: QueryClient
+let registry: CommunityDbRegistry
+let unregister: () => void
-beforeEach(() => {
+beforeEach(async () => {
queryClient = new QueryClient()
+ registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ unregister = registerCommunityDbRegistry(registry)
+})
+
+afterEach(async () => {
+ unregister()
+ await registry.cleanup()
})
function seedCanonicalCaches() {
+ publishCommunityForumSidebar(queryClient, {
+ serverId: "server_1",
+ channels: [{
+ id: "post_1", name: "Post", parentChannelId: "forum_1",
+ parentMessageId: "opener_1", activityAt: "2026-09-26T00:00:00.000Z",
+ unread: false, type: "thread",
+ }],
+ openers: [{ id: "opener_1", channelId: "forum_1", content: "Old title", type: "chat" }],
+ proof: {
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
+ })
queryClient.setQueryData(communityKeys.message("opener_1"), {
id: "opener_1", type: "chat", content: "Old title",
})
@@ -113,8 +147,9 @@ describe("reconcileForumOpenerTitle", () => {
expect(queryClient.getQueryData<any>(communityKeys.inboxUnreads()).servers[0].channels[0].children[0].channelName).toBe("Full new title")
expect(queryClient.getQueryData<any>(communityKeys.threads("forum_1")).threads[0].name).toBe("Full new title")
expect(queryClient.getQueryData<any>(feedKey).pages[0].included.parentMessages[0].content).toBe("Full new title")
- expect(queryClient.getQueryData<any>(communityKeys.forumSidebarThreads("server_1")).threads[0].title).toBe("Full new title")
- expect(queryClient.getQueryData<any>(communityKeys.forumOpenerHint("server_1", "opener_1")).content).toBe("Full new title")
+ expect(getForumSidebarBase(queryClient, "server_1").threads[0]?.title).toBe("Full new title")
+ expect(getCanonicalCommunityMessages(queryClient)
+ .find(({ id }) => id === "opener_1")?.content).toBe("Full new title")
})
it("is idempotent and leaves title caches unchanged for every mismatched identity", async () => {
@@ -132,7 +167,7 @@ describe("reconcileForumOpenerTitle", () => {
expect(queryClient.getQueryData<any>(communityKeys.inboxUnreads()).servers[0].channels[0].children[0].channelName).toBe("Old title")
expect(queryClient.getQueryData<any>(communityKeys.threads("forum_1")).threads[0].name).toBe("Old title")
- expect(queryClient.getQueryData<any>(communityKeys.forumSidebarThreads("server_1")).threads[0].title).toBe("Old title")
+ expect(getForumSidebarBase(queryClient, "server_1").threads[0]?.title).toBe("Old title")
})
it("never rewrites a text-thread name", async () => {
diff --git a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
index 15dc13bfe..47af67c01 100644
--- a/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
+++ b/src/web/src/hooks/community/forum-opener-title-reconciliation.ts
@@ -9,9 +9,6 @@ import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"
import {
getForumSidebarBase,
patchForumSidebarTitleExact,
- type ChildChannelMeta,
- type ForumOpenerHint,
- type ForumSidebarThread,
} from "@/hooks/community/use-forum-sidebar-threads"
import { patchMessageContentInCache } from "@/hooks/community/community-ws/cache"
import { useMessageStreamStore } from "@/stores/community/message-stream"
@@ -80,24 +77,10 @@ function patchFeed(
}
function sidebarIdentityMatches(queryClient: QueryClient, identity: ForumOpenerTitleIdentity) {
- const meta = queryClient.getQueryData<ChildChannelMeta>(
- communityKeys.channelMeta(identity.serverId, identity.childChannelId),
- )
- if (meta) {
- return meta.parentChannelId === identity.forumChannelId &&
- meta.parentMessageId === identity.openerMessageId
- }
const base = getForumSidebarBase(queryClient, identity.serverId)?.threads
.find((thread) => thread.id === identity.childChannelId)
- if (base) {
- return base.parentChannelId === identity.forumChannelId &&
- base.parentMessageId === identity.openerMessageId
- }
- const retained = queryClient.getQueryData<ForumSidebarThread | null>(
- communityKeys.forumSidebarRetained(identity.serverId, identity.childChannelId),
- )
- return !!retained && retained.parentChannelId === identity.forumChannelId &&
- retained.parentMessageId === identity.openerMessageId
+ return !!base && base.parentChannelId === identity.forumChannelId &&
+ base.parentMessageId === identity.openerMessageId
}
export async function reconcileForumOpenerTitle(
@@ -191,13 +174,6 @@ export async function reconcileForumOpenerTitle(
identity.content,
)
}
- queryClient.setQueryData<ForumOpenerHint | undefined>(
- communityKeys.forumOpenerHint(identity.serverId, identity.openerMessageId),
- (hint) => hint?.id === identity.openerMessageId
- ? { ...hint, content: identity.content }
- : hint,
- )
-
const streamStore = useMessageStreamStore.getState()
for (const entry of streamStore.entries.values()) {
if (
diff --git a/src/web/src/hooks/community/inbox-read-reservation.ts b/src/web/src/hooks/community/inbox-read-reservation.ts
index 3d83061d2..1cb7eafe7 100644
--- a/src/web/src/hooks/community/inbox-read-reservation.ts
+++ b/src/web/src/hooks/community/inbox-read-reservation.ts
@@ -3,6 +3,18 @@
import { communityKeys } from "@/lib/query-keys"
import type { Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
import type { QueryClient } from "@tanstack/react-query"
+import {
+ getCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import {
+ clearAttentionScopeOptimistically,
+ commitAttentionScopeOptimisticSnapshot,
+ hasAttentionScopeOptimisticFence,
+ restoreAttentionScopeOptimisticSnapshot,
+ type AttentionScopeOptimisticSnapshot,
+} from "@/lib/community-db/sync"
+import { reconcileAccountAttention } from "./use-account-attention"
type InboxChild = {
channelId: string
@@ -135,6 +147,7 @@ type FocusedCandidate = {
epoch: number
candidate: InboxReadCandidate
generation: number | null
+ attentionOptimistic: CanonicalAttentionOptimistic | null
}
type ResponsePermit = {
@@ -170,6 +183,12 @@ type ProjectionTicketState = {
active: boolean
generation: number | null
onReceipt: (receipt: InboxProjectionTerminalReceipt) => void
+ attentionOptimistic: CanonicalAttentionOptimistic | null
+}
+
+type CanonicalAttentionOptimistic = {
+ registry: CommunityDbRegistry
+ snapshot: AttentionScopeOptimisticSnapshot
}
type ProjectionTerminalState = {
@@ -411,9 +430,76 @@ function deliverProjectionTerminal(
terminal: InboxProjectionTerminalReceipt["terminal"],
) {
if (!ticket.active || !state.projectionTickets.delete(ticket.ticket.token)) return
+ settleProjectionAttention(ticket, terminal === "success" || terminal === "deferred")
ticket.onReceipt(freezeProjectionReceipt(state, ticket, terminal))
}
+function projectionAttentionTarget(target: InboxRowTarget) {
+ if (target.kind === "mention" || target.reservedThroughSeq === undefined) return null
+ return {
+ scopeId: target.kind === "thread" ? target.childChannelId : target.channelId,
+ targetSeq: target.reservedThroughSeq,
+ }
+}
+
+function beginProjectionAttention(ticket: ProjectionTicketState) {
+ if (ticket.attentionOptimistic) return
+ const target = projectionAttentionTarget(ticket.target)
+ if (!target) return
+ const registry = getCommunityDbRegistry(ticket.ticket.queryClient)
+ if (
+ !registry
+ || hasAttentionScopeOptimisticFence(
+ ticket.ticket.queryClient,
+ target.scopeId,
+ target.targetSeq,
+ )
+ ) return
+ ticket.attentionOptimistic = {
+ registry,
+ snapshot: clearAttentionScopeOptimistically(
+ registry,
+ target.scopeId,
+ target.targetSeq,
+ ),
+ }
+}
+
+function settleProjectionAttention(ticket: ProjectionTicketState, committed: boolean) {
+ const optimistic = ticket.attentionOptimistic
+ if (!optimistic) return
+ ticket.attentionOptimistic = null
+ settleCanonicalAttention(ticket.ticket.queryClient, optimistic, committed)
+}
+
+function settleCanonicalAttention(
+ queryClient: QueryClient,
+ optimistic: CanonicalAttentionOptimistic,
+ committed: boolean,
+) {
+ if (committed) {
+ commitAttentionScopeOptimisticSnapshot(optimistic.registry, optimistic.snapshot)
+ return
+ }
+ if (!restoreAttentionScopeOptimisticSnapshot(optimistic.registry, optimistic.snapshot)) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry === optimistic.registry) {
+ void reconcileAccountAttention(registry).catch(() => undefined)
+ }
+ }
+}
+
+function settleFocusedAttention(
+ queryClient: QueryClient,
+ focused: FocusedCandidate | null,
+ committed: boolean,
+) {
+ const optimistic = focused?.attentionOptimistic
+ if (!optimistic) return
+ focused.attentionOptimistic = null
+ settleCanonicalAttention(queryClient, optimistic, committed)
+}
+
function bindProjectionTickets(
state: ManagerState,
candidate: InboxReadCandidate,
@@ -657,6 +743,7 @@ export function registerInboxProjectionTicket(
active: false,
generation: null,
onReceipt,
+ attentionOptimistic: null,
}
state.projectionTickets.set(ticket.token, ticketState)
const focused = state.focusedCandidate
@@ -676,6 +763,7 @@ export function activateInboxProjectionTicket(ticket: InboxProjectionTicket) {
const current = state?.projectionTickets.get(ticket.token)
if (!state || !current || current.ticket.epoch !== ticket.epoch) return false
current.active = true
+ beginProjectionAttention(current)
const terminal = current.generation === null
? null
: state.projectionTerminals.get(current.generation)?.terminal ?? null
@@ -685,7 +773,10 @@ export function activateInboxProjectionTicket(ticket: InboxProjectionTicket) {
export function cancelInboxProjectionTicket(ticket: InboxProjectionTicket) {
const state = managers.get(ticket.queryClient)
- return state?.projectionTickets.delete(ticket.token) ?? false
+ const current = state?.projectionTickets.get(ticket.token)
+ if (!state || !current || !state.projectionTickets.delete(ticket.token)) return false
+ settleProjectionAttention(current, false)
+ return true
}
export function publishInboxProjectionGenerationTerminal(
@@ -713,7 +804,10 @@ export function registerInboxReadReservationSurface(
}
state.leases.set(token, { lease, onCandidate })
state.latestToken = token
- if (state.focusedCandidate?.epoch !== lease.epoch) state.focusedCandidate = null
+ if (state.focusedCandidate?.epoch !== lease.epoch) {
+ settleFocusedAttention(queryClient, state.focusedCandidate, false)
+ state.focusedCandidate = null
+ }
reclassifyHeld(state)
return lease
}
@@ -725,6 +819,7 @@ export function armInboxReadReservationCandidate(
lastMessageAt: string
openerMessageId?: string
openerSeq?: number
+ seq?: number
},
) {
const state = managerFor(queryClient)
@@ -748,6 +843,7 @@ export function armInboxReadReservationCandidate(
) return false
if (current?.epoch === lease.lease.epoch) {
+ settleFocusedAttention(queryClient, current, false)
for (const held of [...state.held.values()]) {
if (candidateIdentityMatches(current.candidate, held.candidate)) cancelHeld(state, held)
}
@@ -768,6 +864,23 @@ export function armInboxReadReservationCandidate(
epoch: lease.lease.epoch,
candidate,
generation: null,
+ attentionOptimistic: (() => {
+ if (input.seq === undefined) return null
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry || hasAttentionScopeOptimisticFence(
+ queryClient,
+ input.channelId,
+ input.seq,
+ )) return null
+ return {
+ registry,
+ snapshot: clearAttentionScopeOptimistically(
+ registry,
+ input.channelId,
+ input.seq,
+ ),
+ }
+ })(),
}
bindProjectionTickets(state, candidate, null)
notifyActive(state, candidate)
@@ -780,7 +893,10 @@ export function releaseInboxReadReservationSurface(lease: InboxReadReservationLe
state.leases.delete(lease.token)
if (state.latestToken !== lease.token) return
state.latestToken = null
- if (state.focusedCandidate?.epoch === lease.epoch) state.focusedCandidate = null
+ if (state.focusedCandidate?.epoch === lease.epoch) {
+ settleFocusedAttention(lease.queryClient, state.focusedCandidate, false)
+ state.focusedCandidate = null
+ }
if (state.discardedCandidate?.epoch === lease.epoch) state.discardedCandidate = null
if (state.permit?.epoch === lease.epoch) state.permit = null
const epoch = ++state.nextEpoch
@@ -837,6 +953,7 @@ export function takeInboxReadReservationNegative(
&& focused.candidate.channelId === lease.channelId
&& focused.generation === null
) {
+ settleFocusedAttention(lease.queryClient, focused, false)
state.focusedCandidate = null
if (!released) {
state.permit = {
@@ -880,6 +997,7 @@ export async function settleInboxReadReservationGeneration(
fingerprint: null,
}
if (state.focusedCandidate?.generation === generation) {
+ settleFocusedAttention(queryClient, state.focusedCandidate, false)
state.focusedCandidate = null
}
notifyActive(state, null)
@@ -894,12 +1012,16 @@ export async function settleInboxReadReservationGeneration(
}
await Promise.all(matching.map((held) => releaseHeldNegative(state, held)))
publishProjectionTerminal(state, generation, "negative")
- if (state.focusedCandidate?.generation === generation) state.focusedCandidate = null
+ if (state.focusedCandidate?.generation === generation) {
+ settleFocusedAttention(queryClient, state.focusedCandidate, false)
+ state.focusedCandidate = null
+ }
return
}
if (matching.length === 0 && !claimed) {
const focused = state.focusedCandidate
if (committed && focused?.generation === generation) {
+ settleFocusedAttention(queryClient, focused, true)
state.discardedCandidate = {
epoch: focused.epoch,
candidate: focused.candidate,
@@ -917,7 +1039,10 @@ export async function settleInboxReadReservationGeneration(
for (const held of [...state.held.values()]) {
if (held.generation === generation) cancelHeld(state, held)
}
- if (state.focusedCandidate?.generation === generation) state.focusedCandidate = null
+ if (state.focusedCandidate?.generation === generation) {
+ settleFocusedAttention(queryClient, state.focusedCandidate, true)
+ state.focusedCandidate = null
+ }
notifyActive(state, null)
}
@@ -950,6 +1075,7 @@ export async function reserveInboxUnreadsResponse<T extends InboxResponse>(
epoch: armed.epoch,
candidate,
generation: null,
+ attentionOptimistic: armed.attentionOptimistic,
}
state.focusedCandidate = focused
}
@@ -1123,11 +1249,15 @@ export function disposeInboxReadReservation(queryClient: QueryClient) {
state.handoff = null
state.claimedOpeners.clear()
state.routeLeases.clear()
+ settleFocusedAttention(queryClient, state.focusedCandidate, true)
state.focusedCandidate = null
state.discardedCandidate = null
state.permit = null
state.leases.clear()
state.latestToken = null
+ for (const ticket of state.projectionTickets.values()) {
+ settleProjectionAttention(ticket, true)
+ }
state.projectionTickets.clear()
state.projectionCandidates.clear()
state.projectionTerminals.clear()
diff --git a/src/web/src/hooks/community/message-surface-ownership.test.ts b/src/web/src/hooks/community/message-surface-ownership.test.ts
new file mode 100644
index 000000000..58543fb36
--- /dev/null
+++ b/src/web/src/hooks/community/message-surface-ownership.test.ts
@@ -0,0 +1,175 @@
+import { QueryClient } from "@tanstack/react-query"
+import { afterEach, describe, expect, it } from "vitest"
+import type { CommunityWsEvent } from "@alook/shared"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import {
+ materializeCanonicalMessages,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ getCanonicalCommunityMessages,
+ projectCommunityWsEventToDb,
+ publishCommunityEmbeddedMessages,
+} from "@/lib/community-db/sync"
+import type { Msg } from "@/lib/community/models/message"
+import { mapForumFeedPages, type ForumFeedPage } from "./use-forum-feed"
+import { materializeThreadsResponse, type ThreadsResponse } from "./use-channel-panels"
+
+let registry: CommunityDbRegistry | undefined
+let unregister: (() => void) | undefined
+
+afterEach(async () => {
+ unregister?.()
+ unregister = undefined
+ if (registry) await registry.cleanup()
+ registry = undefined
+})
+
+describe("embedded message surface ownership", () => {
+ it("publishes an empty first load once and projects WS edit/delete across every surface", async () => {
+ const queryClient = new QueryClient()
+ registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ unregister = registerCommunityDbRegistry(registry)
+ const transport: Msg = {
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ authorId: "author",
+ authorName: "Author",
+ content: "initial",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }
+ const transportSurfaces = {
+ mentions: [transport],
+ marked: [transport],
+ pins: [transport],
+ context: [transport],
+ }
+ const forumPage: ForumFeedPage = {
+ serverId: "s1",
+ parentType: "forum",
+ threads: [{
+ id: "post-1",
+ name: "transport",
+ creatorId: "author",
+ messageCount: 1,
+ parentMessageId: "m1",
+ lastMessageAt: transport.createdAt!,
+ createdAt: transport.createdAt!,
+ activityAt: transport.createdAt!,
+ }],
+ included: {
+ parentMessages: [{
+ id: "m1",
+ channelId: "c1",
+ seq: 1,
+ createdAt: transport.createdAt,
+ content: "transport",
+ authorId: "author",
+ authorName: "Author",
+ authorImage: null,
+ authorAvatarVersion: 0,
+ }],
+ firstMessages: [],
+ tags: [],
+ participants: [],
+ },
+ hasMore: false,
+ }
+ const threads: ThreadsResponse = {
+ threads: [{
+ id: "post-1",
+ name: "transport",
+ messageCount: 1,
+ lastMessageAt: transport.createdAt!,
+ parent: { authorName: "transport", text: "transport" },
+ openerMessageId: "m1",
+ }],
+ serverId: "s1",
+ parentType: "forum",
+ parentChannelId: "c1",
+ }
+ const canonical = () => new Map(
+ getCanonicalCommunityMessages(queryClient).map((message) => [message.id, message as Msg]),
+ )
+ const projectEverySurface = () => ({
+ rows: Object.fromEntries(Object.entries(transportSurfaces).map(([surface, messages]) => [
+ surface,
+ materializeCanonicalMessages(messages, canonical()).map((message) => message.content),
+ ])),
+ forum: mapForumFeedPages([forumPage], canonical()).map((post) => post.name),
+ threads: materializeThreadsResponse(threads, canonical()).map((thread) => thread.name),
+ })
+
+ expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
+ publishCommunityEmbeddedMessages(queryClient, {
+ entries: [{ channelId: "c1", message: transport }],
+ proof: {
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
+ })
+ expect(projectEverySurface()).toEqual({
+ rows: {
+ mentions: ["initial"], marked: ["initial"], pins: ["initial"], context: ["initial"],
+ },
+ forum: ["initial"],
+ threads: ["initial"],
+ })
+
+ projectCommunityWsEventToDb(queryClient, {
+ type: "community:message.edited",
+ serverId: "s1",
+ channelId: "c1",
+ messageId: "m1",
+ content: "edited",
+ } as CommunityWsEvent)
+ expect(projectEverySurface()).toEqual({
+ rows: {
+ mentions: ["edited"], marked: ["edited"], pins: ["edited"], context: ["edited"],
+ },
+ forum: ["edited"],
+ threads: ["edited"],
+ })
+
+ projectCommunityWsEventToDb(queryClient, {
+ type: "community:channel.delete",
+ serverId: "s1",
+ channelId: "c1",
+ } as CommunityWsEvent)
+ expect(projectEverySurface()).toEqual({
+ rows: { mentions: [], marked: [], pins: [], context: [] },
+ forum: [],
+ threads: [],
+ })
+ })
+
+ it("normalizes legacy embedded messages that omit the transport type", async () => {
+ const queryClient = new QueryClient()
+ registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ unregister = registerCommunityDbRegistry(registry)
+ const transport = {
+ id: "legacy-mention-message",
+ seq: 1,
+ content: "legacy embedded payload",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ } as Msg
+
+ expect(publishCommunityEmbeddedMessages(queryClient, {
+ entries: [{ channelId: "c1", message: transport }],
+ proof: {
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
+ })).toBe("published")
+ expect(getCanonicalCommunityMessages(queryClient)).toEqual([
+ expect.objectContaining({ id: transport.id, type: "chat" }),
+ ])
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.ts
index 503d9d5a2..b520b574c 100644
--- a/src/web/src/hooks/community/mutations/channels.test.ts
+++ b/src/web/src/hooks/community/mutations/channels.test.ts
@@ -67,25 +67,6 @@ beforeEach(() => {
capturedQc = new QueryClient()
})
-function seedStructuralSnapshot() {
- capturedQc.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "u1",
- capturedAt: Date.now(),
- serverOrder: ["s1"],
- folders: [],
- servers: [{
- id: "s1",
- name: "Studio",
- discriminator: "0042",
- icon: null,
- categories: [{ id: "cat_1", name: "Channels" }],
- channels: [{ id: "c1", name: "general", type: "text", categoryId: "cat_1" }],
- childRouteHints: [],
- }],
- })
-}
-
describe("useRenameChannel", () => {
type CachedChannel = { id: string; name: string; active: boolean; unread: boolean }
type CachedCategory = { id: string; name: string; channels: CachedChannel[] }
@@ -153,7 +134,6 @@ describe("useRenameChannel", () => {
it("reconciles both caches to the PATCH response's normalized name", async () => {
seed()
- seedStructuralSnapshot()
apiFetchMock.mockResolvedValueOnce({ id: "c1", name: "General-Chat" })
const mod = await load()
mod.useRenameChannel()
@@ -166,12 +146,6 @@ describe("useRenameChannel", () => {
)
expect(serverChannels().find((channel) => channel.id === "c1")?.name).toBe("General-Chat")
expect(directory()[0].channels.find((channel) => channel.id === "c1")?.name).toBe("General-Chat")
- expect(capturedQc.getQueryData<{
- servers: Array<{ channels: Array<{ id: string; name: string }> }>
- }>(communityKeys.structuralSnapshot())?.servers[0]?.channels[0]).toMatchObject({
- id: "c1",
- name: "General-Chat",
- })
})
it("restores both snapshots on failure without optimistic residue", async () => {
@@ -537,25 +511,10 @@ describe("useDeleteCategory — optimistic removal with rollback", () => {
expect(cats().map((c) => c.id)).toEqual(["cat_1", "cat_2"])
})
- it("prunes the persisted category after a committed delete", async () => {
- seed([{ id: "cat_1", name: "General", channels: [] }])
- seedStructuralSnapshot()
- apiFetchMock.mockResolvedValueOnce(undefined)
- const mod = await load()
- mod.useDeleteCategory()
-
- await runMutation({ serverId: "s1", categoryId: "cat_1" })
-
- const structural = capturedQc.getQueryData<{
- servers: Array<{ categories: Array<{ id: string }> }>
- }>(communityKeys.structuralSnapshot())
- expect(structural?.servers[0]?.categories).toEqual([])
- })
})
-describe("committed category and order projections", () => {
- it("patches the persisted category name after update", async () => {
- seedStructuralSnapshot()
+describe("committed category mutations", () => {
+ it("sends the category name update", async () => {
apiFetchMock.mockResolvedValueOnce(undefined)
const mod = await load()
mod.useUpdateCategory()
@@ -566,47 +525,5 @@ describe("committed category and order projections", () => {
"/api/community/servers/s1/categories/cat_1",
{ method: "PATCH", body: JSON.stringify({ name: "Renamed" }) },
)
- const structural = capturedQc.getQueryData<{
- servers: Array<{ categories: Array<{ name: string }> }>
- }>(communityKeys.structuralSnapshot())
- expect(structural?.servers[0]?.categories[0]?.name).toBe("Renamed")
- })
-
- it("projects committed category and channel order", async () => {
- seedStructuralSnapshot()
- capturedQc.setQueryData<any>(communityKeys.structuralSnapshot(), (current: any) => ({
- ...current,
- servers: current.servers.map((server: any) => ({
- ...server,
- categories: [
- ...server.categories,
- { id: "cat_2", name: "Later", private: false },
- ],
- channels: [
- ...server.channels,
- { id: "c2", name: "later", type: "forum", categoryId: "cat_2" },
- ],
- })),
- }))
- const mod = await load()
-
- apiFetchMock.mockResolvedValueOnce(undefined)
- mod.useReorderCategories()
- await runMutation({ serverId: "s1", categoryIds: ["cat_2", "cat_1"] })
-
- apiFetchMock.mockResolvedValueOnce(undefined)
- mod.useReorderChannels()
- await runMutation({ serverId: "s1", channelIds: ["c2", "c1"] })
-
- const structural = capturedQc.getQueryData<{
- servers: Array<{
- categories: Array<{ id: string }>
- channels: Array<{ id: string }>
- }>
- }>(communityKeys.structuralSnapshot())
- expect(structural?.servers[0]?.categories.map((category) => category.id))
- .toEqual(["cat_2", "cat_1"])
- expect(structural?.servers[0]?.channels.map((channel) => channel.id))
- .toEqual(["c2", "c1"])
})
})
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index 26583a17e..0d309d608 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -8,7 +8,6 @@ import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
import type { ServerDetail } from "@/hooks/community/use-servers"
import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"
import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
-import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"
import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
import { projectChannelScopeEviction } from "@/hooks/community/community-ws/channel-scope-projection"
@@ -135,16 +134,6 @@ export function useCreateChannel() {
})),
}
})
- updateStructuralSnapshot(queryClient, {
- type: "upsertChannel",
- serverId: args.serverId,
- channel: {
- id: data.channel.id,
- name: args.name.trim(),
- type: args.type,
- categoryId: isUncategorizedTarget(args.categoryId) ? null : args.categoryId,
- },
- })
},
onError: (_err, args, ctx) => {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
@@ -250,12 +239,6 @@ export function useRenameChannel() {
queryClient.setQueryData<ChannelRefDirectory>(communityKeys.channelRefDirectory(), (prev) =>
renameDirectoryChannel(prev, args.serverId, args.channelId, data.name),
)
- updateStructuralSnapshot(queryClient, {
- type: "patchChannel",
- serverId: args.serverId,
- channelId: args.channelId,
- changes: { name: data.name },
- })
},
onError: (_err, args, ctx) => {
if (ctx?.serverSnapshot) {
@@ -292,12 +275,6 @@ export function useMoveChannel() {
})
},
onSuccess: (_data, args) => {
- updateStructuralSnapshot(queryClient, {
- type: "patchChannel",
- serverId: args.serverId,
- channelId: args.channelId,
- changes: { categoryId: args.categoryId },
- })
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
invalidateChannelRefDirectory(queryClient)
},
@@ -394,15 +371,6 @@ export function useCreateCategory() {
),
}
})
- updateStructuralSnapshot(queryClient, {
- type: "upsertCategory",
- serverId: args.serverId,
- category: {
- id: data.category.id,
- name: args.name.trim(),
- private: args.private === true,
- },
- })
},
onError: (_err, args, ctx) => {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
@@ -431,14 +399,6 @@ export function useUpdateCategory() {
})
},
onSuccess: (_data, args) => {
- if (args.name !== undefined) {
- updateStructuralSnapshot(queryClient, {
- type: "patchCategory",
- serverId: args.serverId,
- categoryId: args.categoryId,
- changes: { name: args.name },
- })
- }
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
invalidateChannelRefDirectory(queryClient)
},
@@ -476,13 +436,6 @@ export function useDeleteCategory() {
onError: (_err, args, ctx) => {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
},
- onSuccess: (_data, args) => {
- updateStructuralSnapshot(queryClient, {
- type: "removeCategory",
- serverId: args.serverId,
- categoryId: args.categoryId,
- })
- },
onSettled: (_data, _err, args) => {
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
invalidateChannelRefDirectory(queryClient)
@@ -502,11 +455,6 @@ export function useReorderCategories() {
})
},
onSuccess: (_data, args) => {
- updateStructuralSnapshot(queryClient, {
- type: "reorderCategories",
- serverId: args.serverId,
- categoryIds: args.categoryIds,
- })
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
invalidateChannelRefDirectory(queryClient)
},
@@ -525,11 +473,6 @@ export function useReorderChannels() {
})
},
onSuccess: (_data, args) => {
- updateStructuralSnapshot(queryClient, {
- type: "reorderChannels",
- serverId: args.serverId,
- channelIds: args.channelIds,
- })
void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
invalidateChannelRefDirectory(queryClient)
},
diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.ts
index 6b66d88a0..c0007c010 100644
--- a/src/web/src/hooks/community/mutations/forum.test.ts
+++ b/src/web/src/hooks/community/mutations/forum.test.ts
@@ -3,7 +3,7 @@
* `useMutation` config is captured and driven through React Query's lifecycle
* order so we can assert the cache patches without a real query client loop.
*/
-import { describe, it, expect, vi, beforeEach } from "vitest"
+import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
@@ -12,6 +12,7 @@ const { clearLastChannelMock } = vi.hoisted(() => ({
}))
vi.mock("@/lib/community/last-channel", () => ({
clearLastChannel: (...args: unknown[]) => clearLastChannelMock(...args),
+ getLastChannel: () => null,
}))
vi.mock("react", () => ({
@@ -35,6 +36,7 @@ type MutConfig<Args> = {
}
let capturedConfig: MutConfig<unknown> | null = null
let capturedQc: QueryClient
+let cleanupRegistry: (() => Promise<void>) | null = null
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
return {
@@ -73,7 +75,16 @@ async function runMutationExpectError<Args>(args: Args) {
async function load() {
vi.resetModules()
- return await import("./forum")
+ const mod = await import("./forum")
+ const collections = await import("@/lib/community-db/collections")
+ const registry = collections.createCommunityDbRegistry(capturedQc, "viewer")
+ await registry.preload()
+ const unregister = collections.registerCommunityDbRegistry(registry)
+ cleanupRegistry = async () => {
+ unregister()
+ await registry.cleanup()
+ }
+ return mod
}
beforeEach(() => {
@@ -83,6 +94,54 @@ beforeEach(() => {
clearLastChannelMock.mockClear()
})
+afterEach(async () => {
+ await cleanupRegistry?.()
+ cleanupRegistry = null
+})
+
+async function seedCanonicalSidebar(ids: string[], archivedId?: string) {
+ const sync = await import("@/lib/community-db/sync")
+ sync.publishCommunityForumSidebar(capturedQc, {
+ serverId: "server_1",
+ channels: ids.map((id) => ({
+ id,
+ name: id,
+ parentChannelId: "forum_1",
+ parentMessageId: `opener_${id}`,
+ activityAt: "2026-08-08T00:00:00.000Z",
+ unread: false,
+ type: "thread",
+ archived: false,
+ })),
+ openers: ids.map((id) => ({
+ id: `opener_${id}`,
+ channelId: "forum_1",
+ content: id,
+ type: "chat" as const,
+ })),
+ proof: {
+ token: sync.captureCommunityLiveSnapshotToken(capturedQc),
+ signal: undefined,
+ },
+ })
+ if (archivedId) {
+ sync.removeCanonicalCommunityChannelMembership(capturedQc, archivedId, "notify")
+ }
+}
+
+async function canonicalSidebarIds() {
+ const { getForumSidebarBase } = await import("../use-forum-sidebar-threads")
+ return getForumSidebarBase(capturedQc, "server_1").threads.map(({ id }) => id)
+}
+
+async function canonicalMemberships(channelId: string) {
+ const { getCanonicalCommunityChannelMemberships } = await import("@/lib/community-db/sync")
+ return getCanonicalCommunityChannelMemberships(capturedQc)
+ .filter((membership) => membership.channelId === channelId)
+ .map((membership) => membership.relation)
+ .sort()
+}
+
describe("useCreateForumThread", () => {
it("POSTs JSON with name + content only when no attachments/mentionType are provided", async () => {
const { useCreateForumThread } = await load()
@@ -367,13 +426,7 @@ describe("useUpdatePostTags", () => {
const { useUpdatePostTags } = await load()
useUpdatePostTags()
const baseKey = communityKeys.forumSidebarThreads("server_1")
- const retainedKey = communityKeys.forumSidebarRetained("server_1", "p2")
- const metaKey = communityKeys.channelMeta("server_1", "p2")
- const hintKey = communityKeys.forumOpenerHint("server_1", "opener_p2")
- capturedQc.setQueryData(baseKey, sidebar(["p1", "p2", "p3"]))
- capturedQc.setQueryData(retainedKey, sidebar(["p2"]).threads[0])
- capturedQc.setQueryData(metaKey, { id: "p2", parentMessageId: "opener_p2" })
- capturedQc.setQueryData(hintKey, { id: "opener_p2", content: "p2" })
+ await seedCanonicalSidebar(["p1", "p2", "p3"])
apiFetchMock.mockResolvedValueOnce({ tags: ["bug", "archived"] })
await runMutation({
@@ -385,23 +438,15 @@ describe("useUpdatePostTags", () => {
tags: ["bug", "archived"],
})
- expect(capturedQc.getQueryData<ReturnType<typeof sidebar>>(baseKey)?.threads.map(({ id }) => id))
- .toEqual(["p1", "p3"])
- expect(capturedQc.getQueryState(retainedKey)).toBeUndefined()
- expect(capturedQc.getQueryData(metaKey)).toEqual({ id: "p2", parentMessageId: "opener_p2" })
- expect(capturedQc.getQueryData(hintKey)).toEqual({ id: "opener_p2", content: "p2" })
- await vi.waitFor(() => {
- expect(capturedQc.getQueryState(baseKey)?.isInvalidated).toBe(true)
- })
+ expect((await canonicalSidebarIds()).sort()).toEqual(["p1", "p3"])
+ expect(await canonicalMemberships("p2")).toEqual(["access"])
})
it("waits for authoritative ranking on unarchive without speculative insertion", async () => {
const { useUpdatePostTags } = await load()
useUpdatePostTags()
const baseKey = communityKeys.forumSidebarThreads("server_1")
- const retainedKey = communityKeys.forumSidebarRetained("server_1", "p2")
- capturedQc.setQueryData(baseKey, sidebar(["p1", "p3"]))
- capturedQc.setQueryData(retainedKey, null)
+ await seedCanonicalSidebar(["p1", "p2", "p3"], "p2")
apiFetchMock.mockResolvedValueOnce({ tags: ["bug"] })
await runMutation({
@@ -412,12 +457,8 @@ describe("useUpdatePostTags", () => {
previousTags: ["archived", "bug"],
tags: ["bug"],
})
- expect(capturedQc.getQueryData<ReturnType<typeof sidebar>>(baseKey)?.threads.map(({ id }) => id))
- .toEqual(["p1", "p3"])
- await vi.waitFor(() => {
- expect(capturedQc.getQueryState(retainedKey)).toBeUndefined()
- expect(capturedQc.getQueryState(baseKey)?.isInvalidated).toBe(true)
- })
+ expect((await canonicalSidebarIds()).sort()).toEqual(["p1", "p2", "p3"])
+ expect(await canonicalMemberships("p2")).toEqual(["access", "notify"])
})
it("uses normalized returned tags and leaves the sidebar neutral without a transition", async () => {
@@ -573,11 +614,7 @@ describe("useDeleteForumThread", () => {
}
capturedQc.setQueryData(communityKeys.forumFeed("forum_1", null), forumFeed)
const sidebarKey = communityKeys.forumSidebarThreads("server_1")
- capturedQc.setQueryData(sidebarKey, {
- channels: [], included: { parentMessages: [] }, serverNow: "2026-08-08T00:00:00.000Z",
- serverClockOffsetMs: 0,
- threads: [{ id: "p2", parentChannelId: "forum_1" }],
- })
+ await seedCanonicalSidebar(["p2"])
apiFetchMock.mockResolvedValueOnce(undefined)
await runMutation({
@@ -600,7 +637,7 @@ describe("useDeleteForumThread", () => {
})
expect(capturedQc.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
expect(capturedQc.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(true)
- expect(capturedQc.getQueryData<{ threads: unknown[] }>(sidebarKey)?.threads).toEqual([])
+ expect(await canonicalSidebarIds()).toEqual([])
})
it("restores exact feed/sidebar/meta snapshots when the DELETE fails", async () => {
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index e63ecba02..47dcb03d0 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -192,10 +192,7 @@ function isForumPostUnitQuery(query: Query, unit: ForumPostUnitIdentity) {
const exactKeys: QueryKey[] = [
communityKeys.server(unit.serverId),
communityKeys.forumSidebarThreads(unit.serverId),
- communityKeys.forumSidebarUnreadFallbacks(unit.serverId),
- communityKeys.forumSidebarRetained(unit.serverId, unit.childChannelId),
communityKeys.channelMeta(unit.serverId, unit.childChannelId),
- communityKeys.forumOpenerHint(unit.serverId, unit.openerMessageId),
communityKeys.message(unit.openerMessageId),
]
return exactKeys.some((candidate) => hashKey(candidate) === hashKey(key)) || [
diff --git a/src/web/src/hooks/community/mutations/friends.test.ts b/src/web/src/hooks/community/mutations/friends.test.ts
index 02ff54d60..cdc5132ba 100644
--- a/src/web/src/hooks/community/mutations/friends.test.ts
+++ b/src/web/src/hooks/community/mutations/friends.test.ts
@@ -1,9 +1,10 @@
/**
* Friend-mutation tests. Same shim pattern as messages.test.ts.
*/
-import { describe, it, expect, vi, beforeEach } from "vitest"
+import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
vi.mock("react", () => ({
useRef: (initial: unknown) => ({ current: initial }),
@@ -26,6 +27,8 @@ type MutConfig<Args, Ctx> = {
}
let capturedConfig: MutConfig<unknown, unknown> | null = null
let capturedQc: QueryClient
+let canonicalRegistry: CommunityDbRegistry | null = null
+let unregisterCanonicalRegistry: (() => void) | null = null
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
return {
@@ -64,6 +67,20 @@ beforeEach(() => {
capturedQc = new QueryClient()
})
+afterEach(async () => {
+ unregisterCanonicalRegistry?.()
+ unregisterCanonicalRegistry = null
+ await canonicalRegistry?.cleanup()
+ canonicalRegistry = null
+})
+
+async function installCanonicalRegistry() {
+ const collections = await import("@/lib/community-db/collections")
+ canonicalRegistry = collections.createCommunityDbRegistry(capturedQc, "u_me")
+ await canonicalRegistry.preload()
+ unregisterCanonicalRegistry = collections.registerCommunityDbRegistry(canonicalRegistry)
+}
+
describe("useSendFriendRequest — invalidates friends on success", () => {
it("triggers invalidateQueries(friends)", async () => {
apiFetchMock.mockResolvedValueOnce(undefined)
@@ -90,6 +107,127 @@ describe("useSendFriendRequest — invalidates friends on success", () => {
})
describe("useAcceptFriendRequest — rollback", () => {
+ it("commits canonical attention removal and reconciles after success", async () => {
+ const mod = await load()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
+ const canonical = {
+ scopes: [],
+ items: [{
+ id: "friend_request:f_1", kind: "friend_request" as const, sourceId: "f_1",
+ scopeId: null, messageId: null, actorUserId: "u_1",
+ createdAt: "2026-09-27T00:00:00.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ }
+ ingestAttentionSnapshot(canonicalRegistry!, canonical)
+ capturedQc.setQueryData(communityKeys.friends(), {
+ friends: [], blocked: [],
+ pending: [{ id: "f_1", userId: "u_1", name: "One", avatar: "1", kind: "incoming" }],
+ })
+ capturedQc.setQueryData(communityKeys.inboxUnreads(), {
+ friendRequests: [{
+ id: "f_1", userId: "u_1", name: "One", avatar: "1",
+ createdAt: "2026-09-27T00:00:00.000Z",
+ }],
+ servers: [],
+ dms: [],
+ })
+ apiFetchMock.mockImplementation(async (path: string) => (
+ path === "/api/community/users/me/attention"
+ ? { ...canonical, items: [] }
+ : undefined
+ ))
+
+ mod.useAcceptFriendRequest()
+ const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>
+ const context = await cfg.onMutate?.({ friendshipId: "f_1" })
+ await cfg.onSuccess?.(undefined, { friendshipId: "f_1" }, context)
+
+ await vi.waitFor(() => {
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/attention",
+ expect.objectContaining({ signal: expect.anything() }),
+ )
+ })
+ })
+
+ it("does not compensate a late error after the same action is terminal", async () => {
+ const mod = await load()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
+ ingestAttentionSnapshot(canonicalRegistry!, {
+ scopes: [],
+ items: [{
+ id: "friend_request:f_1", kind: "friend_request", sourceId: "f_1",
+ scopeId: null, messageId: null, actorUserId: "u_1",
+ createdAt: "2026-09-27T00:00:00.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ })
+ capturedQc.setQueryData(communityKeys.friends(), {
+ friends: [], blocked: [],
+ pending: [{ id: "f_1", userId: "u_1", name: "One", avatar: "1", kind: "incoming" }],
+ })
+
+ mod.useAcceptFriendRequest()
+ const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>
+ const context = await cfg.onMutate?.({ friendshipId: "f_1" })
+ await cfg.onSuccess?.(undefined, { friendshipId: "f_1" }, context)
+ await cfg.onError?.(new Error("late failure"), { friendshipId: "f_1" }, context)
+
+ expect(context).toBeDefined()
+ })
+
+ it("reconciles a failed friend action after an intervening canonical event", async () => {
+ const mod = await load()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot, projectAttentionUnreadBump } = await import(
+ "@/lib/community-db/sync"
+ )
+ const canonical = {
+ scopes: [],
+ items: [{
+ id: "friend_request:f_1", kind: "friend_request" as const, sourceId: "f_1",
+ scopeId: null, messageId: null, actorUserId: "u_1",
+ createdAt: "2026-09-27T00:00:00.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ }
+ ingestAttentionSnapshot(canonicalRegistry!, canonical)
+ capturedQc.setQueryData(communityKeys.friends(), {
+ friends: [], blocked: [],
+ pending: [{ id: "f_1", userId: "u_1", name: "One", avatar: "1", kind: "incoming" }],
+ })
+ apiFetchMock.mockImplementation(async (path: string) => {
+ if (path === "/api/community/users/me/attention") return canonical
+ throw new Error("friend action failed")
+ })
+ mod.useAcceptFriendRequest()
+ const cfg = capturedConfig as MutConfig<{ friendshipId: string }, unknown>
+ const context = await cfg.onMutate?.({ friendshipId: "f_1" })
+ projectAttentionUnreadBump(capturedQc, {
+ type: "community:unread.bump",
+ userId: "u_me",
+ channelId: "other",
+ serverId: "s_1",
+ isMention: false,
+ }, { seq: 2 })
+
+ await cfg.onError?.(new Error("friend action failed"), { friendshipId: "f_1" }, context)
+
+ await vi.waitFor(() => {
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/attention",
+ expect.objectContaining({ signal: expect.anything() }),
+ )
+ expect(canonicalRegistry!.collections.attentionItems.get("friend_request:f_1")).toBeDefined()
+ })
+ })
+
it("restores the pending row when the server rejects", async () => {
capturedQc.setQueryData(communityKeys.friends(), {
friends: [],
diff --git a/src/web/src/hooks/community/mutations/friends.ts b/src/web/src/hooks/community/mutations/friends.ts
index 80c58c676..c4e47e17f 100644
--- a/src/web/src/hooks/community/mutations/friends.ts
+++ b/src/web/src/hooks/community/mutations/friends.ts
@@ -11,6 +11,14 @@ import {
getFriendRequestActionController,
type FriendRequestAction,
} from "@/hooks/community/use-friend-request-action-state"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import {
+ commitAttentionItemsOptimisticSnapshot,
+ removeAttentionItemsOptimistically,
+ restoreAttentionItemsOptimisticSnapshot,
+ type AttentionItemsOptimisticSnapshot,
+} from "@/lib/community-db/sync"
+import { reconcileAccountAttention } from "@/hooks/community/use-account-attention"
/**
* Friend-scoped mutations. All six live on one query key
@@ -52,6 +60,7 @@ type FriendRequestMutationContext = {
friends?: CapturedRow<PendingRequest>
generation: number
inbox?: CapturedRow<InboxFriendRequest>
+ attention?: AttentionItemsOptimisticSnapshot
}
function captureRow<T extends { id: string }>(
@@ -96,6 +105,15 @@ function useFriendRequestMutation(
friends: captureRow(friends?.pending ?? [], friendshipId),
generation,
inbox: captureRow(inbox?.friendRequests ?? [], friendshipId),
+ attention: (() => {
+ const registry = getCommunityDbRegistry(queryClient)
+ return registry
+ ? removeAttentionItemsOptimistically(
+ registry,
+ (item) => item.kind === "friend_request" && item.sourceId === friendshipId,
+ )
+ : undefined
+ })(),
}
queryClient.setQueryData<FriendsResponse | undefined>(friendsKey, (current) =>
current
@@ -114,11 +132,27 @@ function useFriendRequestMutation(
},
onSuccess: async (_data, { friendshipId }, context) => {
if (!context) return
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry && context.attention) {
+ commitAttentionItemsOptimisticSnapshot(registry, context.attention)
+ void reconcileAccountAttention(registry).catch(() => undefined)
+ }
await controller.publishTerminalAndFence(friendshipId, context.generation)
},
onError: (_error, { friendshipId }, context) => {
if (!context) return
- if (!controller.isCompensatable(friendshipId, context.generation)) return
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!controller.isCompensatable(friendshipId, context.generation)) {
+ if (registry && context.attention) {
+ commitAttentionItemsOptimisticSnapshot(registry, context.attention)
+ }
+ return
+ }
+ if (registry && context.attention) {
+ if (!restoreAttentionItemsOptimisticSnapshot(registry, context.attention)) {
+ void reconcileAccountAttention(registry).catch(() => undefined)
+ }
+ }
queryClient.setQueryData<FriendsResponse | undefined>(communityKeys.friends(), (current) =>
current
? { ...current, pending: reinsertRow(current.pending, context?.friends) }
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index ab792483d..cc7014311 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -7,10 +7,11 @@
* `onError` manually. Same qc is used for cache assertions before/after each
* step.
*/
-import { describe, it, expect, vi, beforeEach } from "vitest"
+import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import type { Msg } from "@/lib/community/models/message"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
// ── React shim (mirrors use-community-ws.test.ts) ────────────────────────
let refs: Map<string, { current: unknown }> = new Map()
@@ -68,6 +69,8 @@ type MutConfig<Args, Ctx> = {
}
let capturedConfig: MutConfig<unknown, unknown> | null = null
let capturedQc: QueryClient
+let canonicalRegistry: CommunityDbRegistry | null = null
+let unregisterCanonicalRegistry: (() => void) | null = null
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
return {
@@ -155,6 +158,60 @@ beforeEach(() => {
callbackCounter = 0
})
+afterEach(async () => {
+ unregisterCanonicalRegistry?.()
+ unregisterCanonicalRegistry = null
+ await canonicalRegistry?.cleanup()
+ canonicalRegistry = null
+})
+
+async function installCanonicalRegistry() {
+ const collections = await import("@/lib/community-db/collections")
+ canonicalRegistry = collections.createCommunityDbRegistry(capturedQc, "u_me")
+ await canonicalRegistry.preload()
+ unregisterCanonicalRegistry = collections.registerCommunityDbRegistry(canonicalRegistry)
+}
+
+async function seedCanonicalParent(type: "forum" | "text") {
+ if (!canonicalRegistry) throw new Error("canonical test registry is not active")
+ const sync = await import("@/lib/community-db/sync")
+ sync.ingestServers(canonicalRegistry, { servers: [{
+ id: "s1", name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "u_me",
+ }] })
+ sync.ingestServerDetail(canonicalRegistry, {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "u_me", categories: [{
+ id: "cat_1", name: "Category", channels: [{
+ id: "forum_1", name: "Parent", active: false, unread: false, type,
+ }],
+ }],
+ })
+}
+
+async function seedCanonicalSidebar() {
+ await seedCanonicalParent("forum")
+ const sync = await import("@/lib/community-db/sync")
+ sync.publishCommunityForumSidebar(capturedQc, {
+ serverId: "s1",
+ channels: [{
+ id: "post_1", name: "Post", parentChannelId: "forum_1",
+ parentMessageId: "opener_1", activityAt: "2026-08-06T00:00:00.000Z",
+ unread: false, type: "thread",
+ }],
+ openers: [{ id: "opener_1", channelId: "forum_1", content: "Old title", type: "chat" }],
+ proof: {
+ token: sync.captureCommunityLiveSnapshotToken(capturedQc),
+ signal: undefined,
+ },
+ })
+}
+
+async function canonicalSidebar() {
+ const { getForumSidebarBase } = await import("../use-forum-sidebar-threads")
+ return getForumSidebarBase(capturedQc, "s1")
+}
+
describe("useEditMessage", () => {
it("optimistically patches content and rolls back when PATCH fails", async () => {
const key = communityKeys.channelMessages("ch_1")
@@ -213,11 +270,10 @@ describe("useEditMessage", () => {
})
it("patches a loaded forum-sidebar title after the opener edit succeeds", async () => {
- seedParent("forum")
- const sidebarKey = communityKeys.forumSidebarThreads("s1")
- capturedQc.setQueryData(sidebarKey, sidebarData())
apiFetchMock.mockResolvedValueOnce(undefined)
const mod = await loadMod()
+ await installCanonicalRegistry()
+ await seedCanonicalSidebar()
mod.useEditMessage()
await runMutation({
@@ -229,8 +285,7 @@ describe("useEditMessage", () => {
forumThreadId: "post_1",
})
- expect(capturedQc.getQueryData<ReturnType<typeof sidebarData>>(sidebarKey)?.threads[0].title)
- .toBe("New title")
+ expect((await canonicalSidebar()).threads[0]?.title).toBe("New title")
})
})
@@ -275,11 +330,10 @@ describe("useSendMessage — happy path", () => {
})
it("re-ranks a loaded participating forum thread from the canonical send timestamp", async () => {
- seedParent("forum")
- const sidebarKey = communityKeys.forumSidebarThreads("s1")
- capturedQc.setQueryData(sidebarKey, sidebarData())
apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
const mod = await loadMod()
+ await installCanonicalRegistry()
+ await seedCanonicalSidebar()
mod.useSendMessage()
await runMutation({
@@ -290,7 +344,7 @@ describe("useSendMessage — happy path", () => {
author: { id: "u_me", name: "me", avatar: "M" },
})
- expect(capturedQc.getQueryData<ReturnType<typeof sidebarData>>(sidebarKey)?.threads[0])
+ expect((await canonicalSidebar()).threads[0])
.toMatchObject({
activityAt: "2026-08-07T10:00:00.000Z",
expiresAt: "2026-08-10T10:00:00.000Z",
@@ -298,12 +352,12 @@ describe("useSendMessage — happy path", () => {
})
it("invalidates the sidebar collection when a just-enrolled thread is not loaded", async () => {
- seedParent("forum")
const sidebarKey = communityKeys.forumSidebarThreads("s1")
- const empty = { ...sidebarData(), threads: [] }
- capturedQc.setQueryData(sidebarKey, empty)
+ capturedQc.setQueryData(sidebarKey, { ...sidebarData(), threads: [] })
apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
const mod = await loadMod()
+ await installCanonicalRegistry()
+ await seedCanonicalParent("forum")
mod.useSendMessage()
await runMutation({
@@ -1062,36 +1116,51 @@ describe("useCreateThread — patches parent message + invalidates threads", ()
// ── useMarkAllInboxRead ───────────────────────────────────────────────────
describe("useMarkAllInboxRead", () => {
- it("fires exactly three POSTs — mentions + unreads + dms read-all", async () => {
+ it("uses the three existing read-all endpoints", async () => {
capturedQc.setQueryData(communityKeys.inboxUnreads(), { servers: [] })
capturedQc.setQueryData(communityKeys.inboxMentions(), { mentions: [] })
- apiFetchMock.mockResolvedValue(undefined)
+ apiFetchMock.mockResolvedValue({ revision: 2 })
const mod = await loadMod()
mod.useMarkAllInboxRead()
await runMutation<void>(undefined as unknown as void)
const posts = apiFetchMock.mock.calls.filter(
(c) => (c[1] as { method?: string })?.method === "POST",
)
- expect(posts).toHaveLength(3)
- const paths = posts.map((c) => c[0] as string).sort()
- expect(paths).toEqual([
- "/api/community/users/me/inbox/dms/read-all",
+ expect(posts.map((call) => call[0])).toEqual([
"/api/community/users/me/inbox/mentions/read-all",
"/api/community/users/me/inbox/unreads/read-all",
+ "/api/community/users/me/inbox/dms/read-all",
])
})
- it("keeps raw inbox caches authoritative while projection fences hide the captured prefix", async () => {
+ it("clears the canonical attention owner optimistically without rewriting legacy raw caches", async () => {
+ const mod = await loadMod()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
+ ingestAttentionSnapshot(canonicalRegistry!, {
+ scopes: [{
+ scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
+ ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: 1, attentionCount: 1,
+ }],
+ items: [{
+ id: "mention:men_1", kind: "mention", sourceId: "men_1", scopeId: "ch_1",
+ messageId: "m_1", actorUserId: "u_2", createdAt: "2026-09-27T00:00:00.000Z",
+ }, {
+ id: "friend_request:f_1", kind: "friend_request", sourceId: "f_1",
+ scopeId: null, messageId: null, actorUserId: "u_3",
+ createdAt: "2026-09-27T00:00:01.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ })
capturedQc.setQueryData(communityKeys.inboxUnreads(), {
servers: [{ serverId: "s_1", serverName: "s", channels: [{ channelId: "ch_1" }] }],
})
capturedQc.setQueryData(communityKeys.inboxMentions(), {
mentions: [{ id: "men_1" }],
})
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
mod.useMarkAllInboxRead()
- const cfg = capturedConfig as MutConfig<void, unknown>
+ const cfg = capturedConfig as MutConfig<void, { snapshot?: unknown }>
await cfg.onMutate?.(undefined as unknown as void)
expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual({
servers: [{ serverId: "s_1", serverName: "s", channels: [{ channelId: "ch_1" }] }],
@@ -1099,65 +1168,160 @@ describe("useMarkAllInboxRead", () => {
expect(capturedQc.getQueryData(communityKeys.inboxMentions())).toEqual({
mentions: [{ id: "men_1" }],
})
- const { getActiveAccountUnreadProjection } = await import(
- "@/hooks/community/account-unread-projection"
- )
- expect(getActiveAccountUnreadProjection(capturedQc).projectUnread(
- "inbox-unreads",
- "ch_1",
- true,
- 1,
- )).toBe(false)
+ await vi.waitFor(() => {
+ expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")).toBeUndefined()
+ expect(canonicalRegistry!.collections.attentionItems.get("mention:men_1")).toBeUndefined()
+ expect(canonicalRegistry!.collections.attentionItems.get("friend_request:f_1")).toBeDefined()
+ })
})
- it("reconciles fulfilled domains through the primary snapshot and server surfaces", async () => {
+ it("reconciles the canonical attention and read-state snapshots after success", async () => {
+ const mod = await loadMod()
+ await installCanonicalRegistry()
apiFetchMock.mockImplementation(async (path: string) => {
+ if (path.endsWith("/read-all")) {
+ return { revision: 3 }
+ }
+ if (path === "/api/community/users/me/attention") {
+ return { scopes: [], items: [], limit: 100, truncated: false }
+ }
if (path === "/api/community/users/me/read-state") {
return { revision: 3, readStates: [] }
}
- return { revision: 3 }
+ throw new Error(`unexpected path: ${path}`)
+ })
+ mod.useMarkAllInboxRead()
+ await runMutation<void>(undefined as unknown as void)
+ await vi.waitFor(() => {
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/attention",
+ expect.objectContaining({ signal: expect.anything() }),
+ )
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/read-state",
+ expect.objectContaining({ signal: expect.anything() }),
+ )
})
+ })
+
+ it("preserves the failed mention domain when channel and DM mark-all succeed", async () => {
const mod = await loadMod()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
+ const mentionOnly = {
+ scopes: [{
+ scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
+ ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,
+ }],
+ items: [{
+ id: "mention:men_1", kind: "mention" as const, sourceId: "men_1", scopeId: "ch_1",
+ messageId: "m_1", actorUserId: "u_2", createdAt: "2026-09-27T00:00:00.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ }
+ ingestAttentionSnapshot(canonicalRegistry!, {
+ ...mentionOnly,
+ scopes: [{ ...mentionOnly.scopes[0]!, ordinaryUnread: true }],
+ })
+ apiFetchMock.mockImplementation(async (path: string) => {
+ if (path === "/api/community/users/me/inbox/mentions/read-all") throw new Error("mentions failed")
+ if (path.endsWith("/read-all")) return { revision: 5 }
+ if (path === "/api/community/users/me/attention") return mentionOnly
+ if (path === "/api/community/users/me/read-state") return { revision: 5, readStates: [] }
+ throw new Error(`unexpected path: ${path}`)
+ })
mod.useMarkAllInboxRead()
- const spy = vi.spyOn(capturedQc, "invalidateQueries")
+
await runMutation<void>(undefined as unknown as void)
- await vi.waitFor(() => expect(spy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "servers"
- }).length).toBeGreaterThanOrEqual(1))
+
+ await vi.waitFor(() => {
+ expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")).toMatchObject({
+ ordinaryUnread: false,
+ attentionCount: 1,
+ lastAttentionSeq: 4,
+ })
+ expect(canonicalRegistry!.collections.attentionItems.get("mention:men_1")).toBeDefined()
+ })
})
- it("toasts the failure reason when one of the three read-all POSTs fails", async () => {
- apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ it("toasts the failure reason when all three read-all requests fail", async () => {
+ apiFetchMock.mockRejectedValue(new Error("boom"))
const mod = await loadMod()
mod.useMarkAllInboxRead()
await runMutation<void>(undefined as unknown as void).catch(() => { })
expect(toastMock).toHaveBeenCalledWith("boom")
})
- it("rolls back every domain fence when all three read-all requests fail", async () => {
- apiFetchMock.mockRejectedValue(new Error("all domains failed"))
+ it("restores canonical attention when the atomic read-all request fails", async () => {
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
+ ingestAttentionSnapshot(canonicalRegistry!, {
+ scopes: [{
+ scopeId: "channel", channelId: "channel", serverId: "s_1", parentChannelId: null,
+ ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: null, attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ apiFetchMock.mockRejectedValue(new Error("account read-all failed"))
const mod = await loadMod()
mod.useMarkAllInboxRead()
await expect(runMutation<void>(undefined as unknown as void))
- .rejects.toThrow("all domains failed")
+ .rejects.toThrow("account read-all failed")
- const { getActiveAccountUnreadProjection } = await import(
- "@/hooks/community/account-unread-projection"
+ expect(canonicalRegistry!.collections.attentionScopes.get("channel")).toBeDefined()
+ expect(toastMock).toHaveBeenCalledWith("account read-all failed")
+ })
+
+ it("reconciles mark-all after an intervening canonical event declines rollback", async () => {
+ const mod = await loadMod()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot, projectAttentionUnreadBump } = await import(
+ "@/lib/community-db/sync"
)
- const projection = getActiveAccountUnreadProjection(capturedQc)
- expect(projection.projectUnread("inbox-unreads", "channel", true, 1)).toBe(true)
- expect(projection.projectUnread("dms", "dm", true, 1, "dms")).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "mention", true, 1, "mentions"))
- .toBe(true)
- expect(toastMock).toHaveBeenCalledWith("all domains failed")
+ const canonical = {
+ scopes: [{
+ scopeId: "channel", channelId: "channel", serverId: "s_1", parentChannelId: null,
+ ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: null, attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ }
+ ingestAttentionSnapshot(canonicalRegistry!, canonical)
+ apiFetchMock.mockImplementation(async (path: string) => {
+ if (path === "/api/community/users/me/attention") return canonical
+ throw new Error("account read-all failed")
+ })
+ mod.useMarkAllInboxRead()
+ const cfg = capturedConfig as MutConfig<void, unknown>
+ const context = await cfg.onMutate?.(undefined as unknown as void)
+ projectAttentionUnreadBump(capturedQc, {
+ type: "community:unread.bump",
+ userId: "u_me",
+ channelId: "other",
+ serverId: "s_1",
+ isMention: false,
+ }, { seq: 2 })
+
+ cfg.onError?.(new Error("account read-all failed"), undefined as unknown as void, context)
+
+ await vi.waitFor(() => {
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/attention",
+ expect.objectContaining({ signal: expect.anything() }),
+ )
+ expect(canonicalRegistry!.collections.attentionScopes.get("channel")).toBeDefined()
+ })
})
- it("ignores an unexpected result whose optimistic domain token is absent", async () => {
+ it("tolerates partial success without an active canonical registry", async () => {
const mod = await loadMod()
mod.useMarkAllInboxRead()
- const cfg = capturedConfig as MutConfig<void, { tokens: Map<string, unknown> }>
+ const cfg = capturedConfig as MutConfig<void, unknown>
expect(() => cfg.onSuccess?.(
[{ domain: "channels", result: { status: "fulfilled", value: { revision: 1 } } }],
undefined as unknown as void,
@@ -1165,13 +1329,13 @@ describe("useMarkAllInboxRead", () => {
)).not.toThrow()
})
- it("retries all three idempotent routes after mentions and DMs commit before unreads fails", async () => {
- let unreadAttempts = 0
- apiFetchMock.mockImplementation(async (path: string) => {
- if (path === "/api/community/users/me/inbox/unreads/read-all" && unreadAttempts++ === 0) {
- throw new Error("channel read-all failed")
+ it("retries the same existing domain mutations after a transient failure", async () => {
+ let attempts = 0
+ apiFetchMock.mockImplementation(async () => {
+ if (attempts++ === 0) {
+ throw new Error("account read-all failed")
}
- return undefined
+ return { revision: 2 }
})
const mod = await loadMod()
mod.useMarkAllInboxRead()
@@ -1179,20 +1343,101 @@ describe("useMarkAllInboxRead", () => {
await runMutation<void>(undefined as unknown as void).catch(() => { })
await runMutation<void>(undefined as unknown as void)
- for (const path of [
- "/api/community/users/me/inbox/mentions/read-all",
- "/api/community/users/me/inbox/unreads/read-all",
- "/api/community/users/me/inbox/dms/read-all",
- ]) {
- expect(apiFetchMock.mock.calls.filter((call) => call[0] === path)).toHaveLength(2)
- }
- expect(toastMock).toHaveBeenCalledWith("channel read-all failed")
+ expect(apiFetchMock.mock.calls.filter(
+ (call) => String(call[0]).endsWith("/read-all"),
+ )).toHaveLength(6)
+ expect(toastMock).toHaveBeenCalledWith("account read-all failed")
})
})
// ── useDeleteMention — rollback ──────────────────────────────────────────
describe("useDeleteMention — rollback", () => {
+ it("commits canonical attention removal and reconciles after success", async () => {
+ const mod = await loadMod()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
+ const canonical = {
+ scopes: [{
+ scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
+ ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,
+ }],
+ items: [{
+ id: "mention:men_1", kind: "mention" as const, sourceId: "men_1", scopeId: "ch_1",
+ messageId: "m_1", actorUserId: "u_2", createdAt: "2026-09-27T00:00:00.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ }
+ ingestAttentionSnapshot(canonicalRegistry!, canonical)
+ capturedQc.setQueryData(communityKeys.inboxMentions(), {
+ mentions: [{ id: "men_1", channelId: "ch_1", kind: "mention", m: { id: "m_1", seq: 4 } }],
+ })
+ apiFetchMock.mockImplementation(async (path: string) => (
+ path === "/api/community/users/me/attention"
+ ? { ...canonical, scopes: [], items: [] }
+ : { revision: 5 }
+ ))
+
+ mod.useDeleteMention()
+ await runMutation({ mentionId: "men_1" })
+
+ await vi.waitFor(() => {
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/attention",
+ expect.objectContaining({ signal: expect.anything() }),
+ )
+ })
+ })
+
+ it("reconciles a failed dismissal after an intervening canonical event", async () => {
+ const mod = await loadMod()
+ await installCanonicalRegistry()
+ const { ingestAttentionSnapshot, projectAttentionUnreadBump } = await import(
+ "@/lib/community-db/sync"
+ )
+ const canonical = {
+ scopes: [{
+ scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
+ ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,
+ }],
+ items: [{
+ id: "mention:men_1", kind: "mention" as const, sourceId: "men_1", scopeId: "ch_1",
+ messageId: "m_1", actorUserId: "u_2", createdAt: "2026-09-27T00:00:00.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ }
+ ingestAttentionSnapshot(canonicalRegistry!, canonical)
+ capturedQc.setQueryData(communityKeys.inboxMentions(), {
+ mentions: [{ id: "men_1", channelId: "ch_1", kind: "mention", m: { id: "m_1", seq: 4 } }],
+ })
+ apiFetchMock.mockImplementation(async (path: string) => {
+ if (path === "/api/community/users/me/attention") return canonical
+ throw new Error("dismiss failed")
+ })
+ mod.useDeleteMention()
+ const cfg = capturedConfig as MutConfig<{ mentionId: string }, unknown>
+ const context = await cfg.onMutate?.({ mentionId: "men_1" })
+ projectAttentionUnreadBump(capturedQc, {
+ type: "community:unread.bump",
+ userId: "u_me",
+ channelId: "other",
+ serverId: "s_1",
+ isMention: false,
+ }, { seq: 5 })
+
+ cfg.onError?.(new Error("dismiss failed"), { mentionId: "men_1" }, context)
+
+ await vi.waitFor(() => {
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/attention",
+ expect.objectContaining({ signal: expect.anything() }),
+ )
+ expect(canonicalRegistry!.collections.attentionItems.get("mention:men_1")).toBeDefined()
+ })
+ })
+
it("keeps a same-seq sibling and only decrements badges for direct mentions", async () => {
const reply = {
id: "reply-1",
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 04e231c9d..f4e2b6ef5 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -43,11 +43,24 @@ import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-
import { isBlocked, type MentionType } from "@alook/shared"
import {
getActiveAccountUnreadProjection,
- type AccountUnreadDismissToken,
type AccountUnreadDomain,
+ type AccountUnreadDismissToken,
type MarkAllToken,
} from "@/hooks/community/account-unread-projection"
import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"
+import { reconcileAccountAttention } from "@/hooks/community/use-account-attention"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import {
+ clearAttentionOptimistically,
+ commitAttentionOptimisticSnapshot,
+ commitAttentionItemsOptimisticSnapshot,
+ removeAttentionItemsOptimistically,
+ restoreAttentionOptimisticDomains,
+ restoreAttentionOptimisticSnapshot,
+ restoreAttentionItemsOptimisticSnapshot,
+ type AttentionOptimisticSnapshot,
+ type AttentionItemsOptimisticSnapshot,
+} from "@/lib/community-db/sync"
/**
@@ -871,7 +884,10 @@ export function useMarkAllInboxRead() {
domain: AccountUnreadDomain
result: PromiseSettledResult<ReadAllResponse>
}
- type MarkAllContext = { tokens: Map<AccountUnreadDomain, MarkAllToken> }
+ type MarkAllContext = {
+ tokens: Map<AccountUnreadDomain, MarkAllToken>
+ snapshot?: AttentionOptimisticSnapshot
+ }
return useMutation<DomainResult[], Error, void, MarkAllContext>({
mutationFn: async () => {
const requests = [
@@ -891,23 +907,24 @@ export function useMarkAllInboxRead() {
entry.result.status === "rejected"
),
)
- if (failures.length === results.length) {
- throw failures[0]!.result.reason
- }
+ if (failures.length === results.length) throw failures[0]!.result.reason
return results
},
onMutate: async () => {
+ const registry = getCommunityDbRegistry(queryClient)
return {
tokens: new Map<AccountUnreadDomain, MarkAllToken>([
["channels", unreadProjection.beginMarkAll("channels")],
["dms", unreadProjection.beginMarkAll("dms")],
["mentions", unreadProjection.beginMarkAll("mentions")],
]),
+ snapshot: registry ? clearAttentionOptimistically(registry) : undefined,
}
},
onSuccess: (results, _variables, context) => {
let targetRevision = 0
let firstFailure: unknown
+ const failedDomains = new Set<AccountUnreadDomain>()
for (const { domain, result } of results) {
const token = context.tokens.get(domain)
if (!token) continue
@@ -916,9 +933,19 @@ export function useMarkAllInboxRead() {
unreadProjection.commitMarkAll(token, result.value?.revision ?? 0)
} else {
unreadProjection.rollbackMarkAll(token)
+ failedDomains.add(domain)
firstFailure ??= result.reason
}
}
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry && context.snapshot) {
+ if (failedDomains.size === 0) {
+ commitAttentionOptimisticSnapshot(registry, context.snapshot)
+ } else {
+ restoreAttentionOptimisticDomains(registry, context.snapshot, failedDomains)
+ }
+ }
+ if (registry) void reconcileAccountAttention(registry).catch(() => undefined)
if (firstFailure) toastApiError(firstFailure, "Some inbox items could not be marked read")
void reconcileAccountReadState(queryClient, {
surfaceMode: "all",
@@ -929,6 +956,12 @@ export function useMarkAllInboxRead() {
for (const token of context?.tokens.values() ?? []) {
unreadProjection.rollbackMarkAll(token)
}
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry && context?.snapshot) {
+ if (!restoreAttentionOptimisticSnapshot(registry, context.snapshot)) {
+ void reconcileAccountAttention(registry).catch(() => undefined)
+ }
+ }
toastApiError(e, "Failed to mark inbox read")
void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
@@ -945,7 +978,11 @@ export function useDeleteMention() {
{ revision: number },
Error,
DeleteMentionArgs,
- { snapshot: MentionsResponse | undefined; token?: AccountUnreadDismissToken }
+ {
+ snapshot: MentionsResponse | undefined
+ token?: AccountUnreadDismissToken
+ attentionSnapshot?: AttentionItemsOptimisticSnapshot
+ }
>({
mutationFn: async ({ mentionId }) => {
return apiFetch<{ revision: number }>(
@@ -968,16 +1005,34 @@ export function useDeleteMention() {
queryClient.setQueryData(key, (prev: { mentions: { id: string }[] } | undefined) =>
prev ? { ...prev, mentions: prev.mentions.filter((m) => m.id !== args.mentionId) } : prev,
)
- return { snapshot, token }
+ const registry = getCommunityDbRegistry(queryClient)
+ const attentionSnapshot = registry
+ ? removeAttentionItemsOptimistically(
+ registry,
+ (item) => item.sourceId === args.mentionId && item.kind !== "friend_request",
+ )
+ : undefined
+ return { snapshot, token, attentionSnapshot }
},
onSuccess: (result, _args, context) => {
if (context.token) unreadProjection.commitDismissMention(context.token, result?.revision)
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry && context.attentionSnapshot) {
+ commitAttentionItemsOptimisticSnapshot(registry, context.attentionSnapshot)
+ void reconcileAccountAttention(registry).catch(() => undefined)
+ }
// Deleting a mention row removes it from the unread-mention aggregate
// that feeds the server rail badge — refresh so the count drops.
void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
},
onError: (err, _args, ctx) => {
if (ctx?.token) unreadProjection.rollbackDismissMention(ctx.token)
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry && ctx?.attentionSnapshot) {
+ if (!restoreAttentionItemsOptimisticSnapshot(registry, ctx.attentionSnapshot)) {
+ void reconcileAccountAttention(registry).catch(() => undefined)
+ }
+ }
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.inboxMentions(), ctx.snapshot)
toastApiError(err, "Failed to remove mention")
},
diff --git a/src/web/src/hooks/community/mutations/server-rail.test.ts b/src/web/src/hooks/community/mutations/server-rail.test.ts
index d6f060374..d6dba4958 100644
--- a/src/web/src/hooks/community/mutations/server-rail.test.ts
+++ b/src/web/src/hooks/community/mutations/server-rail.test.ts
@@ -104,26 +104,4 @@ describe("useServerRailCommit", () => {
expect(invalidate).toHaveBeenCalledTimes(2)
})
- it("drops empty folders from the persisted rail projection", () => {
- queryClient.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "u1",
- capturedAt: Date.now(),
- serverOrder: ["a", "b", "c"],
- folders: [{ id: "one", name: "One", serverIds: ["c"] }],
- servers: [],
- })
- const options = useServerRailCommit() as any
- const emptyAfter = {
- ...after,
- folderOrder: ["one", "empty"],
- folders: { one: ["c"], empty: [] },
- }
- options.onSuccess({ createdFolderIds: {} }, { ...args, after: emptyAfter })
-
- expect(queryClient.getQueryData<any>(communityKeys.structuralSnapshot())).toMatchObject({
- serverOrder: ["b", "a", "c"],
- folders: [{ id: "one", name: "One", serverIds: ["c"] }],
- })
- })
})
diff --git a/src/web/src/hooks/community/mutations/server-rail.ts b/src/web/src/hooks/community/mutations/server-rail.ts
index ae9f27930..0ea8575b2 100644
--- a/src/web/src/hooks/community/mutations/server-rail.ts
+++ b/src/web/src/hooks/community/mutations/server-rail.ts
@@ -8,7 +8,6 @@ import type { FoldersResponse } from "@/hooks/community/use-folders"
import type { ServersResponse } from "@/hooks/community/use-servers"
import type { FolderServer } from "@/lib/community/models/navigation"
import type { RailState } from "@/lib/community/server-rail-model"
-import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"
export type ServerRailCommitArgs = {
before: RailState
@@ -108,25 +107,10 @@ export function useServerRailCommit() {
queryClient.setQueryData(serversKey, context.servers)
queryClient.setQueryData(foldersKey, context.folders)
},
- onSuccess: (response, args) => {
+ onSuccess: (response) => {
queryClient.setQueryData<FoldersResponse | undefined>(foldersKey, (folders) =>
reconcileCreatedFolderIds(folders, response.createdFolderIds),
)
- const folderNameById = new Map(
- (queryClient.getQueryData<FoldersResponse>(foldersKey)?.folders ?? [])
- .map((folder) => [folder.id, folder.name]),
- )
- updateStructuralSnapshot(queryClient, {
- type: "replaceRail",
- serverOrder: args.after.serverOrder,
- folders: args.after.folderOrder.flatMap((clientId) => {
- const id = response.createdFolderIds[clientId] ?? clientId
- const serverIds = args.after.folders[clientId] ?? []
- return serverIds.length > 0
- ? [{ id, name: folderNameById.get(id) ?? "Group", serverIds }]
- : []
- }),
- })
},
onSettled: async () => {
await Promise.all([
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 50a877d2f..b02b698fe 100644
--- a/src/web/src/hooks/community/mutations/servers.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/servers.dom.test.tsx
@@ -9,6 +9,7 @@ import {
claimOwnerServerDeleteScopeFlush,
completeOwnerServerDeleteScopeFlush,
createOwnerServerDeleteRouteToken,
+ isOwnerServerDeleteMeRootLanding,
isOwnerServerDeleteRouteProtected,
observeOwnerServerDeleteRouteCommit,
} from "@/lib/community/eject-server"
@@ -109,8 +110,10 @@ describe("useDeleteServer — unmounted caller", () => {
expect(onSuccess).toHaveBeenCalledWith({ serverId }, { needsNavigation: true })
expect(isOwnerServerDeleteRouteProtected(serverId)).toBe(true)
expect(claimOwnerServerDeleteNavigation(serverId, routeToken, "/c/me")).toBe(true)
+ expect(isOwnerServerDeleteMeRootLanding()).toBe(true)
observeOwnerServerDeleteRouteCommit("/c/me")
+ expect(isOwnerServerDeleteMeRootLanding()).toBe(true)
expect(claimOwnerServerDeleteScopeFlush(serverId)).toBe(true)
expect(completeOwnerServerDeleteScopeFlush(serverId)).toBe(true)
expect(isOwnerServerDeleteRouteProtected(serverId)).toBe(false)
diff --git a/src/web/src/hooks/community/mutations/servers.test.ts b/src/web/src/hooks/community/mutations/servers.test.ts
index a92102231..bc9782a2c 100644
--- a/src/web/src/hooks/community/mutations/servers.test.ts
+++ b/src/web/src/hooks/community/mutations/servers.test.ts
@@ -64,25 +64,6 @@ beforeEach(() => {
capturedQc = new QueryClient()
})
-function seedStructuralSnapshot(serverId = "srv_1") {
- capturedQc.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "u1",
- capturedAt: Date.now(),
- serverOrder: [serverId],
- folders: [],
- servers: [{
- id: serverId,
- name: "Server",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [],
- childRouteHints: [],
- }],
- })
-}
-
describe("useLeaveServer — optimistic + rollback", () => {
it("fences every unread source in the departing scope and rolls back atomically", async () => {
const mod = await load()
@@ -126,7 +107,6 @@ describe("useLeaveServer — optimistic + rollback", () => {
"%s success clears the server subtree, stream, and current private route",
async (operation) => {
apiFetchMock.mockResolvedValueOnce(undefined)
- seedStructuralSnapshot()
const mod = await load()
const { useCommunityStore } = await import("@/stores/community")
const { useMessageStreamStore } = await import("@/stores/community/message-stream")
@@ -181,9 +161,6 @@ describe("useLeaveServer — optimistic + rollback", () => {
expect(capturedQc.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()
expect([...useMessageStreamStore.getState().entries.values()]
.some((entry) => entry.scope.serverId === "srv_1")).toBe(false)
- expect(capturedQc.getQueryData<{
- serverOrder: string[]
- }>(communityKeys.structuralSnapshot())?.serverOrder).toEqual([])
if (operation === "delete") {
const lifecycle = await import("@/lib/community/eject-server")
expect(lifecycle.isOwnerServerDeleteRouteProtected("srv_1")).toBe(false)
@@ -303,8 +280,6 @@ describe("useDeleteServer — navigation lifecycle", () => {
describe("useUpdateServer — rollback on both caches", () => {
it("restores server-detail + servers-list on failure", async () => {
- seedStructuralSnapshot()
- const structuralBefore = capturedQc.getQueryData(communityKeys.structuralSnapshot())
capturedQc.setQueryData(communityKeys.server("srv_1"), {
id: "srv_1",
name: "old",
@@ -336,7 +311,6 @@ describe("useUpdateServer — rollback on both caches", () => {
communityKeys.servers(),
)
expect(list?.servers[0]).toMatchObject({ name: "old", description: "d" })
- expect(capturedQc.getQueryData(communityKeys.structuralSnapshot())).toBe(structuralBefore)
})
it("keeps the canonical list metadata aligned with an optimistic detail update", async () => {
diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.ts
index 7d7e4ec46..580c8f703 100644
--- a/src/web/src/hooks/community/mutations/servers.ts
+++ b/src/web/src/hooks/community/mutations/servers.ts
@@ -9,7 +9,6 @@ import {
getActiveAccountUnreadProjection,
type AccountUnreadScopeToken,
} from "@/hooks/community/account-unread-projection"
-import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"
import {
evictServerChannelScopes,
flushOwnerServerDeleteAfterSuccess,
@@ -237,13 +236,6 @@ export function useUpdateServer() {
if (ctx?.serverSnap) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.serverSnap)
if (ctx?.listSnap) queryClient.setQueryData(communityKeys.servers(), ctx.listSnap)
},
- onSuccess: (_data, args) => {
- updateStructuralSnapshot(queryClient, {
- type: "patchServer",
- serverId: args.serverId,
- changes: { name: args.name },
- })
- },
onSettled: () => {
void queryClient.invalidateQueries({
queryKey: communityKeys.channelRefDirectory(),
@@ -290,11 +282,6 @@ export function useUploadServerIcon() {
}
: prev,
)
- updateStructuralSnapshot(queryClient, {
- type: "patchServer",
- serverId: args.serverId,
- changes: { icon: bustUrl },
- })
},
})
}
diff --git a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
index 1e8980c8b..f1f322422 100644
--- a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
+++ b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
@@ -6,8 +6,7 @@ import { toAttachmentVm } from "./messages"
// carries the pending-row `id` (no server url), and the display url is derived
// CLIENT-side from (channelId, id) — matching the id-addressed
// `channels/{id}/attachments/{attachmentId}` door the server read path emits.
-// The image branch must carry width/height through — a silent-drop site flagged
-// in plans/attachment-image-dimensions.md's plan review.
+// The image branch must carry width/height through without silently dropping it.
describe("toAttachmentVm", () => {
it("derives the canonical thumbnail URL only from server confirmation", () => {
expect(toAttachmentVm("c1", {
diff --git a/src/web/src/hooks/community/mutations/uploads.test.ts b/src/web/src/hooks/community/mutations/uploads.test.ts
index ee1e5b806..14e806bed 100644
--- a/src/web/src/hooks/community/mutations/uploads.test.ts
+++ b/src/web/src/hooks/community/mutations/uploads.test.ts
@@ -8,8 +8,7 @@ import type { UploadFileResult } from "./uploads"
// The zip must happen BEFORE filtering out failed uploads (`null` results),
// or indices between `results` and the original `attachments` input array
-// misalign once a failed upload is dropped — see the design note in
-// plans/attachment-image-dimensions.md ("Exact zip transform").
+// misalign once a failed upload is dropped.
describe("zipUploadResultsWithDimensions", () => {
const upload = (name: string): UploadFileResult => ({
url: `/media/${name}`,
diff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.ts
index b2882066d..c52610ec5 100644
--- a/src/web/src/hooks/community/mutations/uploads.ts
+++ b/src/web/src/hooks/community/mutations/uploads.ts
@@ -90,8 +90,7 @@ export function buildAttachmentUploadFormData({
*
* The zip MUST happen before dropping failed (`null`) results, or indices
* between `results` and `attachments` misalign once a failed upload is
- * filtered out — see plans/attachment-image-dimensions.md's "Exact zip
- * transform" note.
+ * filtered out.
*/
export function zipUploadResultsWithDimensions(
results: (UploadFileResult | null)[],
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
index 7a9fa6f70..712779212 100644
--- a/src/web/src/hooks/community/read-coordinator.test.ts
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -2,9 +2,19 @@ import { QueryClient } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import {
+ ingestAttentionSnapshot,
+ ingestMessages,
+ projectAttentionUnreadBump,
+} from "@/lib/community-db/sync"
const apiFetch = vi.hoisted(() => vi.fn())
const reconcileAccountReadState = vi.hoisted(() => vi.fn())
+const reconcileAccountAttention = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetch(...args),
@@ -14,6 +24,10 @@ vi.mock("./community-ws/read-state-reconciliation", () => ({
reconcileAccountReadState: (...args: unknown[]) => reconcileAccountReadState(...args),
}))
+vi.mock("./use-account-attention", () => ({
+ reconcileAccountAttention: (...args: unknown[]) => reconcileAccountAttention(...args),
+}))
+
import {
confirmReadSurface,
disposeReadCoordinator,
@@ -29,10 +43,17 @@ import {
} from "./read-coordinator"
import {
activateInboxProjectionTicket,
+ armInboxReadReservationCandidate,
+ cancelInboxProjectionTicket,
+ disposeInboxReadReservation,
inboxReadCandidateFingerprint,
+ promoteInboxReadReservation,
+ publishInboxProjectionGenerationTerminal,
registerInboxProjectionTicket,
registerInboxReadReservationSurface,
+ releaseInboxReadReservationSurface,
reserveInboxUnreadsResponse,
+ settleInboxReadReservationGeneration,
type InboxRowTarget,
} from "./inbox-read-reservation"
import { getAccountUnreadProjection } from "./account-unread-projection"
@@ -63,6 +84,7 @@ describe("read coordinator", () => {
vi.useFakeTimers()
apiFetch.mockReset()
reconcileAccountReadState.mockReset().mockResolvedValue(undefined)
+ reconcileAccountAttention.mockReset().mockResolvedValue(undefined)
})
afterEach(() => {
@@ -180,6 +202,591 @@ describe("read coordinator", () => {
expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
})
+ it("clears canonical attention while the read PUT is pending and restores it on failure", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const scope = {
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: 4,
+ attentionCount: 1,
+ }
+ const item = {
+ id: "mention:mention-1",
+ kind: "mention" as const,
+ sourceId: "mention-1",
+ scopeId: "channel-1",
+ messageId: "message-4",
+ actorUserId: "user-2",
+ createdAt: "2026-09-27T01:00:00.000Z",
+ }
+ ingestAttentionSnapshot(registry, {
+ scopes: [scope],
+ items: [item],
+ limit: 100,
+ truncated: false,
+ })
+ let rejectPut!: (error: unknown) => void
+ apiFetch.mockReturnValueOnce(new Promise((_resolve, reject) => {
+ rejectPut = reject
+ }))
+
+ try {
+ const lease = timelineLease(queryClient)
+ expect(submitTimeline(lease, 4)).toBe(true)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ expect(registry.collections.attentionItems.get(item.id)).toBeUndefined()
+
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(apiFetch).toHaveBeenCalledOnce()
+ ingestAttentionSnapshot(registry, {
+ scopes: [scope],
+ items: [item],
+ limit: 100,
+ truncated: false,
+ })
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ expect(registry.collections.attentionItems.get(item.id)).toBeUndefined()
+
+ rejectPut(new ApiError("forbidden", 403))
+ await vi.waitFor(() => {
+ expect(registry.collections.attentionScopes.get("channel-1"))
+ .toMatchObject(scope)
+ })
+ expect(registry.collections.attentionItems.get(item.id)).toMatchObject(item)
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
+ it("advances a coalesced attention fence and restores every cleared target on failure", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestMessages(registry, "channel-1", [3, 4].map((seq) => ({
+ id: `message-${seq}`,
+ type: "chat" as const,
+ authorId: "user-2",
+ seq,
+ })))
+ const items = [3, 4].map((seq) => ({
+ id: `mention:${seq}`,
+ kind: "mention" as const,
+ sourceId: String(seq),
+ scopeId: "channel-1",
+ messageId: `message-${seq}`,
+ actorUserId: "user-2",
+ createdAt: `2026-09-27T01:0${seq}:00.000Z`,
+ }))
+ const scope = {
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: 4,
+ attentionCount: 2,
+ }
+ ingestAttentionSnapshot(registry, {
+ scopes: [scope],
+ items,
+ limit: 100,
+ truncated: false,
+ })
+ apiFetch.mockRejectedValueOnce(new ApiError("forbidden", 403))
+
+ try {
+ const lease = timelineLease(queryClient)
+ expect(submitTimeline(lease, 3)).toBe(true)
+ expect(registry.collections.attentionScopes.get("channel-1")?.attentionCount).toBe(1)
+ expect(registry.collections.attentionItems.get("mention:3")).toBeUndefined()
+ expect(registry.collections.attentionItems.get("mention:4")).toBeDefined()
+
+ expect(submitTimeline(lease, 4)).toBe(true)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ expect(registry.collections.attentionItems.get("mention:4")).toBeUndefined()
+
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(registry.collections.attentionScopes.get("channel-1")).toMatchObject(scope)
+ expect(registry.collections.attentionItems.get("mention:3")).toMatchObject(items[0])
+ expect(registry.collections.attentionItems.get("mention:4")).toMatchObject(items[1])
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
+ it("reconciles canonical attention when a retry succeeds after its fence rolled back", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const scope = {
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }
+ ingestAttentionSnapshot(registry, {
+ scopes: [scope],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ apiFetch
+ .mockRejectedValueOnce(new ApiError("unavailable", 500))
+ .mockResolvedValueOnce({ changed: true, revision: 9, targetSeq: 4 })
+ reconcileAccountAttention.mockImplementationOnce(async () => {
+ ingestAttentionSnapshot(registry, {
+ scopes: [],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ })
+
+ try {
+ const lease = timelineLease(queryClient)
+ expect(submitTimeline(lease, 4)).toBe(true)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(reconcileAccountAttention).not.toHaveBeenCalled()
+ expect(registry.collections.attentionScopes.get("channel-1")).toMatchObject(scope)
+
+ await vi.advanceTimersByTimeAsync(251)
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(reconcileAccountAttention).toHaveBeenCalledWith(registry)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
+ it("reconciles instead of restoring stale attention across an intervening WS fact", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ let rejectPut!: (error: unknown) => void
+ apiFetch.mockReturnValueOnce(new Promise((_resolve, reject) => {
+ rejectPut = reject
+ }))
+
+ try {
+ const lease = timelineLease(queryClient)
+ submitTimeline(lease, 4)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ projectAttentionUnreadBump(queryClient, {
+ type: "community:unread.bump",
+ userId: "user-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ isMention: false,
+ }, { seq: 5 })
+
+ rejectPut(new ApiError("forbidden", 403))
+ await vi.waitFor(() => expect(reconcileAccountAttention).toHaveBeenCalledWith(registry))
+ expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(5)
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
+ it("keeps canonical attention cleared when a failed request has a newer generation", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 3,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ let rejectFirst!: (error: unknown) => void
+ apiFetch
+ .mockReturnValueOnce(new Promise((_resolve, reject) => {
+ rejectFirst = reject
+ }))
+ .mockReturnValueOnce(new Promise(() => undefined))
+
+ try {
+ const lease = timelineLease(queryClient)
+ submitTimeline(lease, 3)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ submitTimeline(lease, 4)
+
+ rejectFirst(new ApiError("forbidden", 403))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
+ it("reconciles canonical attention after a committed read", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ apiFetch.mockResolvedValue({ changed: true, revision: 9, targetSeq: 4 })
+ reconcileAccountAttention.mockRejectedValueOnce(new Error("attention unavailable"))
+
+ try {
+ const lease = timelineLease(queryClient)
+ submitTimeline(lease, 4)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+
+ expect(reconcileAccountAttention).toHaveBeenCalledWith(registry)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
+ it("lets an activated Inbox ticket own the pre-observer canonical clear", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ const lastMessageAt = "2026-09-27T01:00:00.000Z"
+ const target: InboxRowTarget = {
+ kind: "channel-direct",
+ identity: JSON.stringify(["channel-direct", "server-1", "channel-1"]),
+ fingerprint: inboxReadCandidateFingerprint({
+ channelId: "channel-1",
+ lastMessageAt,
+ openerUnread: false,
+ }),
+ confirmationChannelId: "channel-1",
+ serverId: "server-1",
+ channelId: "channel-1",
+ reservedThroughSeq: 4,
+ }
+ const receipt = vi.fn()
+ const reservation = registerInboxReadReservationSurface(
+ queryClient,
+ "channel-1",
+ vi.fn(),
+ )
+ armInboxReadReservationCandidate(queryClient, { channelId: "channel-1", lastMessageAt })
+ activateInboxProjectionTicket(registerInboxProjectionTicket(
+ queryClient,
+ 1,
+ target,
+ receipt,
+ ))
+ activateInboxProjectionTicket(registerInboxProjectionTicket(
+ queryClient,
+ 2,
+ target,
+ vi.fn(),
+ ))
+
+ try {
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ const lease = timelineLease(queryClient)
+ const generation = submitReadIntentGeneration(lease, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: "message-4",
+ seq: 4,
+ })!
+ promoteInboxReadReservation(reservation, generation)
+ publishInboxProjectionGenerationTerminal(queryClient, generation, "success")
+
+ expect(receipt).toHaveBeenCalledWith(expect.objectContaining({ terminal: "success" }))
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
+ it("restores a canceled Inbox ticket and reconciles a conflicted cancellation", async () => {
+ const run = async (conflict: boolean) => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ const target: InboxRowTarget = {
+ kind: "channel-direct",
+ identity: JSON.stringify(["channel-direct", "server-1", "channel-1"]),
+ fingerprint: "focused",
+ confirmationChannelId: "channel-1",
+ serverId: "server-1",
+ channelId: "channel-1",
+ reservedThroughSeq: 4,
+ }
+ const ticket = registerInboxProjectionTicket(queryClient, 1, target, vi.fn())
+ activateInboxProjectionTicket(ticket)
+ if (conflict) {
+ projectAttentionUnreadBump(queryClient, {
+ type: "community:unread.bump",
+ userId: "user-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ isMention: false,
+ }, { seq: 5 })
+ }
+
+ try {
+ expect(cancelInboxProjectionTicket(ticket)).toBe(true)
+ if (conflict) {
+ expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(5)
+ expect(reconcileAccountAttention).toHaveBeenCalledWith(registry)
+ } else {
+ expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(4)
+ }
+ } finally {
+ disposeInboxReadReservation(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ }
+
+ await run(false)
+ reconcileAccountAttention.mockClear()
+ await run(true)
+ })
+
+ it("commits an active Inbox attention fence on reservation disposal", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ activateInboxProjectionTicket(registerInboxProjectionTicket(
+ queryClient,
+ 1,
+ {
+ kind: "channel-direct",
+ identity: "dispose",
+ fingerprint: "dispose",
+ confirmationChannelId: "channel-1",
+ serverId: "server-1",
+ channelId: "channel-1",
+ reservedThroughSeq: 4,
+ },
+ vi.fn(),
+ ))
+
+ disposeInboxReadReservation(queryClient)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ unregister()
+ await registry.cleanup()
+ })
+
+ it.each(["commit", "rollback"] as const)(
+ "%s settles a focused WS attention fence at its exact sequence",
+ async (terminal) => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ const lease = registerInboxReadReservationSurface(
+ queryClient,
+ "channel-1",
+ vi.fn(),
+ )
+
+ try {
+ expect(armInboxReadReservationCandidate(queryClient, {
+ channelId: "channel-1",
+ lastMessageAt: "2026-09-27T01:00:00.000Z",
+ seq: 4,
+ })).toBe(true)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+
+ if (terminal === "commit") {
+ expect(promoteInboxReadReservation(lease, 41)).toBe(true)
+ await settleInboxReadReservationGeneration(queryClient, 41, true, "channel-1")
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ } else {
+ releaseInboxReadReservationSurface(lease)
+ expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(4)
+ }
+ } finally {
+ disposeInboxReadReservation(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ },
+ )
+
+ it("does not duplicate a focused WS fence already owned by an Inbox ticket", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ activateInboxProjectionTicket(registerInboxProjectionTicket(
+ queryClient,
+ 1,
+ {
+ kind: "channel-direct",
+ identity: "existing-fence",
+ fingerprint: "existing-fence",
+ confirmationChannelId: "channel-1",
+ serverId: "server-1",
+ channelId: "channel-1",
+ reservedThroughSeq: 4,
+ },
+ vi.fn(),
+ ))
+ registerInboxReadReservationSurface(queryClient, "channel-1", vi.fn())
+
+ expect(armInboxReadReservationCandidate(queryClient, {
+ channelId: "channel-1",
+ lastMessageAt: "2026-09-27T01:00:00.000Z",
+ seq: 4,
+ })).toBe(true)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+
+ disposeInboxReadReservation(queryClient)
+ unregister()
+ await registry.cleanup()
+ })
+
it("rolls back the matching optimistic projection while a transient retry waits", async () => {
const queryClient = new QueryClient()
const lease = timelineLease(queryClient)
@@ -200,6 +807,46 @@ describe("read coordinator", () => {
expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
})
+ it("keeps canonical attention restored while a transient retry waits", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "user-1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "channel-1",
+ channelId: "channel-1",
+ serverId: "server-1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ apiFetch
+ .mockRejectedValueOnce(new ApiError("busy", 503))
+ .mockReturnValueOnce(new Promise(() => undefined))
+
+ try {
+ submitTimeline(timelineLease(queryClient), 4)
+ expect(registry.collections.attentionScopes.get("channel-1")).toBeUndefined()
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(4)
+
+ await vi.advanceTimersByTimeAsync(251)
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(registry.collections.attentionScopes.get("channel-1")?.lastUnreadSeq).toBe(4)
+ } finally {
+ disposeReadCoordinator(queryClient)
+ unregister()
+ await registry.cleanup()
+ }
+ })
+
it("bounds transient retries, retains dirty intent, and resumes it later", async () => {
const queryClient = new QueryClient()
const lease = timelineLease(queryClient)
diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.ts
index 432085706..488e686f1 100644
--- a/src/web/src/hooks/community/read-coordinator.ts
+++ b/src/web/src/hooks/community/read-coordinator.ts
@@ -17,6 +17,15 @@ import {
settleInboxReadReservationGeneration,
} from "./inbox-read-reservation"
import { getAccountUnreadProjection } from "./account-unread-projection"
+import { getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
+import {
+ clearAttentionScopeOptimistically,
+ commitAttentionScopeOptimisticSnapshot,
+ hasAttentionScopeOptimisticFence,
+ restoreAttentionScopeOptimisticSnapshot,
+ type AttentionScopeOptimisticSnapshot,
+} from "@/lib/community-db/sync"
+import { reconcileAccountAttention } from "./use-account-attention"
export const READ_COORDINATOR_DEBOUNCE_MS = 500
@@ -87,6 +96,10 @@ type ScopeState = {
attemptEpoch: number
retryCount: number
confirmedSeq: number
+ attentionOptimistic: {
+ registry: CommunityDbRegistry
+ snapshot: AttentionScopeOptimisticSnapshot
+ } | null
}
const coordinators = new WeakMap<QueryClient, ReadCoordinator>()
@@ -147,6 +160,7 @@ class ReadCoordinator {
attemptEpoch: 0,
retryCount: 0,
confirmedSeq,
+ attentionOptimistic: null,
}
this.states.set(key, state)
} else if (surface.kind === "timeline") {
@@ -206,6 +220,9 @@ class ReadCoordinator {
state.surface.channelId,
)
}
+ if (!state.accepted && !state.dirty && !state.inFlight) {
+ this.rollbackAttentionOptimisticRead(state)
+ }
return
}
if (state.leases.size > 0 || state.releaseTimer !== null) return
@@ -246,6 +263,7 @@ class ReadCoordinator {
}
state.accepted = laterIntent(state.accepted, queued)
state.dirty = laterIntent(state.dirty, queued)
+ this.beginAttentionOptimisticRead(state)
for (const generation of supersededGenerations) {
getAccountUnreadProjection(this.queryClient, this.ownerUserId)
.settleOptimisticRead(generation, false)
@@ -297,6 +315,7 @@ class ReadCoordinator {
if (state.retryTimer !== null) clearTimeout(state.retryTimer)
if (state.releaseTimer !== null) clearTimeout(state.releaseTimer)
state.inFlight?.controller.abort()
+ this.commitAttentionOptimisticRead(state)
state.attemptEpoch += 1
state.accepted = null
state.dirty = null
@@ -398,6 +417,7 @@ class ReadCoordinator {
this.cancelConfirmedWork(state)
return Promise.resolve({ committed: false, reconciled: false })
}
+ this.beginAttentionOptimisticRead(state)
state.accepted = null
const controller = new AbortController()
const attemptEpoch = ++state.attemptEpoch
@@ -448,6 +468,10 @@ class ReadCoordinator {
)
getAccountUnreadProjection(this.queryClient, this.ownerUserId)
.settleOptimisticRead(target.generation, false)
+ const newerOptimisticRead = [state.accepted, state.dirty].some((pending) => (
+ pending !== null && pending.generation > target.generation
+ ))
+ if (!newerOptimisticRead) this.rollbackAttentionOptimisticRead(state)
if (!retryable(error)) {
if (state.dirty && sameIntent(state.dirty, target)) state.dirty = null
state.retryCount = 0
@@ -491,11 +515,17 @@ class ReadCoordinator {
&& state.accepted !== null
&& state.accepted.generation > activeAttempt.drainCutoff)
try {
- await reconcileAccountReadState(this.queryClient, {
- surfaceMode: deferInboxDms ? "non-inbox" : "all",
- awaitSurfaceMode: deferInboxDms ? "none" : "inbox-dms",
- targetRevision: response.revision,
- })
+ const attentionRegistry = getCommunityDbRegistry(this.queryClient)
+ await Promise.all([
+ reconcileAccountReadState(this.queryClient, {
+ surfaceMode: deferInboxDms ? "non-inbox" : "all",
+ awaitSurfaceMode: deferInboxDms ? "none" : "inbox-dms",
+ targetRevision: response.revision,
+ }),
+ attentionRegistry
+ ? reconcileAccountAttention(attentionRegistry).catch(() => undefined)
+ : Promise.resolve(),
+ ])
if (deferInboxDms) {
publishInboxProjectionGenerationTerminal(
this.queryClient,
@@ -525,6 +555,9 @@ class ReadCoordinator {
)
return { committed: true, reconciled: false }
} finally {
+ if (!state.accepted && !state.dirty) {
+ this.commitAttentionOptimisticRead(state)
+ }
this.finishAttempt(state, attemptEpoch)
}
}
@@ -572,6 +605,55 @@ class ReadCoordinator {
clearTimeout(state.retryTimer)
state.retryTimer = null
}
+ if (!state.accepted && !state.dirty && !state.inFlight) {
+ this.commitAttentionOptimisticRead(state)
+ const registry = getCommunityDbRegistry(this.queryClient)
+ if (registry) void reconcileAccountAttention(registry).catch(() => undefined)
+ }
+ }
+
+ private beginAttentionOptimisticRead(state: ScopeState) {
+ const targetSeq = state.accepted?.intent.seq ?? state.dirty?.intent.seq ?? 0
+ if (
+ state.attentionOptimistic
+ && state.attentionOptimistic.snapshot.targetSeq >= targetSeq
+ ) return
+ if (state.attentionOptimistic) this.rollbackAttentionOptimisticRead(state)
+ if (state.retryCount > 0) return
+ const registry = getCommunityDbRegistry(this.queryClient)
+ if (!registry) return
+ if (hasAttentionScopeOptimisticFence(
+ this.queryClient,
+ state.surface.channelId,
+ targetSeq,
+ )) return
+ state.attentionOptimistic = {
+ registry,
+ snapshot: clearAttentionScopeOptimistically(
+ registry,
+ state.surface.channelId,
+ targetSeq,
+ ),
+ }
+ }
+
+ private commitAttentionOptimisticRead(state: ScopeState) {
+ const optimistic = state.attentionOptimistic
+ if (!optimistic) return
+ state.attentionOptimistic = null
+ commitAttentionScopeOptimisticSnapshot(optimistic.registry, optimistic.snapshot)
+ }
+
+ private rollbackAttentionOptimisticRead(state: ScopeState) {
+ const optimistic = state.attentionOptimistic
+ if (!optimistic) return
+ state.attentionOptimistic = null
+ if (!restoreAttentionScopeOptimisticSnapshot(optimistic.registry, optimistic.snapshot)) {
+ const registry = getCommunityDbRegistry(this.queryClient)
+ if (registry === optimistic.registry) {
+ void reconcileAccountAttention(registry).catch(() => undefined)
+ }
+ }
}
private confirmed(state: ScopeState, intent: ReadIntent) {
diff --git a/src/web/src/hooks/community/server-detail-cache.test.ts b/src/web/src/hooks/community/server-detail-cache.test.ts
index abf081100..7cb295284 100644
--- a/src/web/src/hooks/community/server-detail-cache.test.ts
+++ b/src/web/src/hooks/community/server-detail-cache.test.ts
@@ -63,10 +63,8 @@ describe("patchChannelUnread", () => {
expect(toFalse?.categories[0].channels.find((c) => c.id === "ch_a1")?.unread).toBe(false)
})
- // Regression: the "optimistic markRead stomp" found in plan review — see
- // plans/community-unread-indicators.md §2 "Second-order risk". Without the
- // click-time cache patch (channels/layout.tsx), A would have reverted to
- // `true` here.
+ // Regression: without the click-time cache patch, a later sibling-channel
+ // update would overwrite the optimistic mark-read and make A unread again.
it("clicking channel A then a WS patch for sibling channel B does not resurrect A's cleared dot", () => {
let cache: ServerDetail | undefined = fixture()
// Seed A as unread (as if a message arrived earlier).
diff --git a/src/web/src/hooks/community/use-account-attention.ts b/src/web/src/hooks/community/use-account-attention.ts
new file mode 100644
index 000000000..a8d378623
--- /dev/null
+++ b/src/web/src/hooks/community/use-account-attention.ts
@@ -0,0 +1,145 @@
+"use client"
+
+import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
+import {
+ AccountAttentionSnapshotSchema,
+ type AccountAttentionSnapshot,
+} from "@alook/shared"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ useAttentionItems,
+ useAttentionScopes,
+ useCanonicalChannelsById,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishAccountAttentionSnapshot,
+} from "@/lib/community-db/sync"
+import {
+ getCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
+import { useDms } from "@/hooks/community/use-dms"
+
+class StaleAttentionReadError extends Error {
+ constructor() {
+ super("stale D1 attention read")
+ this.name = "StaleAttentionReadError"
+ }
+}
+
+async function fetchAccountAttention(signal?: AbortSignal): Promise<AccountAttentionSnapshot> {
+ const response = await apiFetch<AccountAttentionSnapshot & { stale?: boolean }>(
+ "/api/community/users/me/attention",
+ signal ? { signal } : undefined,
+ )
+ if (response.stale) throw new StaleAttentionReadError()
+ return AccountAttentionSnapshotSchema.parse(response)
+}
+
+const accountAttentionQueryFn = (queryClient: QueryClient) =>
+ async ({ signal }: { signal?: AbortSignal } = {}) => {
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ const snapshot = await fetchAccountAttention(signal)
+ publishAccountAttentionSnapshot(queryClient, {
+ snapshot,
+ proof: { token, signal },
+ })
+ return snapshot
+ }
+
+export function useAccountAttention() {
+ const queryClient = useQueryClient()
+ const scopes = useAttentionScopes()
+ const items = useAttentionItems()
+ const query = useQuery({
+ queryKey: communityKeys.accountAttention(),
+ queryFn: accountAttentionQueryFn(queryClient),
+ staleTime: 0,
+ refetchOnMount: "always",
+ })
+ return { ...query, scopes, items }
+}
+
+/**
+ * Attention owns only stable structural refs. When those refs arrive before a
+ * cold route has loaded their canonical owners, enable the existing structural
+ * directory/DM queries. Their normal publishers hydrate the shared collections
+ * and every Inbox observer then recomposes without a second attention request.
+ */
+export function useAccountAttentionScopeHydration() {
+ const scopes = useAttentionScopes()
+ const channelsById = useCanonicalChannelsById()
+ const needsServerChannels = scopes.some((scope) => (
+ Boolean(scope.serverId) && !channelsById.has(scope.channelId)
+ ))
+ const needsDms = scopes.some((scope) => (
+ !scope.serverId && !channelsById.has(scope.channelId)
+ ))
+ useChannelRefDirectory(needsServerChannels)
+ useDms(needsDms)
+}
+
+/**
+ * Read-only observer for consumers. The shell owns the sole enabled transport;
+ * every visible attention surface observes that query plus the canonical rows.
+ */
+export function useAccountAttentionProjection() {
+ const queryClient = useQueryClient()
+ const scopes = useAttentionScopes()
+ const items = useAttentionItems()
+ const query = useQuery({
+ queryKey: communityKeys.accountAttention(),
+ queryFn: accountAttentionQueryFn(queryClient),
+ enabled: false,
+ })
+ return { ...query, scopes, items }
+}
+
+export async function reconcileAccountAttention(
+ registry: CommunityDbRegistry,
+) {
+ const snapshot = await registry.queryClient.fetchQuery({
+ queryKey: communityKeys.accountAttention(),
+ queryFn: accountAttentionQueryFn(registry.queryClient),
+ staleTime: 0,
+ })
+ return snapshot
+}
+
+type AttentionReconcileState = { version: number; running: boolean }
+const attentionReconcileStates = new WeakMap<QueryClient, AttentionReconcileState>()
+
+export function scheduleAccountAttentionReconcile(queryClient: QueryClient) {
+ const state = attentionReconcileStates.get(queryClient) ?? { version: 0, running: false }
+ state.version += 1
+ attentionReconcileStates.set(queryClient, state)
+ if (state.running) return
+ state.running = true
+ queueMicrotask(() => {
+ void (async () => {
+ try {
+ while (true) {
+ const targetVersion = state.version
+ // An event must never join a request that began before that event.
+ // Abort that read first, then let the fresh query capture its own
+ // publication token after the local WS projection is complete.
+ await queryClient.cancelQueries({
+ queryKey: communityKeys.accountAttention(),
+ exact: true,
+ })
+ const registry = getCommunityDbRegistry(queryClient)
+ if (registry) await reconcileAccountAttention(registry).catch(() => undefined)
+ if (state.version === targetVersion) break
+ }
+ } finally {
+ state.running = false
+ if (state.version > 0 && !getCommunityDbRegistry(queryClient)) {
+ attentionReconcileStates.delete(queryClient)
+ }
+ }
+ })()
+ })
+}
diff --git a/src/web/src/hooks/community/use-bots.dom.test.ts b/src/web/src/hooks/community/use-bots.dom.test.ts
index 57eb05bbd..e4f396a01 100644
--- a/src/web/src/hooks/community/use-bots.dom.test.ts
+++ b/src/web/src/hooks/community/use-bots.dom.test.ts
@@ -106,7 +106,7 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
const output = renderer.container.querySelector("span")
expect(output).toHaveAttribute("data-count", "1")
expect(output).toHaveAttribute("data-name", "Seeded Bot")
- expect(output).toHaveAttribute("data-avatar", "S")
+ expect(output).not.toHaveAttribute("data-avatar")
expect(output).toHaveAttribute("data-version", "2")
expect(output).toHaveAttribute("data-plan", "Free")
expect(output).toHaveAttribute("data-limit", "3")
@@ -131,9 +131,9 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
let mutation!: ReturnType<typeof useSetBotActive>
function Probe() { useBots(); mutation = useSetBotActive(); return null }
render(React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)))
- await waitFor(() => expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")?.presence).toBe("offline"))
+ await waitFor(() => expect(useCommunityWsStore.getState().presenceByUserId.get("bot_1")).toBe("offline"))
await act(async () => { await mutation.mutateAsync({ id: "bot_1", active: true }) })
- await waitFor(() => expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")?.presence).toBe("online"))
+ await waitFor(() => expect(useCommunityWsStore.getState().presenceByUserId.get("bot_1")).toBe("online"))
})
it("does not overwrite a newer presence event with a late bot list", async () => {
@@ -144,17 +144,16 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
function Probe() { useBots(); return null }
render(React.createElement(QueryClientProvider, { client: queryClient }, React.createElement(Probe)))
await waitFor(() => expect(apiFetchMock).toHaveBeenCalled())
- const profiles = useCommunityWsStore.getState()
- act(() => profiles.patchProfiles(profiles.beginProfileSnapshot(), [{ id: "bot_1", presence: "offline" }]))
+ act(() => useCommunityWsStore.getState().setPresence("bot_1", "offline"))
await act(async () => resolve({
plan: { id: "free", displayName: "Free" }, limit: 3, ownedCount: 1, activeCount: 1,
bots: [{ id: "bot_1", name: "Bot", image: null, avatarVersion: 0, isActive: true, presence: "online" }],
}))
await waitFor(() => expect(queryClient.getQueryData(communityKeys.bots())).toBeDefined())
- expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")?.presence).toBe("offline")
+ expect(useCommunityWsStore.getState().presenceByUserId.get("bot_1")).toBe("offline")
})
- it("useCreateBot commits the returned bot profile before invalidating metadata", async () => {
+ it("useCreateBot accepts the returned bot before invalidating metadata", async () => {
const { useCreateBot } = await import("./use-bots")
apiFetchMock.mockResolvedValue({
bot: {
@@ -189,12 +188,6 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/bots", expect.objectContaining({
method: "POST",
}))
- expect(useCommunityWsStore.getState().profilesByUserId.get("bot_created")).toMatchObject({
- name: "Created Bot",
- kind: "bot",
- avatar: "C",
- avatarVersion: 3,
- })
act(() => renderer.unmount())
})
@@ -350,7 +343,7 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
// than reading an id off the (empty) response body.
})
- it("useUploadBotAvatar patches the canonical avatar without rewriting raw caches", async () => {
+ it("useUploadBotAvatar keeps raw query caches immutable", async () => {
const { useUploadBotAvatar } = await import("./use-bots")
const { useCommunityWsStore } = await import("@/stores/community/ws")
useCommunityWsStore.getState().reset()
@@ -381,10 +374,6 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
})
})
- expect(useCommunityWsStore.getState().profilesByUserId.get("bot_1")).toMatchObject({
- avatar: "/api/community/bots/bot_1/avatar?v=4",
- avatarVersion: 4,
- })
expect(queryClient.getQueryData(communityKeys.bots())).toMatchObject({
bots: [{ id: "bot_1", image: "/avatar?v=1", avatarVersion: 1 }],
})
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 528a53de3..432caf808 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -2,14 +2,17 @@
import { useQuery, useMutation, useQueryClient, type UseQueryResult } from "@tanstack/react-query"
import { apiFetch, readUploadError } from "@/lib/api/client"
-import { apiFetchProfiles } from "@/lib/community/profile-seed"
+import {
+ apiFetchProfiles,
+ writeCommunityProfilePatches,
+} from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
-import { useCommunityWsStore } from "@/stores/community/ws"
import type { BotActivityDay, CommunityProfilePatch } from "@/lib/community/models/people"
import { avatarInitial } from "@/lib/community/avatar"
import type { DailyUsageMetric, ReasoningEffort } from "@alook/shared"
import { useMemo } from "react"
import { readCommunityProfile } from "@/lib/community/profile-read"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
export type BotUsageDay = {
day: string
@@ -92,10 +95,12 @@ export function useBots(): UseQueryResult<BotsResponse> & { bots: BotSummary[] }
(data) => data.bots.map((bot) => ({ ...botProfilePatch(bot), presence: bot.presence })),
),
})
- const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)
+ const profilesByUserId = useCanonicalProfilesByUserId()
const bots = useMemo(
() => (query.data?.bots ?? EMPTY_BOTS).map((bot) => {
- const profile = readCommunityProfile(profilesByUserId.get(bot.id), bot.id)
+ const canonical = profilesByUserId.get(bot.id)
+ if (!canonical) return bot
+ const profile = readCommunityProfile(canonical, bot.id)
return {
...bot,
name: profile.name,
@@ -145,8 +150,7 @@ export function useCreateBot() {
body: JSON.stringify(input),
}),
onSuccess: (data) => {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [botProfilePatch(data.bot)])
+ writeCommunityProfilePatches([botProfilePatch(data.bot)])
invalidateBotSurfaces(qc, data.bot.id)
},
})
@@ -238,8 +242,7 @@ export function useUpdateBot() {
}),
}),
onSuccess: (data) => {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [botProfilePatch(data.bot)])
+ writeCommunityProfilePatches([botProfilePatch(data.bot)])
invalidateBotSurfaces(qc, data.bot.id)
},
})
@@ -304,8 +307,7 @@ export function useUploadBotAvatar() {
return (await res.json()) as UploadBotAvatarResult
},
onSuccess: (data, variables) => {
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
+ writeCommunityProfilePatches([{
id: variables.botId,
avatar: { avatar: data.url, avatarVersion: data.avatarVersion },
}])
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 fbb4d4d31..85cbd944b 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
@@ -2,7 +2,6 @@ import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { renderHook, waitFor } from "@/test/react-dom-harness"
-import { useCommunityWsStore } from "@/stores/community/ws"
const apiFetchMock = vi.fn()
@@ -12,8 +11,6 @@ vi.mock("@/lib/api/client", () => ({
beforeEach(() => {
apiFetchMock.mockReset()
- useCommunityWsStore.getState().reset()
- useCommunityWsStore.getState().activateProfileAccount("viewer")
})
describe("useChannelMembers", () => {
@@ -50,11 +47,5 @@ describe("useChannelMembers", () => {
)
})
await waitFor(() => expect(rendered.result.current.members).toHaveLength(1))
- expect(useCommunityWsStore.getState().profilesByUserId.get("member_1")).toMatchObject({
- name: "Alice",
- discriminator: "0042",
- avatar: "A",
- avatarVersion: 4,
- })
})
})
diff --git a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
index 0f047181b..2b25e4429 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
@@ -26,6 +26,11 @@ const mocks = vi.hoisted(() => ({
},
useMessages: vi.fn(),
watermark: vi.fn(),
+ canonicalReadSnapshot: undefined as undefined | {
+ lastReadMessageId: string | null
+ lastReadAt: string
+ lastReadSeq: number
+ },
}))
vi.mock("./use-channel-read-state", () => ({
@@ -44,6 +49,9 @@ vi.mock("./use-channel-panels", () => ({
useThreads: () => ({ threads: [], isLoading: false }),
usePins: () => ({ pins: [], isLoading: false }),
}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useReadStateProjection: () => mocks.canonicalReadSnapshot,
+}))
function Capture() {
const result = useChannelMessageFeed({
@@ -55,6 +63,7 @@ function Capture() {
})
return createElement("output", {
"data-divider": result.newDividerBefore,
+ "data-anchor-found": result.anchorInCache,
"data-unread": result.unreadCount,
})
}
@@ -66,8 +75,15 @@ describe("useChannelMessageFeed", () => {
lastReadSeq: 2,
}
mocks.readState.isFetching = false
+ mocks.messages.messages = [
+ { id: "self", authorId: "viewer" },
+ { id: "authoritative-anchor", authorId: "viewer" },
+ { id: "peer", authorId: "peer" },
+ ]
+ mocks.messages.anchorReconciled = true
mocks.useMessages.mockReset()
mocks.watermark.mockReset()
+ mocks.canonicalReadSnapshot = undefined
})
it("always revalidates a mount and reconciles the authoritative server anchor", () => {
@@ -83,6 +99,45 @@ describe("useChannelMessageFeed", () => {
renderer.unmount()
})
+ it("seeds the frozen mount snapshot from the canonical read projection", () => {
+ mocks.canonicalReadSnapshot = {
+ lastReadMessageId: "authoritative-anchor",
+ lastReadAt: "2026-09-26T00:00:00.000Z",
+ lastReadSeq: 2,
+ }
+ render(createElement(Capture)).unmount()
+ expect(mocks.useMessages).toHaveBeenLastCalledWith("channel", expect.objectContaining({
+ lastReadMessageId: "authoritative-anchor",
+ }))
+ })
+
+ it("projects a warm canonical anchor before the query page marker settles", () => {
+ mocks.messages.anchorReconciled = false
+ const renderer = render(createElement(Capture))
+ const output = renderer.container.querySelector("output")!
+ expect(output).toHaveAttribute("data-divider", "peer")
+ expect(output).toHaveAttribute("data-anchor-found", "true")
+ renderer.unmount()
+ })
+
+ it("keeps an incomplete canonical window unresolved until its anchor arrives", () => {
+ mocks.messages.anchorReconciled = false
+ mocks.messages.messages = [{ id: "peer", authorId: "peer" }]
+ const renderer = render(createElement(Capture))
+ const output = () => renderer.container.querySelector("output")!
+ expect(output()).not.toHaveAttribute("data-divider")
+ expect(output()).toHaveAttribute("data-anchor-found", "false")
+
+ mocks.messages.messages = [
+ { id: "authoritative-anchor", authorId: "viewer" },
+ { id: "peer", authorId: "peer" },
+ ]
+ renderer.rerender(createElement(Capture))
+ expect(output()).toHaveAttribute("data-divider", "peer")
+ expect(output()).toHaveAttribute("data-anchor-found", "true")
+ renderer.unmount()
+ })
+
it("gates the messages request until the mount-owned server anchor resolves", () => {
mocks.readState.snapshot = null
mocks.readState.isFetching = true
diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.ts
index 7a0101e77..466127627 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.ts
@@ -5,6 +5,8 @@ import { useChannelReadStateSnapshot } from "./use-channel-read-state"
import { useChannelWatermark } from "./use-channel-watermark"
import { useMessages } from "./use-messages"
import { usePins, useThreads } from "./use-channel-panels"
+import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"
+import { useReadStateProjection } from "@/lib/community-db/projections"
export function useChannelMessageFeed({
channelId,
@@ -19,7 +21,8 @@ export function useChannelMessageFeed({
isChildChannel: boolean
anchorMessageId: string | null
}) {
- const readState = useChannelReadStateSnapshot(channelId)
+ const canonicalReadSnapshot = useReadStateProjection(channelId)
+ const readState = useChannelReadStateSnapshot(channelId, canonicalReadSnapshot)
const readSnapshot = readState.snapshot
const messagesQuery = useMessages(channelId, {
serverId,
@@ -39,26 +42,12 @@ export function useChannelMessageFeed({
})
const { newDividerBefore, anchorFound } = useMemo(() => {
if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
- if (!messagesQuery.anchorReconciled) {
- return { newDividerBefore: undefined, anchorFound: false }
- }
- const lastId = readSnapshot.lastReadMessageId
- if (!lastId) {
- for (const message of messagesQuery.messages) {
- if (message.authorId !== viewerUserId) {
- return { newDividerBefore: message.id, anchorFound: true }
- }
- }
- return { newDividerBefore: undefined, anchorFound: true }
- }
- const index = messagesQuery.messages.findIndex((message) => message.id === lastId)
- if (index === -1) return { newDividerBefore: undefined, anchorFound: false }
- for (let i = index + 1; i < messagesQuery.messages.length; i++) {
- if (messagesQuery.messages[i].authorId !== viewerUserId) {
- return { newDividerBefore: messagesQuery.messages[i].id, anchorFound: true }
- }
- }
- return { newDividerBefore: undefined, anchorFound: true }
+ return resolveMessageReadProjection({
+ messages: messagesQuery.messages,
+ lastReadMessageId: readSnapshot.lastReadMessageId,
+ viewerUserId,
+ anchorReconciled: messagesQuery.anchorReconciled,
+ })
}, [messagesQuery.anchorReconciled, messagesQuery.messages, readSnapshot, viewerUserId])
const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)
/* istanbul ignore next -- retained Chromium covers the mounted observer integration */
diff --git a/src/web/src/hooks/community/use-channel-panels.dom.test.ts b/src/web/src/hooks/community/use-channel-panels.dom.test.ts
new file mode 100644
index 000000000..340930b75
--- /dev/null
+++ b/src/web/src/hooks/community/use-channel-panels.dom.test.ts
@@ -0,0 +1,32 @@
+import { createElement, type PropsWithChildren } from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { describe, expect, it } from "vitest"
+import { renderHook } from "@/test/react-dom-harness"
+import { communityKeys } from "@/lib/query-keys"
+import { usePins, useThreads } from "./use-channel-panels"
+
+describe("usePins", () => {
+ it("exposes a stable empty list while the query is disabled", () => {
+ const queryClient = new QueryClient()
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ )
+ const rendered = renderHook(() => usePins(null), { wrapper })
+
+ expect(rendered.result.current.pins).toEqual([])
+ expect(renderHook(() => useThreads(null), { wrapper }).result.current.threads).toEqual([])
+ const disabledPins = queryClient.getQueryCache().find({
+ queryKey: communityKeys.pins("__none__"),
+ })?.options.queryFn
+ const disabledThreads = queryClient.getQueryCache().find({
+ queryKey: communityKeys.threads("__none__"),
+ })?.options.queryFn
+ expect(disabledPins).toBeTypeOf("function")
+ expect(disabledThreads).toBeTypeOf("function")
+ expect(disabledPins!({} as never)).rejects.toThrow("disabled")
+ expect(disabledThreads!({} as never)).rejects.toThrow("disabled")
+ rendered.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-channel-panels.test.ts b/src/web/src/hooks/community/use-channel-panels.test.ts
index 8429f970d..8c17972f6 100644
--- a/src/web/src/hooks/community/use-channel-panels.test.ts
+++ b/src/web/src/hooks/community/use-channel-panels.test.ts
@@ -15,7 +15,10 @@ describe("useThreads / threadsQueryFn", () => {
it("fetches from /channels/:id/threads and returns { threads }", async () => {
apiFetchMock
.mockResolvedValueOnce({ serverId: "s1", parentType: "forum", threads: [{ id: "t_1", name: "t", type: "thread", creatorId: "u1", parentMessageId: "m1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
- .mockResolvedValueOnce({ messages: [{ id: "m1", channelId: "ch_1", content: "root", seq: 1, authorId: "u1", authorName: "A", authorImage: null }], firstMessages: [] })
+ .mockResolvedValueOnce({
+ messages: [{ id: "m1", channelId: "ch_1", content: "root", seq: 1, authorId: "u1", authorName: "A", authorImage: null }],
+ firstMessages: [{ channelId: "t_1", content: "identityless preview" }],
+ })
.mockResolvedValueOnce({ tags: [] })
.mockResolvedValueOnce({ participants: [] })
const { threadsQueryFn } = await import("./use-channel-panels")
@@ -23,18 +26,19 @@ describe("useThreads / threadsQueryFn", () => {
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/threads", { signal: undefined })
expect(apiFetchMock).not.toHaveBeenCalledWith("/api/community/channels/ch_1/posts")
expect(data.threads).toHaveLength(1)
+ expect(data.threads[0]?.parent.text).toBe("identityless preview")
})
it("populates queryClient at communityKeys.threads(channelId)", async () => {
- apiFetchMock.mockResolvedValueOnce({ serverId: "s1", parentType: "text", threads: [] })
- .mockResolvedValueOnce({ messages: [], firstMessages: [] })
+ apiFetchMock.mockResolvedValueOnce({ serverId: "s1", parentType: "text", threads: [{ id: "t_1", name: "thread", type: "thread", creatorId: "u1", parentMessageId: "m_1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
+ .mockResolvedValueOnce({ messages: [{ id: "m_1", channelId: "ch_1", content: "root", seq: 1, authorId: "u1", authorName: "A", authorImage: "avatar.png" }], firstMessages: [] })
.mockResolvedValueOnce({ tags: [] })
.mockResolvedValueOnce({ participants: [] })
const { threadsQueryFn } = await import("./use-channel-panels")
const qc = new QueryClient()
const key = communityKeys.threads("ch_1")
- await qc.fetchQuery({ queryKey: key, queryFn: threadsQueryFn("ch_1") })
- expect(qc.getQueryData(key)).toEqual({ threads: [], serverId: "s1", parentType: "text", parentChannelId: "ch_1" })
+ await qc.fetchQuery({ queryKey: key, queryFn: threadsQueryFn("ch_1", qc) })
+ expect(qc.getQueryData<{ threads: unknown[] }>(key)?.threads).toHaveLength(1)
})
it("uses full opener content only for forum parents and shares one AbortSignal", async () => {
@@ -95,11 +99,33 @@ describe("usePins / pinsQueryFn", () => {
})
it("populates queryClient at communityKeys.pins(channelId)", async () => {
- apiFetchMock.mockResolvedValueOnce({ pins: [] })
+ apiFetchMock.mockResolvedValueOnce({ pins: [{ id: "m_1", type: "chat", authorId: "u1", authorName: "A", content: "pin", createdAt: "now" }] })
const { pinsQueryFn } = await import("./use-channel-panels")
const qc = new QueryClient()
const key = communityKeys.pins("ch_1")
- await qc.fetchQuery({ queryKey: key, queryFn: pinsQueryFn("ch_1") })
- expect(qc.getQueryData(key)).toEqual({ pins: [] })
+ await qc.fetchQuery({ queryKey: key, queryFn: pinsQueryFn("ch_1", qc) })
+ expect(qc.getQueryData<{ pins: unknown[] }>(key)?.pins).toHaveLength(1)
+ })
+})
+
+describe("materializeThreadsResponse", () => {
+ it("filters missing openers and projects forum and text content from canonical rows", async () => {
+ const { materializeThreadsResponse } = await import("./use-channel-panels")
+ const base = {
+ parentType: "forum" as const,
+ serverId: "s1",
+ parentChannelId: "forum_1",
+ threads: [
+ { id: "missing", name: "missing", messageCount: 0, lastMessageAt: "now", parent: { authorName: "", text: "preview" }, openerMessageId: "missing-opener" },
+ { id: "post", name: "fallback", messageCount: 1, lastMessageAt: "now", parent: { authorName: "", text: "preview" }, openerMessageId: "opener" },
+ { id: "identityless", name: "identityless", messageCount: 0, lastMessageAt: "now", parent: { authorName: "", text: "preview" } },
+ ],
+ }
+ const canonical = new Map([["opener", { id: "opener", type: "chat" as const, authorId: "u1", authorName: "A", content: "Canonical title", createdAt: "now" }]])
+
+ expect(materializeThreadsResponse(base, canonical).map(({ name }) => name))
+ .toEqual(["Canonical title", "Post"])
+ expect(materializeThreadsResponse({ ...base, parentType: "text" }, canonical)[0]?.parent.text)
+ .toBe("Canonical title")
})
})
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index 5170a2108..87bfbe643 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -1,10 +1,18 @@
"use client"
-import { useQuery, type UseQueryResult } from "@tanstack/react-query"
+import { useQuery, useQueryClient, type QueryClient, type UseQueryResult } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import type { Thread, Msg } from "@/lib/community/models/message"
+import {
+ materializeCanonicalMessages,
+ useCanonicalMessagesById,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityEmbeddedMessages,
+} from "@/lib/community-db/sync"
// Frozen empty fallbacks — see `use-servers.ts` for the rationale.
const EMPTY_THREADS: readonly Thread[] = Object.freeze([])
@@ -45,6 +53,7 @@ type BatchMessage = {
authorName: string
authorImage: string | null
}
+type FirstMessagePreview = { channelId: string; content: string }
type ParticipantRow = { channelId: string; userId: string; userName: string | null; userImage: string | null; addedAt: string; participantCount?: number }
async function loadThreadResources(channelId: string, tag?: string | null, signal?: AbortSignal) {
@@ -60,7 +69,7 @@ async function loadThreadResources(channelId: string, tag?: string | null, signa
const openerIds = threads.map((thread) => thread.parentMessageId).filter((id): id is string => !!id)
const threadIds = threads.map((thread) => thread.id)
const [messageBatch, tagBatch, participantBatch] = await Promise.all([
- apiFetch<{ messages: BatchMessage[]; firstMessages: BatchMessage[] }>("/api/community/messages/batch", {
+ apiFetch<{ messages: BatchMessage[]; firstMessages: FirstMessagePreview[] }>("/api/community/messages/batch", {
method: "POST",
body: JSON.stringify({ channelId, ids: openerIds, firstInChannelIds: threadIds }),
signal,
@@ -79,8 +88,34 @@ async function loadThreadResources(channelId: string, tag?: string | null, signa
return { threads, parentType, serverId, openerIds, ...messageBatch, ...tagBatch, ...participantBatch }
}
-export const threadsQueryFn = (channelId: string) => async ({ signal }: { signal?: AbortSignal } = {}) => {
+function batchMessageToCanonical(message: BatchMessage): Msg {
+ return {
+ id: message.id,
+ type: "chat",
+ seq: message.seq,
+ content: message.content,
+ authorId: message.authorId,
+ authorName: message.authorName,
+ ...(message.authorImage ? { authorAvatar: message.authorImage } : {}),
+ }
+}
+
+export const threadsQueryFn = (channelId: string, queryClient?: QueryClient) => async (
+ { signal }: { signal?: AbortSignal } = {},
+) => {
+ const publicationToken = queryClient
+ ? captureCommunityLiveSnapshotToken(queryClient)
+ : null
const data = await loadThreadResources(channelId, null, signal)
+ if (queryClient && publicationToken) {
+ publishCommunityEmbeddedMessages(queryClient, {
+ entries: data.messages.map((message) => ({
+ channelId: message.channelId,
+ message: batchMessageToCanonical(message),
+ })),
+ proof: { token: publicationToken, signal },
+ })
+ }
const openerMap = new Map(data.messages.map((message) => [message.id, message]))
const firstMap = new Map(data.firstMessages.map((message) => [message.channelId, message]))
return {
@@ -99,7 +134,9 @@ export const threadsQueryFn = (channelId: string) => async ({ signal }: { signal
parent: {
authorId: opener?.authorId,
authorName: opener?.authorName ?? "",
- text: (opener?.content ?? first?.content ?? "").slice(0, 100),
+ text: (data.parentType === "forum"
+ ? first?.content ?? ""
+ : opener?.content ?? first?.content ?? "").slice(0, 100),
},
...(opener ? { parentSeq: opener.seq } : {}),
...(thread.parentMessageId ? { openerMessageId: thread.parentMessageId } : {}),
@@ -111,18 +148,54 @@ export const threadsQueryFn = (channelId: string) => async ({ signal }: { signal
}
}
+export function materializeThreadsResponse(
+ data: ThreadsResponse | undefined,
+ canonicalMessages?: ReadonlyMap<string, Msg>,
+): Thread[] {
+ if (!data) return EMPTY_THREADS as Thread[]
+ if (canonicalMessages === undefined) return data.threads
+ return data.threads.flatMap((thread): Thread[] => {
+ const opener = thread.openerMessageId
+ ? canonicalMessages.get(thread.openerMessageId)
+ : undefined
+ if (thread.openerMessageId && !opener) return []
+ return [{
+ ...thread,
+ name: data.parentType === "forum"
+ ? opener?.content?.trim() ? opener.content : "Post"
+ : thread.name,
+ parent: {
+ authorId: opener?.authorId,
+ authorName: opener?.authorName ?? "",
+ // Forum firstMessages are identityless read-projection previews, not
+ // message entities. Text-thread roots have stable opener identity and
+ // therefore always read their content from canonical.
+ text: (data.parentType === "forum"
+ ? thread.parent.text
+ : opener?.content ?? "").slice(0, 100),
+ },
+ ...(opener?.seq !== undefined ? { parentSeq: opener.seq } : {}),
+ }]
+ })
+}
+
export function useThreads(channelId: string | null): UseQueryResult<ThreadsResponse> & {
threads: Thread[]
} {
+ const queryClient = useQueryClient()
+ const canonicalMessages = useCanonicalMessagesById()
const enabled = !!channelId
const query = useQuery({
queryKey: enabled ? communityKeys.threads(channelId!) : communityKeys.threads("__none__"),
- queryFn: enabled ? threadsQueryFn(channelId!) : (() => Promise.reject(new Error("disabled"))),
+ queryFn: enabled
+ ? threadsQueryFn(channelId!, queryClient)
+ : (() => Promise.reject(new Error("disabled"))),
enabled,
})
+ const threads = materializeThreadsResponse(query.data, canonicalMessages)
return {
...query,
- threads: query.data?.threads ?? (EMPTY_THREADS as Thread[]),
+ threads,
}
}
@@ -140,23 +213,42 @@ export function useForumTags(channelId: string | null, enabled: boolean) {
*/
export type PinsResponse = { pins: Msg[] }
-export const pinsQueryFn = (channelId: string) => () =>
- apiFetchProfiles<PinsResponse>(
- `/api/community/channels/${channelId}/pins`,
- (data) => messageProfilePatches(data.pins),
- )
+export const pinsQueryFn = (channelId: string, queryClient?: QueryClient) =>
+ async ({ signal }: { signal?: AbortSignal } = {}) => {
+ const publicationToken = queryClient
+ ? captureCommunityLiveSnapshotToken(queryClient)
+ : null
+ const data = await apiFetchProfiles<PinsResponse>(
+ `/api/community/channels/${channelId}/pins`,
+ (response) => messageProfilePatches(response.pins),
+ signal ? { signal } : undefined,
+ )
+ if (queryClient && publicationToken) {
+ publishCommunityEmbeddedMessages(queryClient, {
+ entries: data.pins.map((message) => ({ channelId, message })),
+ proof: { token: publicationToken, signal },
+ })
+ }
+ return data
+ }
export function usePins(channelId: string | null): UseQueryResult<PinsResponse> & {
pins: Msg[]
} {
+ const queryClient = useQueryClient()
+ const canonicalMessages = useCanonicalMessagesById()
const enabled = !!channelId
const query = useQuery({
queryKey: enabled ? communityKeys.pins(channelId!) : communityKeys.pins("__none__"),
- queryFn: enabled ? pinsQueryFn(channelId!) : (() => Promise.reject(new Error("disabled"))),
+ queryFn: enabled
+ ? pinsQueryFn(channelId!, queryClient)
+ : (() => Promise.reject(new Error("disabled"))),
enabled,
})
return {
...query,
- pins: query.data?.pins ?? (EMPTY_PINS as Msg[]),
+ pins: query.data?.pins
+ ? materializeCanonicalMessages(query.data.pins, canonicalMessages)
+ : (EMPTY_PINS as Msg[]),
}
}
diff --git a/src/web/src/hooks/community/use-channel-read-state.test.ts b/src/web/src/hooks/community/use-channel-read-state.test.ts
index fa18ae73d..a0ab06683 100644
--- a/src/web/src/hooks/community/use-channel-read-state.test.ts
+++ b/src/web/src/hooks/community/use-channel-read-state.test.ts
@@ -130,6 +130,31 @@ describe("useChannelReadStateSnapshot — freeze invariant", () => {
})
})
+ it("freezes a canonical snapshot immediately while the mount request revalidates", async () => {
+ const useHook = await loadHook()
+ queryReturn = { data: undefined, isFetching: true }
+ const canonical = {
+ lastReadMessageId: "m_cached",
+ lastReadAt: "2026-07-01T00:00:00.000Z",
+ lastReadSeq: 10,
+ }
+ const warm = useHook("ch_1", canonical)
+ flushEffects()
+ expect(warm).toEqual({ snapshot: canonical, isFetching: false })
+
+ refCounter = 0
+ pendingEffects = []
+ queryReturn = {
+ data: {
+ lastReadMessageId: "m_fresh",
+ lastReadAt: "2026-07-02T00:00:00.000Z",
+ lastReadSeq: 20,
+ },
+ isFetching: false,
+ }
+ expect(useHook("ch_1").snapshot).toEqual(canonical)
+ })
+
it("freezes the snapshot — a subsequent 'refetch' with a NEW value must NOT change what the hook returns", async () => {
const useHook = await loadHook()
diff --git a/src/web/src/hooks/community/use-channel-read-state.ts b/src/web/src/hooks/community/use-channel-read-state.ts
index b6a9d8000..359a5895a 100644
--- a/src/web/src/hooks/community/use-channel-read-state.ts
+++ b/src/web/src/hooks/community/use-channel-read-state.ts
@@ -41,7 +41,10 @@ export type ChannelReadStateSnapshot = {
* before that eviction timer runs. The next snapshot therefore comes from
* the current server response rather than the pre-scroll pointer.
*/
-export function useChannelReadStateSnapshot(channelId: string | null | undefined): {
+export function useChannelReadStateSnapshot(
+ channelId: string | null | undefined,
+ canonicalSnapshot?: ChannelReadStateSnapshot,
+): {
snapshot: ChannelReadStateSnapshot | null
isFetching: boolean
} {
@@ -72,10 +75,15 @@ export function useChannelReadStateSnapshot(channelId: string | null | undefined
retry: 1,
})
- // Latch the first resolved snapshot so subsequent renders return a stable
- // reference. Reset on channelId change — a new channel mount is a new
- // snapshot lifecycle. Must reset synchronously during render so the
- // returned snapshot never belongs to the previous channel.
+ // Latch the first available snapshot so subsequent renders return a stable
+ // reference. A canonical row restored with the message window is a complete
+ // warm projection and may render immediately while this query revalidates
+ // in the background. Its response updates canonical state for later mounts;
+ // it must never walk this mount's divider.
+ //
+ // Reset on channelId change — a new channel mount is a new snapshot
+ // lifecycle. Must reset synchronously during render so the returned
+ // snapshot never belongs to the previous channel.
const snapshotRef = useRef<ChannelReadStateSnapshot | null>(null)
const lastChannelIdRef = useRef<string | null | undefined>(channelId)
/* eslint-disable react-hooks/refs -- sync channel switch reset; see hook tests */
@@ -83,6 +91,9 @@ export function useChannelReadStateSnapshot(channelId: string | null | undefined
snapshotRef.current = null
lastChannelIdRef.current = channelId
}
+ if (snapshotRef.current === null && canonicalSnapshot) {
+ snapshotRef.current = canonicalSnapshot
+ }
/* eslint-enable react-hooks/refs */
useEffect(() => {
if (snapshotRef.current !== null) return
@@ -93,7 +104,7 @@ export function useChannelReadStateSnapshot(channelId: string | null | undefined
/* eslint-disable react-hooks/refs -- latched snapshot read; see hook tests */
return {
snapshot: snapshotRef.current ?? (!query.isFetching ? (query.data ?? null) : null),
- isFetching: query.isFetching,
+ isFetching: snapshotRef.current === null && query.isFetching,
}
/* eslint-enable react-hooks/refs */
}
diff --git a/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts
index be2a8c4b2..0a3fc9a6e 100644
--- a/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts
@@ -4,10 +4,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
const apiFetch = vi.fn()
+const dbProjection = vi.hoisted(() => ({ current: undefined as unknown }))
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetch(...args),
}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useChannelRefDirectoryProjection: () => dbProjection.current,
+ useOptionalCommunityDbRegistry: () => dbProjection.current === undefined ? null : {},
+}))
import { createQueryClient } from "@/lib/query-client"
import { communityKeys } from "@/lib/query-keys"
@@ -63,6 +68,7 @@ describe("channelRefDirectoryQueryFn", () => {
describe("useChannelRefDirectory", () => {
beforeEach(() => {
vi.clearAllMocks()
+ dbProjection.current = undefined
useCommunityWsStore.getState().reset()
})
@@ -70,73 +76,6 @@ describe("useChannelRefDirectory", () => {
act(() => useCommunityWsStore.getState().reset())
})
- it("keeps a rail-only structural snapshot pending until the live directory resolves", () => {
- useCommunityWsStore.getState().activateProfileAccount("viewer_1")
- apiFetch.mockReturnValue(new Promise(() => {}))
- const client = createQueryClient()
- client.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "viewer_1",
- capturedAt: Date.now(),
- serverOrder: ["server_1"],
- folders: [],
- servers: [{
- id: "server_1",
- name: "Studio",
- discriminator: "0042",
- icon: null,
- categories: [],
- channels: [],
- childRouteHints: [],
- }],
- })
-
- const rendered = renderDirectory(client, true)
-
- expect(rendered.result.current).toMatchObject({
- directory: [],
- isResolved: false,
- isLoading: true,
- isError: false,
- })
- })
-
- it("uses a captured structural channel directory while the live query is disabled", () => {
- useCommunityWsStore.getState().activateProfileAccount("viewer_1")
- const client = createQueryClient()
- client.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "viewer_1",
- capturedAt: Date.now(),
- serverOrder: ["server_1"],
- folders: [],
- servers: [{
- id: "server_1",
- name: "Studio",
- discriminator: "0042",
- icon: null,
- categories: [],
- channels: [{ id: "channel_1", name: "general", type: "text", categoryId: null }],
- childRouteHints: [],
- }],
- })
-
- const rendered = renderDirectory(client, false)
-
- expect(apiFetch).not.toHaveBeenCalled()
- expect(rendered.result.current).toMatchObject({
- directory: [{
- id: "server_1",
- name: "Studio",
- discriminator: "0042",
- channels: [{ id: "channel_1", name: "general" }],
- }],
- isResolved: true,
- isLoading: false,
- isError: false,
- })
- })
-
it("stays dormant until enabled, then owns pending and resolved items", async () => {
const request = deferred<{ directory: Array<{
id: string
@@ -249,6 +188,102 @@ describe("useChannelRefDirectory", () => {
expect(apiFetch).not.toHaveBeenCalled()
})
+ it("keeps the account-scoped warm request alive after its popup observer unmounts", async () => {
+ const request = deferred<{ directory: Array<{
+ id: string
+ name: string
+ discriminator: string
+ channels: Array<{ id: string; name: string }>
+ }> }>()
+ apiFetch.mockReturnValue(request.promise)
+ const client = createQueryClient()
+ const first = renderDirectory(client, true)
+
+ expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/channel-directory")
+ first.unmount()
+
+ const directory = [{
+ id: "server_1",
+ name: "Studio",
+ discriminator: "0042",
+ channels: [{ id: "channel_1", name: "general" }],
+ }]
+ await act(async () => request.resolve({ directory }))
+ await waitFor(() => expect(
+ client.getQueryData(communityKeys.channelRefDirectory()),
+ ).toEqual(directory))
+
+ const second = renderDirectory(client, true)
+ expect(second.result.current).toMatchObject({
+ directory,
+ isResolved: true,
+ isLoading: false,
+ isError: false,
+ })
+ expect(apiFetch).toHaveBeenCalledOnce()
+ })
+
+ it("resolves from canonical channels while the transport query is dormant", () => {
+ const directory = [{
+ id: "server_db",
+ name: "Canonical",
+ discriminator: "0001",
+ channels: [{ id: "channel_db", name: "chat" }],
+ }]
+ dbProjection.current = directory
+
+ const rendered = renderDirectory(createQueryClient(), false)
+
+ expect(rendered.result.current).toMatchObject({
+ directory,
+ isResolved: true,
+ isLoading: false,
+ isError: false,
+ })
+ expect(apiFetch).not.toHaveBeenCalled()
+ })
+
+ it("keeps a canonical server with no channels unresolved while HTTP is stalled", () => {
+ dbProjection.current = [{
+ id: "server_db",
+ name: "Canonical",
+ discriminator: "0001",
+ channels: [],
+ }]
+ apiFetch.mockReturnValue(new Promise(() => {}))
+
+ const rendered = renderDirectory(createQueryClient(), true)
+
+ expect(rendered.result.current).toMatchObject({
+ directory: [],
+ isResolved: false,
+ isLoading: true,
+ isError: false,
+ })
+ expect(apiFetch).toHaveBeenCalledOnce()
+ })
+
+ it("keeps an invalidated empty success pending while its refresh is stalled", () => {
+ dbProjection.current = []
+ apiFetch.mockReturnValue(new Promise(() => {}))
+ const client = createQueryClient()
+ client.setQueryData(communityKeys.channelRefDirectory(), [])
+ void client.invalidateQueries({
+ queryKey: communityKeys.channelRefDirectory(),
+ refetchType: "none",
+ })
+
+ const rendered = renderDirectory(client, true)
+
+ expect(rendered.result.current).toMatchObject({
+ directory: [],
+ isResolved: false,
+ isLoading: true,
+ isError: false,
+ })
+ expect(apiFetch).toHaveBeenCalledOnce()
+ })
+
it("keeps cached rows resolved through a failed background refetch", async () => {
const directory = [{
id: "server_1",
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 025301021..20d2d88fe 100644
--- a/src/web/src/hooks/community/use-channel-ref-directory.ts
+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts
@@ -1,12 +1,20 @@
"use client"
-import { useQuery } from "@tanstack/react-query"
+import {
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
-import { structuralSnapshotDirectory } from "@/lib/community/structural-snapshot"
-import { useStructuralSnapshot } from "./use-structural-snapshot"
-import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ useChannelRefDirectoryProjection,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityChannelDirectory,
+} from "@/lib/community-db/sync"
const EMPTY_DIRECTORY = Object.freeze([]) as unknown as ChannelRefDirectory
@@ -24,28 +32,43 @@ export function useChannelRefDirectory(enabled = true): {
isError: boolean
refetch: ReturnType<typeof useQuery<ChannelRefDirectory>>["refetch"]
} {
- const accountId = useCommunityWsStore((state) => state.profileViewerId)
- const structuralSnapshot = useStructuralSnapshot(accountId)
+ const registry = useOptionalCommunityDbRegistry()
+ const queryClient = useQueryClient()
+ const dbDirectory = useChannelRefDirectoryProjection()
const query = useQuery<ChannelRefDirectory>({
queryKey: communityKeys.channelRefDirectory(),
- queryFn: channelRefDirectoryQueryFn,
+ // This account-scoped directory warms every composer, so its owner is the
+ // QueryClient rather than the popup observer that happened to start it.
+ // Let an in-flight request finish across popup/route unmounts; the live
+ // snapshot token still rejects account/access changes before publication.
+ queryFn: async () => {
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ const directory = await channelRefDirectoryQueryFn()
+ publishCommunityChannelDirectory(queryClient, {
+ directory,
+ proof: { token, signal: undefined },
+ })
+ return directory
+ },
enabled,
staleTime: Infinity,
refetchOnReconnect: true,
retry: false,
})
- const structuralDirectory = structuralSnapshotDirectory(structuralSnapshot)
- const directory = query.data ?? structuralDirectory
- // A server-list receipt creates rail identities before any server detail
- // tree has been loaded. An empty directory from that partial hint is not an
- // authoritative "no channels" result and must not suppress the live
- // directory's pending/error state.
- const hasStructuralChannels = structuralDirectory.some((server) => server.channels.length > 0)
- const isResolved = query.data !== undefined || hasStructuralChannels
+ const directory = registry
+ ? dbDirectory ?? EMPTY_DIRECTORY
+ : query.data ?? EMPTY_DIRECTORY
+ const hasCanonicalChannels = dbDirectory?.some((server) => server.channels.length > 0) ?? false
+ const isResolved = registry
+ ? hasCanonicalChannels || (query.isSuccess && !query.isFetching)
+ : query.data !== undefined
return {
directory: isResolved ? directory : EMPTY_DIRECTORY,
isResolved,
- isLoading: enabled && !isResolved && query.isFetching,
+ // Enabling the query and React Query publishing `isFetching` are separate
+ // renders. Keep the unresolved surface pending across that handoff instead
+ // of briefly exposing a false empty state.
+ isLoading: enabled && !isResolved && !query.isError,
isError: enabled && !isResolved && query.isError,
refetch: query.refetch,
}
diff --git a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
index 5ffa8bbf9..f8fa6c41b 100644
--- a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
@@ -133,17 +133,30 @@ describe("unresolved metadata terminal error and retry", () => {
expect(mocks.replace).not.toHaveBeenCalled()
})
- it.each([401, 403, 404])("preserves the existing %s exit instead of offering metadata Retry", async (status) => {
+ it.each([401, 403, 404])("exits on the first authoritative %s instead of retrying or offering metadata Retry", async (status) => {
mocks.apiFetch.mockRejectedValue(new ApiError("denied", status))
await mount()
await until(() => current.routeLifecycle === "terminal-error")
expect(current.metadataError).toBe(false)
await current.retryMetadata()
- expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ expect(mocks.apiFetch).toHaveBeenCalledOnce()
if (status === 401) expect(mocks.replace).not.toHaveBeenCalled()
else expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1")
})
+ it("does not let a late missing-metadata response overwrite newer navigation", async () => {
+ const request = deferred()
+ mocks.apiFetch.mockReturnValueOnce(request.promise)
+ await mount()
+ await until(() => mocks.apiFetch.mock.calls.length === 1)
+
+ act(() => useCommunityStore.getState().setCurrentChannelId(null))
+ await act(async () => request.reject(new ApiError("missing", 404)))
+ await until(() => current.routeLifecycle === "terminal-error")
+
+ expect(mocks.replace).not.toHaveBeenCalled()
+ })
+
it.each([0, 500])("keeps a verified thread ready through disconnect, failed %s revalidation, and recovery", async (status) => {
mocks.apiFetch.mockResolvedValue(payload())
await mount()
@@ -225,8 +238,7 @@ describe("unresolved metadata terminal error and retry", () => {
await act(async () => {
if (change === "account") renderer!.rerender(tree({ accountId: "viewer-2" }))
else {
- useCommunityWsStore.getState().markAccessDisconnected()
- useCommunityWsStore.getState().markAccessConnected()
+ useCommunityWsStore.setState((state) => ({ accessEpoch: state.accessEpoch + 1 }))
}
})
expect(current.retryingMetadata).toBe(false)
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 f6b3f1508..5ba4e2c5f 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
@@ -3,7 +3,6 @@ import { QueryClient } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, render } from "@/test/react-dom-harness"
import { useCommunityStore } from "@/stores/community"
-import { communityKeys } from "@/lib/query-keys"
const mocks = vi.hoisted(() => ({
subscribe: vi.fn(),
@@ -19,6 +18,9 @@ const mocks = vi.hoisted(() => ({
isVerified: false,
isError: false,
},
+ dbChannel: undefined as undefined | Record<string, unknown>,
+ communityDb: { current: {} as Record<string, unknown> | null },
+ purgeCommunityChannel: vi.fn(),
}))
const queryClient = new QueryClient()
@@ -34,7 +36,14 @@ vi.mock("./use-servers", () => ({
useServer: () => ({ server: mocks.server }),
}))
vi.mock("./use-child-channel-meta", () => ({
- useChildChannelMeta: () => mocks.metaQuery,
+ useChildChannelMeta: (
+ _serverId: string,
+ _channelId: string,
+ _enabled: boolean,
+ placeholderData?: Record<string, unknown>,
+ ) => placeholderData && !mocks.metaQuery.isVerified
+ ? { ...mocks.metaQuery, data: placeholderData, isVerified: true }
+ : mocks.metaQuery,
}))
vi.mock("./use-community-ws", () => ({
communityWsSubscribe: (...args: unknown[]) => mocks.subscribe(...args),
@@ -49,6 +58,15 @@ vi.mock("@/lib/community/last-community-route", () => ({
COMMUNITY_COLD_ENTRY_FALLBACK: "/c/me/machines",
consumeCommunityColdEntryFailure: (...args: unknown[]) => mocks.consumeColdEntryFailure(...args),
}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useOptionalCommunityDbRegistry: () => mocks.communityDb.current,
+ useRouteChannelProjection: () => mocks.dbChannel,
+}))
+vi.mock("@/lib/community-db/sync", () => ({
+ purgeCommunityChannel: (...args: unknown[]) => mocks.purgeCommunityChannel(...args),
+ patchCanonicalCommunityChannel: vi.fn(() => true),
+ removeCanonicalCommunityChannel: vi.fn(),
+}))
import { buildChannelRouteModel, useChannelRouteModel } from "./use-channel-route-model"
@@ -65,6 +83,7 @@ function lifecycle(renderer: ReturnType<typeof render>) {
}
beforeEach(() => {
+ queryClient.clear()
useCommunityStore.getState().reset()
mocks.subscribe.mockClear()
mocks.unsubscribe.mockClear()
@@ -72,6 +91,8 @@ beforeEach(() => {
mocks.clearLastChannel.mockClear()
mocks.consumeColdEntryFailure.mockReset()
mocks.consumeColdEntryFailure.mockReturnValue(false)
+ mocks.communityDb.current = {}
+ mocks.purgeCommunityChannel.mockClear()
mocks.lastChannel = null
mocks.server = {
id: "server-1",
@@ -81,6 +102,7 @@ beforeEach(() => {
}],
}
mocks.metaQuery = { data: undefined, error: null, isVerified: false, isError: false }
+ mocks.dbChannel = undefined
})
afterEach(() => {
@@ -112,37 +134,6 @@ describe("useChannelRouteModel subscription ownership", () => {
act(() => renderer!.unmount())
})
- it("uses persisted structure only to choose the pending skeleton subtype", () => {
- mocks.server = undefined
- queryClient.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "viewer-1",
- capturedAt: Date.now(),
- serverOrder: ["server-1"],
- folders: [],
- servers: [{
- id: "server-1",
- name: "Server",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [{ id: "forum-1", name: "Forum", type: "forum", categoryId: null }],
- childRouteHints: [],
- }],
- })
-
- let renderer!: ReturnType<typeof render>
- act(() => {
- renderer = render(React.createElement(Harness, { channelId: "forum-1" }))
- })
-
- const node = renderer.container.querySelector("span")
- expect(node?.getAttribute("data-lifecycle")).toBe("pending")
- expect(node?.getAttribute("data-skeleton-subtype")).toBe("forum")
- expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
- act(() => renderer.unmount())
- })
-
it("reports the live top-level text subtype after access is ready", () => {
mocks.server = {
id: "server-1",
@@ -160,6 +151,43 @@ describe("useChannelRouteModel subscription ownership", () => {
act(() => renderer.unmount())
})
+ it.each(["forum", "text", "thread"] as const)(
+ "uses the canonical %s subtype while the route is pending",
+ (type) => {
+ mocks.server = undefined
+ mocks.dbChannel = { id: "post-1", type }
+
+ const renderer = render(React.createElement(Harness))
+
+ expect(renderer.container.querySelector("span")?.getAttribute("data-skeleton-subtype"))
+ .toBe(type)
+ act(() => renderer.unmount())
+ },
+ )
+
+ it("hydrates a canonical thread placeholder with nullable child fields", () => {
+ mocks.dbChannel = {
+ id: "post-1",
+ serverId: "server-1",
+ name: "Post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: undefined,
+ archived: false,
+ lastMessageAt: undefined,
+ }
+
+ const renderer = render(React.createElement(Harness))
+
+ expect(renderer.container.querySelector("span")).toHaveAttribute("data-lifecycle", "ready")
+ expect(useCommunityStore.getState().currentChannelMeta).toMatchObject({
+ creatorId: null,
+ activityAt: "",
+ })
+ act(() => renderer.unmount())
+ })
+
it("does not hydrate a verified child with the previous child's store metadata", () => {
const model = buildChannelRouteModel(
{
@@ -224,6 +252,38 @@ describe("useChannelRouteModel subscription ownership", () => {
expect(mocks.unsubscribe).toHaveBeenCalledTimes(1)
})
+ it("does not republish equivalent verified metadata with a new object reference", () => {
+ const meta = {
+ id: "post-1",
+ serverId: "server-1",
+ name: "Post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ archived: false,
+ activityAt: "2026-08-09T00:00:00.000Z",
+ verifiedEpoch: 0,
+ }
+ mocks.metaQuery = { data: meta, error: null, isVerified: true, isError: false }
+ const storeListener = vi.fn()
+ const unsubscribeStore = useCommunityStore.subscribe(storeListener)
+ const renderer = render(React.createElement(Harness))
+ const writesAfterFirstPublish = storeListener.mock.calls.length
+
+ mocks.metaQuery = {
+ data: { ...meta },
+ error: null,
+ isVerified: true,
+ isError: false,
+ }
+ act(() => renderer.rerender(React.createElement(Harness)))
+
+ expect(storeListener).toHaveBeenCalledTimes(writesAfterFirstPublish)
+ unsubscribeStore()
+ act(() => renderer.unmount())
+ })
+
it("exposes terminal-error only after the child metadata query errors", () => {
mocks.metaQuery = {
data: undefined,
@@ -266,6 +326,7 @@ describe("useChannelRouteModel subscription ownership", () => {
expect(mocks.clearLastChannel).toHaveBeenCalledWith("server-1")
expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1")
+ expect(mocks.purgeCommunityChannel).toHaveBeenCalledWith(mocks.communityDb.current, "post-1")
expect(mocks.subscribe).toHaveBeenCalledTimes(1)
expect(mocks.unsubscribe).not.toHaveBeenCalled()
diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.ts
index 70b74f287..46b714cee 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { isForum as isForumType } from "@alook/shared"
import { useServer } from "./use-servers"
-import { useCommunityStore, useCurrentChannelMeta } from "@/stores/community"
+import { useCommunityStore } from "@/stores/community"
import { toastApiError } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { useCommunityWsStore } from "@/stores/community/ws"
@@ -21,11 +21,12 @@ import {
removeForumSidebarThreadExact,
removeForumSidebarUnreadChild,
} from "./use-forum-sidebar-threads"
-import { useStructuralSnapshot } from "./use-structural-snapshot"
-import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"
+import { useRouteChannelProjection } from "@/lib/community-db/projections"
+import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
+import { purgeCommunityChannel } from "@/lib/community-db/sync"
type Server = ReturnType<typeof useServer>["server"]
-type ChannelMeta = ReturnType<typeof useCurrentChannelMeta>
+type ChannelMeta = NonNullable<ReturnType<typeof useChildChannelMeta>["data"]> | null
export function buildChannelRouteModel(
server: Server,
@@ -68,18 +69,32 @@ export function useChannelRouteModel(
) {
const router = useRouter()
const queryClient = useQueryClient()
+ const communityDb = useOptionalCommunityDbRegistry()
const { server } = useServer(serverId)
- const structuralSnapshot = useStructuralSnapshot(accountId, queryClient)
- const structuralServer = structuralSnapshot?.servers.find((candidate) => candidate.id === serverId)
- const structuralTopLevel = structuralServer?.channels.find((candidate) => candidate.id === channelId)
- const structuralChild = structuralServer?.childRouteHints.find((candidate) => candidate.id === channelId)
- const currentChannelMeta = useCurrentChannelMeta()
+ const dbChannel = useRouteChannelProjection(channelId)
+ const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const topLevelChannel = server?.categories
?.flatMap((category) => category.channels)
.some((candidate) => candidate.id === channelId)
const isChild = !!server?.categories && !topLevelChannel
- const metaQuery = useChildChannelMeta(serverId, channelId, isChild)
- const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
+ const cachedChildMeta = useMemo(() => dbChannel?.type === "thread"
+ && dbChannel.parentChannelId
+ && dbChannel.parentMessageId ? {
+ id: dbChannel.id,
+ serverId,
+ name: dbChannel.name,
+ type: dbChannel.type,
+ parentChannelId: dbChannel.parentChannelId,
+ parentMessageId: dbChannel.parentMessageId,
+ creatorId: dbChannel.creatorId ?? null,
+ archived: dbChannel.archived,
+ activityAt: dbChannel.lastMessageAt ?? "",
+ verifiedEpoch: accessEpoch,
+ } : undefined, [accessEpoch, dbChannel, serverId])
+ const metaQuery = useChildChannelMeta(serverId, channelId, isChild, cachedChildMeta)
+ const renderableChannelMeta = isChild && metaQuery.isVerified
+ ? (metaQuery.data ?? null)
+ : cachedChildMeta ?? null
const retryScope = JSON.stringify([accountId, serverId, channelId, accessEpoch])
const retryAttemptRef = useRef<{ scope: string } | null>(null)
const [retryAttempt, setRetryAttempt] = useState<{ scope: string } | null>(null)
@@ -104,13 +119,13 @@ export function useChannelRouteModel(
const model = useMemo(
() => buildChannelRouteModel(
server,
- currentChannelMeta,
+ renderableChannelMeta,
channelId,
isChild
? { channelId, settled: metaQuery.isVerified }
: { channelId, settled: true },
),
- [channelId, currentChannelMeta, isChild, metaQuery.isVerified, server],
+ [channelId, isChild, metaQuery.isVerified, renderableChannelMeta, server],
)
const routeLifecycle = !server?.categories
? "pending" as const
@@ -127,8 +142,13 @@ export function useChannelRouteModel(
: model.isForum
? "forum" as const
: "text" as const
- : structuralTopLevel?.type
- ?? (structuralChild ? "thread" as const : "unknown" as const)
+ : dbChannel?.type === "forum"
+ ? "forum" as const
+ : dbChannel?.type === "text"
+ ? "text" as const
+ : dbChannel?.type === "thread"
+ ? "thread" as const
+ : "unknown" as const
useEffect(() => {
useCommunityStore.getState().setCurrentChannelId(channelId)
return () => { useCommunityStore.getState().setCurrentChannelId(null) }
@@ -144,18 +164,20 @@ export function useChannelRouteModel(
}
const denied = isDefinitiveChildMetaFailure(metaQuery.error)
if (denied || metaQuery.data?.archived) {
- useCommunityStore.getState().setCurrentChannelMeta(null)
+ const store = useCommunityStore.getState()
+ const routeStillCurrent = store.currentChannelId === channelId
+ store.setCurrentChannelMeta(null)
removeForumSidebarUnreadChild(queryClient, serverId, channelId)
removeForumSidebarThreadExact(queryClient, serverId, channelId)
- updateStructuralSnapshot(queryClient, {
- type: "removeChildHint",
- serverId,
- channelId,
- })
+ if (communityDb) purgeCommunityChannel(communityDb, channelId)
const lastChannel = getLastChannel(serverId)
if (lastChannel === channelId) {
clearLastChannel(serverId)
}
+ // A top-level delete clears the live pointer and starts its survivor
+ // navigation before this fallback metadata request can settle. Do not
+ // let the late 403/404 supersede that newer navigation with the root.
+ if (!routeStillCurrent) return
const destination = consumeCommunityColdEntryFailure(
accountId,
`/c/channels/${serverParam}/${channelId}`,
@@ -169,7 +191,7 @@ export function useChannelRouteModel(
useCommunityStore.getState().setCurrentChannelMeta(null)
toastApiError(metaQuery.error, "Failed to load thread")
}
- }, [accountId, channelId, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])
+ }, [accountId, channelId, communityDb, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])
return {
...model,
routeLifecycle,
diff --git a/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts b/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts
index aba07f653..02a967c08 100644
--- a/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts
+++ b/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts
@@ -5,13 +5,24 @@ import { renderHook, waitFor } from "@/test/react-dom-harness"
import type { ChildChannelMeta } from "./use-forum-sidebar-threads"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { ApiError } from "@/lib/errors"
const apiFetchMock = vi.hoisted(() => vi.fn())
+const projectedChannel = vi.hoisted(() => ({ current: undefined as undefined | Record<string, unknown> }))
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useRouteChannelProjection: () => projectedChannel.current,
+ useOptionalCommunityDbRegistry: () => projectedChannel.current === undefined ? null : {},
+}))
-import { pickRenderableChildMeta, useChildChannelMeta } from "./use-child-channel-meta"
+import {
+ pickRenderableChildMeta,
+ sameChildChannelMeta,
+ updateTrustedChildMeta,
+ useChildChannelMeta,
+} from "./use-child-channel-meta"
const meta = (overrides: Partial<ChildChannelMeta> = {}): ChildChannelMeta => ({
id: "post-1",
@@ -43,9 +54,18 @@ beforeEach(() => {
})
useCommunityWsStore.getState().reset()
useCommunityWsStore.getState().markAccessConnected()
+ projectedChannel.current = undefined
})
describe("child channel metadata stale rendering", () => {
+ it("compares every durable child metadata field", () => {
+ const left = meta()
+ expect(sameChildChannelMeta(left, { ...left })).toBe(true)
+ expect(sameChildChannelMeta(left, { ...left, verifiedEpoch: 3 })).toBe(false)
+ const trusted = { channelId: left.id, meta: left }
+ expect(updateTrustedChildMeta(trusted, left.id, { ...left })).toBe(trusted)
+ })
+
it("keeps a previously authorized snapshot renderable across a WS epoch", () => {
const trusted = meta({ verifiedEpoch: 2 })
expect(pickRenderableChildMeta(trusted, trusted, 3)).toBe(trusted)
@@ -82,4 +102,119 @@ describe("child channel metadata stale rendering", () => {
communityKeys.channelMeta("server-1", "post-1"),
)).toMatchObject({ id: "post-1", parentChannelId: "forum-1" })
})
+
+ it("renders a current-account structural placeholder while exact metadata revalidates", async () => {
+ apiFetchMock.mockImplementation(() => new Promise(() => {}))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ )
+ const cached = meta({ verifiedEpoch: useCommunityWsStore.getState().accessEpoch })
+ const rendered = renderHook(
+ () => useChildChannelMeta("server-1", "post-1", true, cached),
+ { wrapper },
+ )
+
+ expect(rendered.result.current).toMatchObject({
+ data: cached,
+ isVerified: true,
+ isPlaceholderData: true,
+ })
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ rendered.unmount()
+ })
+
+ it("builds a structural placeholder from a complete canonical thread row", async () => {
+ apiFetchMock.mockImplementation(() => new Promise(() => {}))
+ projectedChannel.current = {
+ id: "post-1",
+ serverId: "server-1",
+ name: "post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: undefined,
+ archived: false,
+ lastMessageAt: undefined,
+ }
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ )
+
+ const rendered = renderHook(
+ () => useChildChannelMeta("server-1", "post-1", true),
+ { wrapper },
+ )
+
+ expect(rendered.result.current).toMatchObject({
+ data: { creatorId: null, activityAt: "" },
+ isVerified: true,
+ isPlaceholderData: false,
+ })
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ rendered.unmount()
+ })
+
+ it("does not retry terminal metadata failures before route ejection", async () => {
+ apiFetchMock.mockRejectedValue(new ApiError("missing", 404))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retryDelay: 0 } } })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ )
+ const rendered = renderHook(
+ () => useChildChannelMeta("server-1", "post-1", true),
+ { wrapper },
+ )
+
+ await waitFor(() => expect(rendered.result.current.isError).toBe(true))
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ })
+
+ it("retries one transient metadata failure", async () => {
+ apiFetchMock.mockRejectedValue(new Error("offline"))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retryDelay: 0 } } })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ )
+ const rendered = renderHook(
+ () => useChildChannelMeta("server-1", "post-1", true),
+ { wrapper },
+ )
+
+ await waitFor(() => expect(rendered.result.current.isError).toBe(true))
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ })
+
+ it("preserves the trusted object when an exact refetch returns identical metadata", async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, structuralSharing: false } },
+ })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ )
+ const rendered = renderHook(
+ () => useChildChannelMeta("server-1", "post-1", true),
+ { wrapper },
+ )
+ await waitFor(() => expect(rendered.result.current.isVerified).toBe(true))
+ const trusted = rendered.result.current.data
+
+ await queryClient.refetchQueries({
+ queryKey: communityKeys.channelMeta("server-1", "post-1"),
+ exact: true,
+ })
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ expect(rendered.result.current.data).toStrictEqual(trusted)
+ })
})
diff --git a/src/web/src/hooks/community/use-child-channel-meta.ts b/src/web/src/hooks/community/use-child-channel-meta.ts
index 7f5441662..1044aeab1 100644
--- a/src/web/src/hooks/community/use-child-channel-meta.ts
+++ b/src/web/src/hooks/community/use-child-channel-meta.ts
@@ -1,11 +1,20 @@
"use client"
-import { useQuery } from "@tanstack/react-query"
+import { useQuery, useQueryClient } from "@tanstack/react-query"
import { useEffect, useState } from "react"
import { fetchChannelMetadata, type ChannelMetadata } from "@/hooks/community/channel-metadata"
import { communityKeys } from "@/lib/query-keys"
import type { ChildChannelMeta } from "@/hooks/community/use-forum-sidebar-threads"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { ApiError } from "@/lib/errors"
+import {
+ useOptionalCommunityDbRegistry,
+ useRouteChannelProjection,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityChannelMetadata,
+} from "@/lib/community-db/sync"
function projectChildMeta(payload: ChannelMetadata, verifiedEpoch: number): ChildChannelMeta {
if (!payload.parentChannelId || !payload.parentMessageId) {
@@ -25,6 +34,34 @@ function projectChildMeta(payload: ChannelMetadata, verifiedEpoch: number): Chil
}
}
+export function sameChildChannelMeta(left: ChildChannelMeta, right: ChildChannelMeta): boolean {
+ return left.id === right.id &&
+ left.serverId === right.serverId &&
+ left.name === right.name &&
+ left.type === right.type &&
+ left.parentChannelId === right.parentChannelId &&
+ left.parentMessageId === right.parentMessageId &&
+ (left.creatorId ?? null) === (right.creatorId ?? null) &&
+ left.archived === right.archived &&
+ left.activityAt === right.activityAt &&
+ left.verifiedEpoch === right.verifiedEpoch
+}
+
+type TrustedChildMeta = { channelId: string; meta: ChildChannelMeta } | null
+
+export function updateTrustedChildMeta(
+ current: TrustedChildMeta,
+ channelId: string,
+ data: ChildChannelMeta,
+): TrustedChildMeta {
+ if (data.archived) return current === null ? current : null
+ if (
+ current?.channelId === channelId
+ && sameChildChannelMeta(current.meta, data)
+ ) return current
+ return { channelId, meta: data }
+}
+
export function pickRenderableChildMeta(
meta: ChildChannelMeta | undefined,
trusted: ChildChannelMeta | undefined,
@@ -39,28 +76,58 @@ export function useChildChannelMeta(
serverId: string,
channelId: string,
enabled: boolean,
+ placeholderData?: ChildChannelMeta,
) {
+ const registry = useOptionalCommunityDbRegistry()
+ const queryClient = useQueryClient()
+ const dbChannel = useRouteChannelProjection(channelId)
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
+ const dbPlaceholder = dbChannel?.type === "thread"
+ && dbChannel.serverId === serverId
+ && dbChannel.parentChannelId
+ && dbChannel.parentMessageId
+ ? {
+ id: dbChannel.id,
+ serverId,
+ name: dbChannel.name,
+ type: dbChannel.type,
+ parentChannelId: dbChannel.parentChannelId,
+ parentMessageId: dbChannel.parentMessageId,
+ creatorId: dbChannel.creatorId ?? null,
+ archived: dbChannel.archived,
+ activityAt: dbChannel.lastMessageAt ?? "",
+ verifiedEpoch: accessEpoch,
+ }
+ : undefined
const query = useQuery<ChildChannelMeta>({
queryKey: communityKeys.channelMeta(serverId, channelId),
queryFn: async ({ signal }) => {
+ const token = captureCommunityLiveSnapshotToken(queryClient)
const meta = await fetchChannelMetadata(serverId, channelId, signal)
+ publishCommunityChannelMetadata(queryClient, {
+ metadata: meta,
+ proof: { token, signal },
+ })
return projectChildMeta(meta, meta.verifiedEpoch)
},
enabled,
+ placeholderData: registry ? undefined : placeholderData,
staleTime: Infinity,
gcTime: 5 * 60 * 1000,
+ retry: (failureCount, error) =>
+ !(error instanceof ApiError && [401, 403, 404].includes(error.status))
+ && failureCount < 1,
})
- const [trusted, setTrusted] = useState<{
- channelId: string
- meta: ChildChannelMeta
- } | null>(null)
+ const [trusted, setTrusted] = useState<TrustedChildMeta>(null)
useEffect(() => {
+ if (registry) return
if (query.data?.verifiedEpoch !== accessEpoch) return
- setTrusted(query.data.archived ? null : { channelId, meta: query.data })
- }, [accessEpoch, channelId, query.data])
+ setTrusted((current) => updateTrustedChildMeta(current, channelId, query.data!))
+ }, [accessEpoch, channelId, query.data, registry])
const trustedMeta = trusted?.channelId === channelId ? trusted.meta : undefined
- const renderable = pickRenderableChildMeta(query.data, trustedMeta, accessEpoch)
+ const renderable = registry
+ ? dbPlaceholder?.archived ? undefined : dbPlaceholder
+ : pickRenderableChildMeta(query.data, trustedMeta, accessEpoch)
return {
...query,
data: renderable,
diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
index 2436fcc14..c953e4a6a 100644
--- a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
@@ -119,11 +119,7 @@ describe("community read-state lifecycle reconciliation", () => {
it("schedules the first-auth owner before non-Inbox reconciliation completes", async () => {
vi.useFakeTimers()
await mountHook({ viewerUserId: "viewer-1" })
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
- id: "viewer-1",
- presence: "offline",
- }])
+ useCommunityWsStore.getState().setPresence("viewer-1", "offline")
let releaseSnapshot!: (value: unknown) => void
getCommunityApiFetchMock().mockReturnValueOnce(new Promise((resolve) => {
releaseSnapshot = resolve
@@ -132,7 +128,7 @@ describe("community read-state lifecycle reconciliation", () => {
const authentication = capturedUseUserWsOptions?.onAuthenticated?.()
expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce()
- expect(useCommunityWsStore.getState().profilesByUserId.get("viewer-1")?.presence)
+ expect(useCommunityWsStore.getState().presenceByUserId.get("viewer-1"))
.toBe("online")
await vi.advanceTimersByTimeAsync(500)
expect(invalidate).toHaveBeenCalledWith({
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index c102397d6..b591f6fc4 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -57,10 +57,11 @@ export type {
*
* Every event either patches the TanStack Query cache directly (fast — no
* refetch) or invalidates a query key (slow — triggers refetch). The choice
- * is driven by the reconciliation table in `plans/21-community-tech-debt-pass-2.md`.
+ * is driven by the reconciliation table in `the community reconciliation table`.
*
* State this hook owns *outside* the query cache:
- * - `useCommunityWsStore.profilesByUserId` — canonical user profile facts.
+ * - `useCommunityWsStore.presenceByUserId` — transient presence only; durable
+ * profile facts live in TanStack DB.
* - `useCommunityWsStore.seenMessageIds` — dedup for `message.create`.
* - `useCommunityStore.typingByScope` + `typingTimers` — typing indicator,
* keyed by conversation scope with per-(scope, user) auto-expire timers.
@@ -244,21 +245,9 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
if (viewerUserId) getAccountUnreadProjection(queryClient, viewerUserId)
viewerUserIdRef.current = viewerUserId
useEffect(() => {
+ if (!viewerUserId) return
const store = useCommunityWsStore.getState()
- const profileAccountEpoch = store.activateProfileAccount(viewerUserId)
- if (viewerUserId) {
- store.patchProfiles(store.beginProfileSnapshot(), [{
- id: viewerUserId,
- presence: "online",
- }])
- }
- return () => {
- const store = useCommunityWsStore.getState()
- if (
- store.profileViewerId === viewerUserId
- && store.profileAccountEpoch === profileAccountEpoch
- ) store.activateProfileAccount(null)
- }
+ store.setPresence(viewerUserId, "online")
}, [viewerUserId])
const inboxRefreshOwner = useRef<InboxRefreshOwner | null>(null)
@@ -529,10 +518,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
store.markAccessConnected()
const viewerId = viewerUserIdRef.current
if (viewerId) {
- store.patchProfiles(store.beginProfileSnapshot(), [{
- id: viewerId,
- presence: "online",
- }])
+ store.setPresence(viewerId, "online")
}
const firstAuthentication = !hasAuthenticatedRef.current
hasAuthenticatedRef.current = true
diff --git a/src/web/src/hooks/community/use-dm-read-state.test.ts b/src/web/src/hooks/community/use-dm-read-state.test.ts
index 0727f49ba..c5fe4b11c 100644
--- a/src/web/src/hooks/community/use-dm-read-state.test.ts
+++ b/src/web/src/hooks/community/use-dm-read-state.test.ts
@@ -119,6 +119,31 @@ describe("useDmReadStateSnapshot — freeze invariant", () => {
})
})
+ it("freezes a canonical snapshot immediately while the mount request revalidates", async () => {
+ const useHook = await loadHook()
+ queryReturn = { data: undefined, isFetching: true }
+ const canonical = {
+ lastReadMessageId: "m_cached",
+ lastReadAt: "2026-07-01T00:00:00.000Z",
+ lastReadSeq: 10,
+ }
+ const warm = useHook("dm_1", canonical)
+ flushEffects()
+ expect(warm).toEqual({ snapshot: canonical, isFetching: false })
+
+ refCounter = 0
+ pendingEffects = []
+ queryReturn = {
+ data: {
+ lastReadMessageId: "m_fresh",
+ lastReadAt: "2026-07-02T00:00:00.000Z",
+ lastReadSeq: 20,
+ },
+ isFetching: false,
+ }
+ expect(useHook("dm_1").snapshot).toEqual(canonical)
+ })
+
it("freezes the snapshot — a subsequent 'refetch' with a NEW value must NOT change what the hook returns", async () => {
const useHook = await loadHook()
diff --git a/src/web/src/hooks/community/use-dm-read-state.ts b/src/web/src/hooks/community/use-dm-read-state.ts
index 55e4f2bb8..fbf15c688 100644
--- a/src/web/src/hooks/community/use-dm-read-state.ts
+++ b/src/web/src/hooks/community/use-dm-read-state.ts
@@ -33,7 +33,10 @@ export type DmReadStateSnapshot = {
* same `staleTime: Infinity` + `gcTime: 0` combo, same channelId → dmId
* substitution.
*/
-export function useDmReadStateSnapshot(dmId: string | null | undefined): {
+export function useDmReadStateSnapshot(
+ dmId: string | null | undefined,
+ canonicalSnapshot?: DmReadStateSnapshot,
+): {
snapshot: DmReadStateSnapshot | null
isFetching: boolean
} {
@@ -67,6 +70,9 @@ export function useDmReadStateSnapshot(dmId: string | null | undefined): {
snapshotRef.current = null
lastDmIdRef.current = dmId
}
+ if (snapshotRef.current === null && canonicalSnapshot) {
+ snapshotRef.current = canonicalSnapshot
+ }
/* eslint-enable react-hooks/refs */
useEffect(() => {
if (snapshotRef.current !== null) return
@@ -77,7 +83,7 @@ export function useDmReadStateSnapshot(dmId: string | null | undefined): {
/* eslint-disable react-hooks/refs -- latched snapshot read; see channel hook tests */
return {
snapshot: snapshotRef.current ?? (!query.isFetching ? (query.data ?? null) : null),
- isFetching: query.isFetching,
+ isFetching: snapshotRef.current === null && query.isFetching,
}
/* eslint-enable react-hooks/refs */
}
diff --git a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts b/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
index e1d2112ae..e12232d09 100644
--- a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
+++ b/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, render } from "@/test/react-dom-harness"
import { communityKeys } from "@/lib/query-keys"
import type { DM } from "@/lib/community/models/people"
+import { useCommunityWsStore } from "@/stores/community/ws"
import {
classifyDmRouteAuthorityError,
DM_ROUTE_VERIFICATION_HEADER,
@@ -80,7 +81,11 @@ async function waitFor(predicate: () => boolean, tries = 80) {
}
describe("DM route verification", () => {
- beforeEach(() => apiFetchMock.mockReset())
+ beforeEach(() => {
+ apiFetchMock.mockReset()
+ useCommunityWsStore.getState().reset()
+ useCommunityWsStore.getState().activateProfileAccount("viewer")
+ })
afterEach(() => onlineManager.setOnline(true))
it("bypasses a fresh cached miss, updates the canonical list, and dedupes callers", async () => {
@@ -109,6 +114,7 @@ describe("DM route verification", () => {
expect(apiFetchMock).toHaveBeenCalledTimes(1)
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/dms", {
headers: { [DM_ROUTE_VERIFICATION_HEADER]: "1" },
+ signal: expect.any(AbortSignal),
})
expect(queryClient.getQueryData(communityKeys.dms())).toEqual(authoritative)
})
@@ -122,6 +128,47 @@ describe("DM route verification", () => {
expect(apiFetchMock).toHaveBeenCalledTimes(1)
})
+ it.each(["cancel", "account", "access"] as const)(
+ "rejects a %s-superseded route authority response before canonical cache publication",
+ async (race) => {
+ const queryClient = client()
+ const current: DM = {
+ id: "dm-current",
+ userId: "u-current",
+ name: "Current peer",
+ discriminator: "0001",
+ avatar: "C",
+ status: "offline",
+ preview: "",
+ }
+ queryClient.setQueryData(communityKeys.dms(), { conversations: [current] })
+ const request = deferred<{ conversations: DM[] }>()
+ apiFetchMock.mockReturnValueOnce(request.promise)
+
+ const pending = startDmRouteVerification(queryClient, "dm-stale-target")
+ const rejected = expect(pending).rejects.toMatchObject(
+ race === "cancel" ? {} : { name: "AbortError" },
+ )
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
+ if (race === "cancel") {
+ await queryClient.cancelQueries({
+ queryKey: communityKeys.dmRouteVerification("dm-stale-target"),
+ exact: true,
+ })
+ } else if (race === "account") {
+ useCommunityWsStore.getState().activateProfileAccount("other")
+ } else {
+ useCommunityWsStore.setState((state) => ({ accessEpoch: state.accessEpoch + 1 }))
+ }
+ request.resolve({ conversations: [] })
+
+ await rejected
+ expect(queryClient.getQueryData(communityKeys.dms())).toEqual({
+ conversations: [current],
+ })
+ },
+ )
+
it("trusts a provisional canonical cache row without starting authority", async () => {
const queryClient = client()
const provisional: DM = {
@@ -168,6 +215,14 @@ describe("DM route verification", () => {
expect(classifyDmRouteAuthorityError({ status })).toBe("denied")
})
+ it("returns denied for an explicit authority rejection", async () => {
+ const queryClient = client()
+ apiFetchMock.mockRejectedValueOnce(Object.assign(new Error("denied"), { status: 403 }))
+
+ await expect(startDmRouteVerification(queryClient, "dm-denied")).resolves.toBe("denied")
+ expect(queryClient.getQueryData(communityKeys.dms())).toBeUndefined()
+ })
+
it("does not classify a transient failure as denied", () => {
expect(classifyDmRouteAuthorityError({ status: 0 })).toBe("error")
expect(classifyDmRouteAuthorityError(new Error("offline"))).toBe("error")
diff --git a/src/web/src/hooks/community/use-dm-route-verification.ts b/src/web/src/hooks/community/use-dm-route-verification.ts
index 403e45d0e..b835135bf 100644
--- a/src/web/src/hooks/community/use-dm-route-verification.ts
+++ b/src/web/src/hooks/community/use-dm-route-verification.ts
@@ -1,17 +1,28 @@
"use client"
import { useCallback, useEffect } from "react"
-import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
+import {
+ useQuery,
+ useQueryClient,
+ QueryObserver,
+ type QueryClient,
+ type QueryFunctionContext,
+} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { DM } from "@/lib/community/models/people"
import type { DmsResponse } from "./use-dms"
+import {
+ assertCommunityLiveSnapshotTokenCurrent,
+ captureCommunityLiveSnapshotToken,
+ publishCommunityLiveSnapshot,
+} from "@/lib/community-db/sync"
export const DM_ROUTE_VERIFICATION_HEADER = "X-Alook-DM-Route-Verification"
-const dmRouteAuthorityQueryFn = () => apiFetch<DmsResponse>(
+const dmRouteAuthorityQueryFn = (signal: AbortSignal | undefined) => apiFetch<DmsResponse>(
"/api/community/users/me/dms",
- { headers: { [DM_ROUTE_VERIFICATION_HEADER]: "1" } },
+ { headers: { [DM_ROUTE_VERIFICATION_HEADER]: "1" }, signal },
)
export type DmRouteVerification = "present" | "missing" | "denied"
@@ -29,26 +40,36 @@ export function classifyDmRouteAuthorityError(error: unknown): "denied" | "error
return status === 403 || status === 404 ? "denied" : "error"
}
-function verifyDmRoute(
+async function verifyDmRoute(
queryClient: QueryClient,
dmId: string,
+ signal: AbortSignal | undefined,
): Promise<DmRouteVerification> {
- return dmRouteAuthorityQueryFn().then(
- (response) => {
- queryClient.setQueryData(communityKeys.dms(), response)
- return response.conversations.some((dm) => dm.id === dmId) ? "present" : "missing"
- },
- (error: unknown) => {
- if (classifyDmRouteAuthorityError(error) === "denied") return "denied"
- throw error
- },
- )
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ try {
+ const response = await dmRouteAuthorityQueryFn(signal)
+ publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "dms", data: response },
+ proof: { kind: "structural", token, signal },
+ })
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
+ queryClient.setQueryData(communityKeys.dms(), response)
+ return response.conversations.some((dm) => dm.id === dmId) ? "present" : "missing"
+ } catch (error) {
+ if (classifyDmRouteAuthorityError(error) === "denied") return "denied"
+ throw error
+ }
}
function verificationOptions(queryClient: QueryClient, dmId: string) {
+ const queryKey = communityKeys.dmRouteVerification(dmId)
return {
- queryKey: communityKeys.dmRouteVerification(dmId),
- queryFn: () => verifyDmRoute(queryClient, dmId),
+ queryKey,
+ queryFn: async ({ signal }: QueryFunctionContext) => {
+ const owner = new QueryObserver(queryClient, { queryKey, enabled: false })
+ const release = owner.subscribe(() => release())
+ return verifyDmRoute(queryClient, dmId, signal)
+ },
retry: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
diff --git a/src/web/src/hooks/community/use-dms.dom.test.ts b/src/web/src/hooks/community/use-dms.dom.test.ts
index af3a343cf..fb4cb88b1 100644
--- a/src/web/src/hooks/community/use-dms.dom.test.ts
+++ b/src/web/src/hooks/community/use-dms.dom.test.ts
@@ -6,12 +6,36 @@ import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
import type { DM } from "@/lib/community/models/people"
import { inboxDmRowTarget } from "./inbox-read-reservation"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import { ingestDms } from "@/lib/community-db/sync"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+function dm(id: string): DM {
+ return {
+ id,
+ userId: `${id}-peer`,
+ name: id,
+ discriminator: "0001",
+ avatar: id,
+ status: "offline",
+ preview: "",
+ }
+}
+
beforeEach(() => {
apiFetchMock.mockReset()
useCommunityWsStore.getState().reset()
@@ -36,6 +60,10 @@ describe("useDms / dmsQueryFn", () => {
const qc = new QueryClient()
const key = communityKeys.dms()
await qc.fetchQuery({ queryKey: key, queryFn: dmsQueryFn })
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/dms",
+ { signal: expect.any(AbortSignal) },
+ )
expect(qc.getQueryData(key)).toEqual({ conversations: [] })
})
@@ -46,12 +74,70 @@ describe("useDms / dmsQueryFn", () => {
const projection = new AccountUnreadProjection("u1")
projection.setNotificationPolicy({})
projection.recordArrival({ channelId: "dm_1", seq: 3 })
+ const queryClient = new QueryClient()
- await dmsProjectedQueryFn(projection)()
+ await dmsProjectedQueryFn(projection, queryClient)()
expect(projection.projectUnread("dms", "dm_1", false)).toBe(false)
})
+ it.each(["cancel", "account", "access"] as const)(
+ "rejects a %s-superseded DM list before destructive publication",
+ async (race) => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const disposeRegistry = registry.cleanup
+ ingestDms(registry, { conversations: [dm("dm-current")] })
+ const request = deferred<{ conversations: DM[] }>()
+ apiFetchMock.mockReturnValueOnce(request.promise)
+ const { dmsProjectedQueryFn } = await import("./use-dms")
+ const { AccountUnreadProjection } = await import("./account-unread-projection")
+ const projection = new AccountUnreadProjection("viewer")
+ const controller = new AbortController()
+
+ const pending = dmsProjectedQueryFn(projection, queryClient)({
+ signal: controller.signal,
+ } as never)
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/dms",
+ { signal: controller.signal },
+ )
+ if (race === "cancel") controller.abort()
+ else if (race === "account") useCommunityWsStore.getState().activateProfileAccount("other")
+ else useCommunityWsStore.setState((state) => ({ accessEpoch: state.accessEpoch + 1 }))
+ request.resolve({ conversations: [] })
+
+ await expect(pending).rejects.toMatchObject({ name: "AbortError" })
+ expect(registry.collections.channels.get("dm-current")).toBeDefined()
+ expect(projection.inspectForTests().pendingSnapshots).toBe(0)
+ unregister()
+ await disposeRegistry()
+ },
+ )
+
+ it("lets a current DM-list generation replace canonical rows", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const disposeRegistry = registry.cleanup
+ ingestDms(registry, { conversations: [dm("dm-current")] })
+ apiFetchMock.mockResolvedValueOnce({ conversations: [] })
+ const { dmsProjectedQueryFn } = await import("./use-dms")
+ const { AccountUnreadProjection } = await import("./account-unread-projection")
+
+ await dmsProjectedQueryFn(
+ new AccountUnreadProjection("viewer"),
+ queryClient,
+ )()
+
+ expect(registry.collections.channels.get("dm-current")).toBeUndefined()
+ unregister()
+ await disposeRegistry()
+ })
+
it("cancels DM snapshot coverage when the transport fails", async () => {
apiFetchMock.mockRejectedValueOnce(new Error("offline"))
const { dmsProjectedQueryFn } = await import("./use-dms")
@@ -93,7 +179,53 @@ describe("useDms / dmsQueryFn", () => {
await act(async () => renderer.unmount())
})
- it("projects the canonical peer profile without rewriting the raw DM cache", async () => {
+ it("uses transport conversations without a canonical registry", async () => {
+ const conversations = [dm("dm-providerless")]
+ const { useDms } = await import("./use-dms")
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
+ qc.setQueryData(communityKeys.dms(), { conversations })
+ let latest: ReturnType<typeof useDms> | undefined
+
+ function Probe() {
+ latest = useDms()
+ return null
+ }
+
+ const renderer = render(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Probe),
+ ))
+ expect(latest?.dms.map(({ id }) => id)).toEqual(["dm-providerless"])
+ await act(async () => renderer.unmount())
+ })
+
+ it("uses canonical conversations while a registry is active", async () => {
+ const { useDms } = await import("./use-dms")
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
+ const registry = createCommunityDbRegistry(qc, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const disposeRegistry = registry.cleanup
+ ingestDms(registry, { conversations: [dm("dm-canonical")] })
+ let latest: ReturnType<typeof useDms> | undefined
+
+ function Probe() {
+ latest = useDms()
+ return null
+ }
+ const renderer = render(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(CommunityDbProvider, { registry }, React.createElement(Probe)),
+ ))
+ expect(latest?.dms.map(({ id }) => id)).toEqual(["dm-canonical"])
+ await act(async () => renderer.unmount())
+ unregister()
+ await disposeRegistry()
+ })
+
+ it("uses transient presence without rewriting the raw canonical DM identity", async () => {
const { useDms } = await import("./use-dms")
const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
const raw = {
@@ -109,13 +241,7 @@ describe("useDms / dmsQueryFn", () => {
}],
}
qc.setQueryData(communityKeys.dms(), raw)
- const store = useCommunityWsStore.getState()
- store.patchProfiles(store.beginProfileSnapshot(), [{
- id: "u_1",
- identityAbout: { name: "Global Alice", discriminator: "0042" },
- avatar: { avatar: "global", avatarVersion: 7 },
- presence: "online",
- }])
+ useCommunityWsStore.getState().setPresence("u_1", "online")
let projected!: ReturnType<typeof useDms>
function Probe() {
projected = useDms()
@@ -128,10 +254,10 @@ describe("useDms / dmsQueryFn", () => {
))
expect(projected.dms[0]).toMatchObject({
- name: "Global Alice",
- discriminator: "0042",
- avatar: "global",
- avatarVersion: 7,
+ name: "Raw Alice",
+ discriminator: "0001",
+ avatar: "raw",
+ avatarVersion: 1,
status: "online",
preview: "hello",
})
@@ -139,7 +265,44 @@ describe("useDms / dmsQueryFn", () => {
await act(async () => renderer.unmount())
})
- it("projects unread arrivals alongside canonical peer profiles", async () => {
+ it("renders persisted DM identity without a live profile seed", async () => {
+ const { useDms } = await import("./use-dms")
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
+ qc.setQueryData(communityKeys.dms(), {
+ conversations: [{
+ id: "dm_cached",
+ userId: "u_cached",
+ name: "Cached Alice",
+ discriminator: "0042",
+ avatar: "cached-avatar",
+ avatarVersion: 7,
+ status: "online",
+ preview: "cached preview",
+ }],
+ })
+ let projected!: ReturnType<typeof useDms>
+ function Probe() {
+ projected = useDms()
+ return null
+ }
+ const renderer = render(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Probe),
+ ))
+
+ expect(projected.dms[0]).toMatchObject({
+ name: "Cached Alice",
+ discriminator: "0042",
+ avatar: "cached-avatar",
+ avatarVersion: 7,
+ status: "offline",
+ })
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ await act(async () => renderer.unmount())
+ })
+
+ it("keeps legacy unread flags subordinate to canonical attention", async () => {
const conversations = [
{
id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0001",
@@ -173,14 +336,14 @@ describe("useDms / dmsQueryFn", () => {
React.createElement(Harness),
))
- expect(latest?.dms[0]?.unread).toBe(true)
- expect(latest?.dms[1]?.unread).toBe(true)
- expect(latest?.dms[2]?.unread).toBe(true)
+ expect(latest?.dms[0]?.unread).toBe(false)
+ expect(latest?.dms[1]?.unread).toBe(false)
+ expect(latest?.dms[2]?.unread).toBe(false)
expect(qc.getQueryData(communityKeys.dms())).toEqual({ conversations })
await act(async () => renderer.unmount())
})
- it("projects and rolls back the exact Inbox DM reservation without hiding a sibling", async () => {
+ it("does not let a legacy Inbox reservation mutate canonical DM attention", async () => {
const conversations = [
{
id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0001",
@@ -229,12 +392,12 @@ describe("useDms / dmsQueryFn", () => {
await act(async () => {
epoch = collapse!.beginProjection(inboxDmRowTarget(inboxDm), "/c/me/dm_1")
})
- expect(latest?.dms.map((dm) => dm.unread)).toEqual([false, true])
+ expect(latest?.dms.map((dm) => dm.unread)).toEqual([false, false])
await act(async () => {
collapse!.rollbackProjection(epoch)
})
- expect(latest?.dms.map((dm) => dm.unread)).toEqual([true, true])
+ expect(latest?.dms.map((dm) => dm.unread)).toEqual([false, false])
await act(async () => renderer.unmount())
})
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index 3e43ef8f1..f0c678baa 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -1,6 +1,12 @@
"use client"
-import { useQuery, useQueryClient, type UseQueryResult } from "@tanstack/react-query"
+import {
+ useQuery,
+ useQueryClient,
+ type QueryClient,
+ type QueryFunctionContext,
+ type UseQueryResult,
+} from "@tanstack/react-query"
import {
apiFetchProfiles,
communityUserProfilePatch,
@@ -8,18 +14,23 @@ import {
import { communityKeys } from "@/lib/query-keys"
import type { DM } from "@/lib/community/models/people"
import { useEffect, useMemo, useSyncExternalStore } from "react"
-import { useProfilesByUserId } from "@/stores/community/ws"
+import {
+ useAttentionScopes,
+ useCanonicalProfilesByUserId,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
getActiveAccountUnreadProjection,
type AccountUnreadProjection,
type AccountUnreadSource,
} from "./account-unread-projection"
-import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
+import { useDmProjection } from "@/lib/community-db/projections"
import {
- reservedUnreadExclusion,
- selectUnreadPresentation,
-} from "./unread-presentation"
+ assertCommunityLiveSnapshotTokenCurrent,
+ captureCommunityLiveSnapshotToken,
+ publishCommunityLiveSnapshot,
+} from "@/lib/community-db/sync"
/**
* Fetches the DM conversation sidebar list.
@@ -34,10 +45,13 @@ export type DmsResponse = { conversations: DM[] }
// Frozen empty fallback — see `use-servers.ts` for the rationale.
const EMPTY_DMS: readonly DM[] = Object.freeze([])
-export const dmsQueryFn = () =>
+export const dmsQueryFn = (
+ context: QueryFunctionContext = {} as QueryFunctionContext,
+) =>
apiFetchProfiles<DmsResponse>(
"/api/community/users/me/dms",
(data) => data.conversations.map((dm) => communityUserProfilePatch(dm.userId, dm)),
+ context.signal ? { signal: context.signal } : undefined,
)
function dmUnreadSources(data: DmsResponse): AccountUnreadSource[] {
@@ -47,11 +61,26 @@ function dmUnreadSources(data: DmsResponse): AccountUnreadSource[] {
}])
}
-export const dmsProjectedQueryFn = (projection: AccountUnreadProjection) => async () => {
+export const dmsProjectedQueryFn = (
+ projection: AccountUnreadProjection,
+ queryClient?: QueryClient,
+) => async (context: QueryFunctionContext = {} as QueryFunctionContext) => {
+ const publicationToken = queryClient
+ ? captureCommunityLiveSnapshotToken(queryClient)
+ : null
const token = projection.beginSnapshot("dms", "dms")
try {
- const data = await dmsQueryFn()
+ const data = await dmsQueryFn(context)
+ if (queryClient && publicationToken) {
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, publicationToken, context.signal)
+ }
projection.absorbSnapshot(token, dmUnreadSources(data))
+ if (queryClient && publicationToken) {
+ publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "dms", data },
+ proof: { kind: "structural", token: publicationToken, signal: context.signal },
+ })
+ }
return data
} catch (error) {
projection.cancelSnapshot(token)
@@ -59,7 +88,10 @@ export const dmsProjectedQueryFn = (projection: AccountUnreadProjection) => asyn
}
}
-export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
+export function useDms(enabled = true): UseQueryResult<DmsResponse> & { dms: DM[] } {
+ const registry = useOptionalCommunityDbRegistry()
+ const attentionScopes = useAttentionScopes()
+ const dbDms = useDmProjection()
const queryClient = useQueryClient()
const unreadProjection = useMemo(
() => getActiveAccountUnreadProjection(queryClient),
@@ -70,22 +102,21 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
- const reservationTarget = useInboxProjectionTarget(queryClient)
- const unreadExclusion = useMemo(
- () => reservedUnreadExclusion(reservationTarget, "dms"),
- [reservationTarget],
+ const queryFn = useMemo(
+ () => dmsProjectedQueryFn(unreadProjection, queryClient),
+ [queryClient, unreadProjection],
)
- const queryFn = useMemo(() => dmsProjectedQueryFn(unreadProjection), [unreadProjection])
const query = useQuery({
queryKey: communityKeys.dms(),
queryFn,
+ enabled,
// Inbox navigation projects the destination into this canonical cache
// before routing. Reusing that projection across /c/me layout mounts keeps
// the transition request-neutral; WS and reconnect invalidations still
// refetch this active key explicitly.
staleTime: Infinity,
})
- const profilesByUserId = useProfilesByUserId()
+ const profilesByUserId = useCanonicalProfilesByUserId()
useEffect(() => {
if (!query.data) return
unreadProjection.mergeSources(
@@ -104,29 +135,27 @@ export function useDms(): UseQueryResult<DmsResponse> & { dms: DM[] } {
}, [query.data, unreadProjection])
const dms = useMemo(() => {
void unreadVersion
- return (query.data?.conversations ?? EMPTY_DMS).map((dm) => {
- const profile = readCommunityProfile(profilesByUserId.get(dm.userId), dm.userId)
- const unread = selectUnreadPresentation({
- accountUnread: unreadProjection.projectUnread(
- "dms",
- dm.id,
- dm.unread === true,
- dm.lastUnreadSeq,
- "dms",
- unreadExclusion,
- ),
- }).effectiveUnread
+ const source = registry
+ ? dbDms ?? EMPTY_DMS
+ : query.data?.conversations ?? EMPTY_DMS
+ if (source.length === 0) return EMPTY_DMS as DM[]
+ return source.map((dm) => {
+ const liveProfile = profilesByUserId.get(dm.userId)
+ const profile = readCommunityProfile(liveProfile, dm.userId)
+ const unread = attentionScopes.some((scope) => (
+ !scope.serverId && scope.channelId === dm.id && scope.ordinaryUnread
+ ))
return {
...dm,
- name: profile.name,
- discriminator: profile.discriminator,
- avatar: profile.avatar,
- avatarVersion: profile.avatarVersion,
- status: profile.presence,
+ name: liveProfile?.name ?? dm.name,
+ discriminator: liveProfile?.discriminator ?? dm.discriminator,
+ avatar: liveProfile?.avatar ?? dm.avatar,
+ avatarVersion: liveProfile?.avatarVersion ?? dm.avatarVersion,
+ status: liveProfile ? profile.presence : "offline",
unread,
}
})
- }, [profilesByUserId, query.data?.conversations, unreadExclusion, unreadProjection, unreadVersion])
+ }, [attentionScopes, dbDms, profilesByUserId, query.data?.conversations, registry, unreadVersion])
return {
...query,
dms,
diff --git a/src/web/src/hooks/community/use-folders.dom.test.ts b/src/web/src/hooks/community/use-folders.dom.test.ts
new file mode 100644
index 000000000..37c2ec10e
--- /dev/null
+++ b/src/web/src/hooks/community/use-folders.dom.test.ts
@@ -0,0 +1,55 @@
+import { createElement, type PropsWithChildren } from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { describe, expect, it, vi } from "vitest"
+import { renderHook } from "@/test/react-dom-harness"
+
+const dbRail = vi.hoisted(() => ({
+ current: {
+ servers: [],
+ folders: [{ id: "db-folder", name: "Canonical", position: 0, servers: [] }],
+ },
+}))
+const registryActive = vi.hoisted(() => ({ current: true }))
+vi.mock("@/lib/community-db/projections", () => ({
+ useServerRailProjection: () => dbRail.current,
+ useOptionalCommunityDbRegistry: () => registryActive.current ? {} : null,
+}))
+vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(() => new Promise(() => undefined)) }))
+
+import { useFolders } from "./use-folders"
+
+describe("useFolders canonical projection", () => {
+ it("prefers the canonical rail while the transport query is pending", () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client },
+ children,
+ )
+ const rendered = renderHook(useFolders, { wrapper })
+
+ expect(rendered.result.current.folders).toEqual(dbRail.current.folders)
+ rendered.unmount()
+ client.clear()
+ })
+
+ it("uses transport folders without a canonical registry", () => {
+ registryActive.current = false
+ const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
+ client.setQueryData(["community", "folders"], {
+ folders: [{ id: "query-folder", name: "Query", position: 0, servers: [] }],
+ })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client },
+ children,
+ )
+ const rendered = renderHook(useFolders, { wrapper })
+
+ expect(rendered.result.current.folders).toEqual([
+ { id: "query-folder", name: "Query", position: 0, servers: [] },
+ ])
+ rendered.unmount()
+ registryActive.current = true
+ })
+})
diff --git a/src/web/src/hooks/community/use-folders.test.ts b/src/web/src/hooks/community/use-folders.test.ts
index 2674dac2c..ec203aec7 100644
--- a/src/web/src/hooks/community/use-folders.test.ts
+++ b/src/web/src/hooks/community/use-folders.test.ts
@@ -34,10 +34,14 @@ describe("useFolders / foldersQueryFn", () => {
it("populates queryClient at communityKeys.folders()", async () => {
apiFetchMock.mockResolvedValueOnce({ folders: [] })
- const { foldersQueryFn } = await import("./use-folders")
+ const { foldersProjectedQueryFn } = await import("./use-folders")
const qc = new QueryClient()
const key = communityKeys.folders()
- await qc.fetchQuery({ queryKey: key, queryFn: foldersQueryFn })
+ await qc.fetchQuery({ queryKey: key, queryFn: foldersProjectedQueryFn(qc) })
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/server-folders",
+ { signal: expect.any(AbortSignal) },
+ )
expect(qc.getQueryData(key)).toEqual({ folders: [] })
})
diff --git a/src/web/src/hooks/community/use-folders.ts b/src/web/src/hooks/community/use-folders.ts
index 0e3f73569..182ea3bf7 100644
--- a/src/web/src/hooks/community/use-folders.ts
+++ b/src/web/src/hooks/community/use-folders.ts
@@ -1,11 +1,25 @@
"use client"
-import { useQuery, type UseQueryResult } from "@tanstack/react-query"
+import {
+ useQuery,
+ useQueryClient,
+ type QueryClient,
+ type QueryFunctionContext,
+ type UseQueryResult,
+} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
import type { CommunityFolder } from "@/lib/community/models/navigation"
import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ useOptionalCommunityDbRegistry,
+ useServerRailProjection,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityLiveSnapshot,
+} from "@/lib/community-db/sync"
/**
* Fetches the user's server-folder groupings for the rail.
@@ -26,14 +40,21 @@ export type FoldersResponse = { folders: CommunityFolder[] }
// Frozen empty fallback — see `use-servers.ts` for the rationale.
const EMPTY_FOLDERS: readonly CommunityFolder[] = Object.freeze([])
-export const foldersQueryFn = async (): Promise<FoldersResponse> => {
+export const foldersQueryFn = async (
+ context: QueryFunctionContext = {} as QueryFunctionContext,
+): Promise<FoldersResponse> => {
const before = useCommunityWsStore.getState()
const token = {
viewerId: before.profileViewerId,
accountEpoch: before.profileAccountEpoch,
accessEpoch: before.accessEpoch,
}
- const data = await apiFetch<{ folders: RawFolder[] }>("/api/community/users/me/server-folders")
+ const data = context.signal
+ ? await apiFetch<{ folders: RawFolder[] }>(
+ "/api/community/users/me/server-folders",
+ { signal: context.signal },
+ )
+ : await apiFetch<{ folders: RawFolder[] }>("/api/community/users/me/server-folders")
const after = useCommunityWsStore.getState()
if (
after.profileViewerId !== token.viewerId
@@ -54,15 +75,32 @@ export const foldersQueryFn = async (): Promise<FoldersResponse> => {
return { folders }
}
+export const foldersProjectedQueryFn = (
+ queryClient: QueryClient,
+) => async (context: QueryFunctionContext = {} as QueryFunctionContext) => {
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ const data = await foldersQueryFn(context)
+ publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "folders", data },
+ proof: { kind: "structural", token, signal: context.signal },
+ })
+ return data
+}
+
export function useFolders(): UseQueryResult<FoldersResponse> & {
folders: CommunityFolder[]
} {
+ const registry = useOptionalCommunityDbRegistry()
+ const dbRail = useServerRailProjection()
+ const queryClient = useQueryClient()
const query = useQuery({
queryKey: communityKeys.folders(),
- queryFn: foldersQueryFn,
+ queryFn: foldersProjectedQueryFn(queryClient),
})
return {
...query,
- folders: query.data?.folders ?? (EMPTY_FOLDERS as CommunityFolder[]),
+ folders: registry
+ ? dbRail?.folders ?? (EMPTY_FOLDERS as CommunityFolder[])
+ : query.data?.folders ?? (EMPTY_FOLDERS as CommunityFolder[]),
}
}
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 c2a0110dc..9de066fc5 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
@@ -100,22 +100,9 @@ describe("forumFeedPageQueryFn", () => {
}
apiFetchMock.mockResolvedValue(page)
- const result = await forumFeedPageQueryFn("forum_one", null)({ pageParam: null })
+ const result = await forumFeedPageQueryFn("forum_one", null, new QueryClient())({ pageParam: null })
expect(result).toBe(page)
- expect(useCommunityWsStore.getState().profilesByUserId.get("author_1")).toMatchObject({
- name: "Alice",
- avatar: "A",
- avatarVersion: 2,
- })
- expect(useCommunityWsStore.getState().profilesByUserId.get("participant_1")).toMatchObject({
- name: "Bob",
- avatar: "bob.png",
- avatarVersion: 3,
- })
- const anonymousParticipant = useCommunityWsStore.getState().profilesByUserId.get("participant_2")
- expect(anonymousParticipant).toMatchObject({ avatarVersion: 0 })
- expect(anonymousParticipant).not.toHaveProperty("name")
})
})
@@ -251,6 +238,66 @@ describe("mapForumFeedPages", () => {
})
})
+ it("projects a canonical opener without reviving transport message fields", () => {
+ const pages: ForumFeedPage[] = [{
+ serverId: "server_1",
+ parentType: "forum",
+ threads: [{
+ id: "post-1",
+ name: "transport title",
+ creatorId: "transport-author",
+ messageCount: 1,
+ parentMessageId: "opener-1",
+ lastMessageAt: null,
+ createdAt: "2026-08-08T00:00:00.000Z",
+ activityAt: "2026-08-08T00:00:00.000Z",
+ }],
+ included: {
+ parentMessages: [{
+ id: "opener-1",
+ channelId: "forum-1",
+ seq: 7,
+ content: "transport content",
+ authorId: "transport-author",
+ authorName: "Transport",
+ authorImage: "/transport.png",
+ authorAvatarVersion: 4,
+ createdAt: "2026-08-08T00:00:00.000Z",
+ }],
+ firstMessages: [{ channelId: "post-1", content: "transport preview" }],
+ tags: [],
+ participants: [],
+ },
+ hasMore: false,
+ }]
+ const canonical = new Map([[
+ "opener-1",
+ {
+ id: "opener-1",
+ type: "chat",
+ content: "canonical content",
+ authorId: undefined,
+ authorName: "Canonical",
+ authorAvatar: undefined,
+ authorAvatarVersion: undefined,
+ createdAt: undefined,
+ seq: undefined,
+ } as never,
+ ]])
+
+ expect(mapForumFeedPages(pages, canonical)).toEqual([
+ expect.objectContaining({
+ name: "canonical content",
+ authorId: "transport-author",
+ authorAvatarVersion: 0,
+ preview: "",
+ parent: { authorName: "Canonical", text: "" },
+ }),
+ ])
+ expect(mapForumFeedPages(pages, canonical)[0]).not.toHaveProperty("openerCreatedAt")
+ expect(mapForumFeedPages(pages, canonical)[0]).not.toHaveProperty("parentSeq")
+ })
+
it("matches SQLite BINARY id ordering for equal-created mixed-case nanoids", () => {
const expectedIds = [
"kMRip4KDm4Ki2HU8vQ2qd",
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index e9abcf7e2..4ff0205a5 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -9,6 +9,11 @@ import { avatarInitial } from "@/lib/community/avatar"
import { canonicalUserImage } from "@/lib/community/storage"
import { readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"
import type { ForumThread } from "@/lib/community/models/message"
+import { useCanonicalMessagesById } from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityEmbeddedMessages,
+} from "@/lib/community-db/sync"
import { useForumTags } from "./use-channel-panels"
import {
projectForumThreadsThroughActiveTagTransitions,
@@ -18,8 +23,15 @@ import {
export { removeForumPostFromFeed } from "./forum-feed-tag-transition"
export type { ForumFeedPage } from "./forum-feed-tag-transition"
-export function forumFeedPageQueryFn(channelId: string, tag: string | null) {
+export function forumFeedPageQueryFn(
+ channelId: string,
+ tag: string | null,
+ queryClient?: ReturnType<typeof useQueryClient>,
+) {
return ({ pageParam, signal }: { pageParam: string | null; signal?: AbortSignal }) => {
+ const publicationToken = queryClient
+ ? captureCommunityLiveSnapshotToken(queryClient)
+ : null
const params = new URLSearchParams({
order: "createdAt",
limit: String(DEFAULT_MESSAGE_PAGE_SIZE),
@@ -52,17 +64,45 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null) {
participant.userId,
participant.userImage,
participant.userAvatarVersion,
- ) ?? avatarInitial(participant.userName ?? "Unknown"),
+ ) ?? avatarInitial(participant.userName ?? "Deleted user"),
avatarVersion: participant.userAvatarVersion,
},
})),
],
signal ? { signal } : undefined,
- )
+ ).then((page) => {
+ if (queryClient && publicationToken) {
+ publishCommunityEmbeddedMessages(queryClient, {
+ entries: page.included.parentMessages.map((message) => ({
+ channelId: message.channelId,
+ message: {
+ id: message.id,
+ type: "chat",
+ seq: message.seq,
+ createdAt: message.createdAt,
+ content: message.content,
+ authorId: message.authorId,
+ authorName: message.authorName,
+ authorAvatar: canonicalUserImage(
+ message.authorId,
+ message.authorImage,
+ message.authorAvatarVersion,
+ ) ?? undefined,
+ authorAvatarVersion: message.authorAvatarVersion,
+ },
+ })),
+ proof: { token: publicationToken, signal },
+ })
+ }
+ return page
+ })
}
}
-export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {
+export function mapForumFeedPages(
+ pages: ForumFeedPage[],
+ canonicalMessages?: ReadonlyMap<string, import("@/lib/community/models/message").Msg>,
+): ForumThread[] {
const byId = new Map<string, ForumThread>()
const createdAtById = new Map<string, string>()
for (const page of pages) {
@@ -91,11 +131,38 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {
for (const thread of page.threads) {
if (byId.has(thread.id)) continue
createdAtById.set(thread.id, thread.createdAt)
- const opener = thread.parentMessageId ? openerById.get(thread.parentMessageId) : undefined
- const first = firstByChannel.get(thread.id)
+ const rawOpener = thread.parentMessageId ? openerById.get(thread.parentMessageId) : undefined
+ const canonicalOpener = rawOpener ? canonicalMessages?.get(rawOpener.id) : undefined
+ if (canonicalMessages !== undefined && thread.parentMessageId && !canonicalOpener) continue
+ const opener = canonicalMessages === undefined
+ ? rawOpener
+ ? {
+ id: rawOpener.id,
+ type: "chat" as const,
+ content: rawOpener.content,
+ authorId: rawOpener.authorId,
+ authorName: rawOpener.authorName,
+ authorAvatar: canonicalUserImage(
+ rawOpener.authorId,
+ rawOpener.authorImage,
+ rawOpener.authorAvatarVersion,
+ ) ?? undefined,
+ authorAvatarVersion: rawOpener.authorAvatarVersion,
+ createdAt: rawOpener.createdAt,
+ seq: rawOpener.seq,
+ }
+ : undefined
+ : canonicalOpener
+ // The forum transport exposes firstMessages only as a channel/content
+ // preview with no stable message identity. It is a providerless read
+ // projection only; a canonical-backed surface must never treat it as a
+ // second message entity source because edits/deletes cannot reconcile it.
+ const first = canonicalMessages === undefined
+ ? firstByChannel.get(thread.id)
+ : undefined
byId.set(thread.id, {
id: thread.id,
- name: opener?.content.trim() ? opener.content : thread.name?.trim() || "Post",
+ name: opener?.content?.trim() ? opener.content : thread.name?.trim() || "Post",
messageCount: thread.messageCount ?? 0,
lastMessageAt: thread.activityAt,
parent: {
@@ -105,13 +172,12 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {
},
authorId: opener?.authorId ?? thread.creatorId ?? "",
authorAvatar: opener
- ? canonicalUserImage(opener.authorId, opener.authorImage, opener.authorAvatarVersion)
- ?? avatarInitial(opener.authorName)
+ ? opener.authorAvatar ?? avatarInitial(opener.authorName ?? "")
: avatarInitial(""),
authorAvatarVersion: opener?.authorAvatarVersion ?? 0,
openerMessageId: thread.parentMessageId ?? "",
...(opener?.createdAt ? { openerCreatedAt: opener.createdAt } : {}),
- ...(opener ? { parentSeq: opener.seq } : {}),
+ ...(opener?.seq !== undefined ? { parentSeq: opener.seq } : {}),
tags: thread.parentMessageId ? tagsByMessage.get(thread.parentMessageId) ?? [] : [],
preview: (first?.content ?? "").slice(0, 100),
participants: participantsByChannel.get(thread.id) ?? [],
@@ -127,6 +193,7 @@ export function mapForumFeedPages(pages: ForumFeedPage[]): ForumThread[] {
export function useForumFeed(_serverId: string, channelId: string) {
const queryClient = useQueryClient()
+ const canonicalMessages = useCanonicalMessagesById()
const [tag, setTag] = useState(() => {
if (typeof window === "undefined") return "All"
try { return readForumTagSelection(window.localStorage, channelId) }
@@ -153,7 +220,7 @@ export function useForumFeed(_serverId: string, channelId: string) {
string | null
>({
queryKey,
- queryFn: forumFeedPageQueryFn(channelId, selectedTag),
+ queryFn: forumFeedPageQueryFn(channelId, selectedTag, queryClient),
initialPageParam: null,
getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,
})
@@ -162,9 +229,9 @@ export function useForumFeed(_serverId: string, channelId: string) {
queryClient,
channelId,
selectedTag,
- mapForumFeedPages(query.data?.pages ?? []),
+ mapForumFeedPages(query.data?.pages ?? [], canonicalMessages),
),
- [channelId, query.data?.pages, queryClient, selectedTag],
+ [canonicalMessages, channelId, query.data?.pages, queryClient, selectedTag],
)
return {
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 eace89d2a..b10476c74 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
@@ -1,8 +1,19 @@
+import "fake-indexeddb/auto"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { renderHook, waitFor } from "@/test/react-dom-harness"
import { communityKeys } from "@/lib/query-keys"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityMessages,
+} from "@/lib/community-db/sync"
+import { useCommunityWsStore } from "@/stores/community/ws"
import { useForumOpenerHint } from "./use-forum-opener-hint"
const apiFetchMock = vi.fn()
@@ -16,7 +27,31 @@ function wrapperFor(queryClient: QueryClient) {
}
}
-beforeEach(() => apiFetchMock.mockReset())
+const cleanups: Array<() => void | Promise<void>> = []
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+ useCommunityWsStore.getState().reset()
+ useCommunityWsStore.getState().activateProfileAccount("viewer")
+})
+
+afterEach(async () => {
+ await Promise.all(cleanups.splice(0).map((dispose) => dispose()))
+})
+
+async function canonicalSetup() {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ cleanups.push(unregister, registry.cleanup.bind(registry))
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(CommunityDbProvider, { registry }, children),
+ )
+ return { queryClient, wrapper }
+}
describe("useForumOpenerHint", () => {
it("does not fetch or authorize content before the route metadata is verified", () => {
@@ -45,10 +80,13 @@ describe("useForumOpenerHint", () => {
})
await waitFor(() => {
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/messages/opener-1")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/messages/opener-1",
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ )
})
expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "opener-1"),
+ communityKeys.message("opener-1"),
)).toEqual({
id: "opener-1",
content: "Seeded",
@@ -56,4 +94,53 @@ describe("useForumOpenerHint", () => {
channelId: "forum-1",
})
})
+
+ it("exposes a warm canonical opener without waiting for its background transport", async () => {
+ const { queryClient, wrapper } = await canonicalSetup()
+ publishCommunityMessages(queryClient, {
+ channelId: "forum-1",
+ messages: [{
+ id: "opener-1",
+ channelId: "forum-1",
+ type: "chat",
+ content: "Warm title",
+ seq: 7,
+ }],
+ proof: {
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
+ })
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
+
+ const rendered = renderHook(
+ () => useForumOpenerHint("server-1", "opener-1", true),
+ { wrapper },
+ )
+
+ await waitFor(() => expect(rendered.result.current.data).toEqual({
+ id: "opener-1",
+ content: "Warm title",
+ seq: 7,
+ }))
+ expect(rendered.result.current.fetchStatus).toBe("fetching")
+ expect(rendered.result.current.isLoading).toBe(false)
+ rendered.unmount()
+ })
+
+ it("keeps a cold canonical opener loading while its transport is pending", async () => {
+ const { wrapper } = await canonicalSetup()
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
+
+ const rendered = renderHook(
+ () => useForumOpenerHint("server-1", "opener-1", true),
+ { wrapper },
+ )
+
+ await waitFor(() => expect(rendered.result.current.fetchStatus).toBe("fetching"))
+ expect(rendered.result.current.data).toBeUndefined()
+ expect(rendered.result.current.isLoading).toBe(true)
+ rendered.unmount()
+ })
+
})
diff --git a/src/web/src/hooks/community/use-forum-opener-hint.ts b/src/web/src/hooks/community/use-forum-opener-hint.ts
index 0df22bb16..1a2ff3183 100644
--- a/src/web/src/hooks/community/use-forum-opener-hint.ts
+++ b/src/web/src/hooks/community/use-forum-opener-hint.ts
@@ -4,6 +4,14 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { ForumOpenerHint } from "@/hooks/community/use-forum-sidebar-threads"
+import {
+ useCanonicalMessagesById,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityMessages,
+} from "@/lib/community-db/sync"
export function useForumOpenerHint(
serverId: string,
@@ -11,20 +19,28 @@ export function useForumOpenerHint(
enabled: boolean,
) {
const active = enabled && !!messageId
+ const registry = useOptionalCommunityDbRegistry()
+ const canonicalMessages = useCanonicalMessagesById()
const queryClient = useQueryClient()
- const queryKey = communityKeys.forumOpenerHint(serverId, messageId ?? "__none__")
- const cached = queryClient.getQueryData<ForumOpenerHint>(queryKey)
- return useQuery<ForumOpenerHint>({
- queryKey,
- queryFn: async () => {
+ const query = useQuery<ForumOpenerHint>({
+ queryKey: communityKeys.message(messageId ?? "__none__"),
+ queryFn: async ({ signal }) => {
+ const token = captureCommunityLiveSnapshotToken(queryClient)
const message = await apiFetch<{
id: string
content: string
seq: number
channelId: string
+ type: "chat" | "system"
}>(
`/api/community/messages/${messageId}`,
+ { signal },
)
+ publishCommunityMessages(queryClient, {
+ channelId: message.channelId,
+ messages: [message],
+ proof: { token, signal },
+ })
return {
id: message.id,
content: message.content,
@@ -33,7 +49,19 @@ export function useForumOpenerHint(
}
},
enabled: active,
- staleTime: cached?.seq === undefined ? 0 : Infinity,
+ staleTime: Infinity,
gcTime: 5 * 60 * 1000,
})
+ const canonical = messageId ? canonicalMessages?.get(messageId) : undefined
+ const data = canonical && typeof canonical.content === "string"
+ ? {
+ id: canonical.id,
+ content: canonical.content,
+ ...(canonical.seq === undefined ? {} : { seq: canonical.seq }),
+ }
+ : undefined
+ void serverId
+ return registry
+ ? { ...query, data, isLoading: query.isLoading && data === undefined }
+ : query
}
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 9ec96defa..d2df04322 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
@@ -1,1759 +1,908 @@
+import "fake-indexeddb/auto"
+import { createElement, type PropsWithChildren } from "react"
+import { dehydrate, hydrate, QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import React from "react"
-import { act, render as rtlRender } from "@/test/react-dom-harness"
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { createCommunityDbRegistry, registerCommunityDbRegistry } from "@/lib/community-db/collections"
+import { CommunityDbProvider, useForumSidebarProjection } from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ ingestAttentionSnapshot,
+ ingestServerDetail,
+ ingestServers,
+ getCanonicalCommunityChannels,
+ getCanonicalCommunityMessages,
+ projectCommunityWsEventToDb,
+ publishCommunityForumSidebar,
+ removeCanonicalCommunityChannelMembership,
+ setCanonicalCommunityChannelMembership,
+} from "@/lib/community-db/sync"
+import { useCommunityWsStore } from "@/stores/community/ws"
import { communityKeys } from "@/lib/query-keys"
import {
deriveForumSidebarProjection,
+ getForumSidebarBase,
grantForumSidebarChild,
- hasForumSidebarOwnershipEvidence,
invalidateForumSidebarBaseExact,
+ normalizeForumSidebarEnvelope,
patchForumSidebarActivityExact,
patchForumSidebarTitleExact,
- removeForumSidebarThreadExact,
- normalizeForumSidebarEnvelope,
- patchForumSidebarActivity,
- patchForumSidebarUnread,
- projectForumSidebarThreads,
+ reconcileForumSidebarNotifyMemberships,
reconcileForumSidebarArchiveTag,
- reconcileForumSidebarUnreadFallbacks,
- recordForumSidebarChildUnread,
- removeForumSidebarThread,
- removeForumSidebarUnreadChild,
- restoreForumSidebarThreadInflight,
+ removeForumSidebarChildrenForParent,
+ removeForumSidebarProjectionExact,
+ removeForumSidebarThreadExact,
resolveForumSidebarRouteCandidate,
- setForumSidebarParentUnreadBase,
- type ForumSidebarQueryData,
- type ForumSidebarThread,
- type ForumSidebarUnreadFallbackState,
- type SidebarThreadEnvelope,
+ restoreForumSidebarThreadInflight,
useForumSidebarThreads,
+ type SidebarThreadEnvelope,
} from "./use-forum-sidebar-threads"
-import type { ServerDetail } from "./use-servers"
-import { useCommunityWsStore } from "@/stores/community/ws"
-import { getActiveAccountUnreadProjection } from "./account-unread-projection"
+import {
+ clearPersistedCache,
+ createIdbPersister,
+ PERSIST_BUSTER,
+} from "@/lib/query-persister"
-const apiFetchMock = vi.fn()
+const apiFetchMock = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
-const envelope = (ids: string[]): SidebarThreadEnvelope => ({
- channels: ids.map((id, index) => ({
- id,
- name: `fallback-${id}`,
- parentChannelId: "forum-1",
- parentMessageId: `opener-${id}`,
- activityAt: `2026-08-08T0${index}:00:00.000Z`,
- expiresAt: `2026-08-11T0${index}:00:00.000Z`,
- unread: index === 0,
- serverId: "server-1",
- type: "thread",
- creatorId: "creator-1",
- archived: false,
- createdAt: `2026-08-08T0${index}:00:00.000Z`,
- })),
- included: {
- parentMessages: ids.map((id) => ({ id: `opener-${id}`, content: `title-${id}` })),
- },
- serverNow: "2026-08-08T00:00:00.000Z",
-})
-
-function Capture({ retainId, onRender, enabled }: {
- retainId: string | null
- onRender: (ids: string[]) => void
- enabled?: boolean
-}) {
- const result = useForumSidebarThreads("server-1", retainId, enabled)
- onRender(result.threads.map((thread) => thread.id))
- return null
-}
-
-async function waitFor(predicate: () => boolean) {
- for (let i = 0; i < 40 && !predicate(); i++) {
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 5))
- })
- }
-}
+const cleanups: Array<() => void | Promise<void>> = []
beforeEach(() => {
apiFetchMock.mockReset()
useCommunityWsStore.getState().reset()
- useCommunityWsStore.getState().markAccessConnected()
})
-afterEach(() => {
+afterEach(async () => {
vi.useRealTimers()
- useCommunityWsStore.getState().reset()
+ await Promise.all(cleanups.splice(0).map((dispose) => dispose()))
})
-function serverDetail(parentUnread: boolean): ServerDetail {
+function envelope(overrides: Partial<SidebarThreadEnvelope> = {}): SidebarThreadEnvelope {
+ const activityAt = new Date(Date.now() - 60_000).toISOString()
return {
+ channels: [{
+ id: "post-1",
+ name: "fallback",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ activityAt,
+ expiresAt: new Date(Date.parse(activityAt) + 72 * 60 * 60 * 1000).toISOString(),
+ unread: true,
+ serverId: "server-1",
+ type: "thread",
+ creatorId: "viewer",
+ archived: false,
+ lastMessageAt: activityAt,
+ }],
+ included: {
+ parentMessages: [{
+ id: "opener-1",
+ content: "Canonical title",
+ seq: 1,
+ channelId: "forum-1",
+ type: "chat",
+ }],
+ },
+ serverNow: new Date().toISOString(),
+ ...overrides,
+ }
+}
+
+function envelopeFor(ids: string[]): SidebarThreadEnvelope {
+ const activityAt = new Date(Date.now() - 60_000).toISOString()
+ return envelope({
+ channels: ids.map((id) => ({
+ id,
+ name: `fallback-${id}`,
+ parentChannelId: "forum-1",
+ parentMessageId: `opener-${id}`,
+ activityAt,
+ expiresAt: new Date(Date.parse(activityAt) + 72 * 60 * 60 * 1000).toISOString(),
+ unread: false,
+ serverId: "server-1",
+ type: "thread",
+ creatorId: "viewer",
+ archived: false,
+ lastMessageAt: activityAt,
+ })),
+ included: {
+ parentMessages: ids.map((id) => ({
+ id: `opener-${id}`,
+ content: `title-${id}`,
+ channelId: "forum-1",
+ type: "chat" as const,
+ })),
+ },
+ })
+}
+
+async function setup() {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ cleanups.push(unregister, registry.cleanup.bind(registry))
+ ingestServers(registry, {
+ servers: [{
+ id: "server-1",
+ name: "Server",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ }],
+ })
+ ingestServerDetail(registry, {
id: "server-1",
name: "Server",
+ discriminator: "0001",
description: "",
icon: null,
- ownerId: "owner-1",
+ ownerId: "viewer",
categories: [{
- id: "category-1",
- name: "Channels",
- private: 0,
+ id: "cat-1",
+ name: "Forums",
channels: [{
id: "forum-1",
- name: "Forum",
- type: "forum",
+ name: "forum",
active: false,
- unread: parentUnread,
- muted: false,
+ unread: false,
+ type: "forum",
}],
}],
- }
+ })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(CommunityDbProvider, { registry }, children),
+ )
+ return { queryClient, registry, wrapper }
}
-function parentUnread(queryClient: QueryClient): boolean {
- return !!queryClient.getQueryData<ServerDetail>(communityKeys.server("server-1"))
- ?.categories[0]?.channels[0]?.unread
+function publish(queryClient: QueryClient, data = envelope()) {
+ const normalized = normalizeForumSidebarEnvelope(data, null)
+ publishCommunityForumSidebar(queryClient, {
+ serverId: "server-1",
+ channels: data.channels,
+ openers: data.included.parentMessages,
+ proof: {
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
+ })
+ return normalized
}
-describe("useForumSidebarThreads", () => {
- it("projects a read thread from server-detail source evidence", async () => {
- apiFetchMock.mockResolvedValue(envelope(["post-1"]))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- queryClient.setQueryData(communityKeys.server("server-1"), {
- ...serverDetail(true),
- forumUnreadState: {
- "forum-1": { baseUnread: false, childIds: ["post-1"] },
- },
- unreadSources: [{
- channelId: "post-1",
- lastUnreadSeq: 2,
- lastAttentionSeq: null,
- }],
- } satisfies ServerDetail)
- getActiveAccountUnreadProjection(queryClient).recordRead("post-1", 2)
- function Harness() {
- const result = useForumSidebarThreads("server-1", null)
- return React.createElement("output", {
- "data-count": result.threads.length,
- "data-unread": String(result.threads[0]?.unread),
- })
- }
- let renderer!: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Harness),
- ))
- })
- await waitFor(() => (
- renderer.container.querySelector("output")?.getAttribute("data-count") === "1"
- ))
- const raw = queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads[0]
- expect(raw?.unread).toBe(true)
- expect(renderer.container.querySelector("output")).toHaveAttribute("data-unread", "false")
- await act(async () => renderer.unmount())
- })
-
- it("confirms a freshly retained child as authoritative access", async () => {
- const base = envelope([])
- const retained = envelope(["post-1"])
- apiFetchMock
- .mockResolvedValueOnce(base)
- .mockResolvedValueOnce({
- ...base,
- canonicalChannels: [],
- retainedChannel: retained.channels[0],
- retainedDisposition: "eligible",
- included: retained.included,
- })
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const projection = getActiveAccountUnreadProjection(queryClient)
- projection.retireAccessScope({ kind: "channel", channelId: "post-1" })
- projection.grantAccessScope({ kind: "channel", channelId: "post-1" })
- projection.recordArrival({ channelId: "post-1", serverId: "server-1", seq: 2 })
- expect(projection.projectUnread("inbox-unreads", "post-1", false, 2)).toBe(false)
+describe("forum sidebar canonical projection", () => {
+ it("classifies retained route candidates and bounded active extras", () => {
+ expect(resolveForumSidebarRouteCandidate(null, ["forum-1"], true)).toBeNull()
+ expect(resolveForumSidebarRouteCandidate("forum-1", ["forum-1"], true)).toBeNull()
+ expect(resolveForumSidebarRouteCandidate("post-3", ["forum-1"], true)).toBe("post-3")
- let renderer!: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ))
- })
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
- await act(async () => {
- renderer.rerender(React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "post-1", onRender: () => undefined }),
- ))
+ const base = normalizeForumSidebarEnvelope(envelopeFor(["post-1", "post-2"]), null, 0).base
+ const extra = normalizeForumSidebarEnvelope(envelopeFor(["post-3"]), null, 0).base.threads[0]!
+ expect(deriveForumSidebarProjection(
+ base,
+ extra,
+ { "forum-1": { baseUnread: false, childIds: ["post-3"] } },
+ Date.parse(base.serverNow),
+ 2,
+ )).toMatchObject({
+ threads: expect.arrayContaining([expect.objectContaining({ id: "post-3", unread: true })]),
+ parentUnread: { "forum-1": false },
})
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarRetained("server-1", "post-1"),
- )?.status === "success")
-
- expect(projection.projectUnread("inbox-unreads", "post-1", false, 2)).toBe(true)
- await act(async () => renderer.unmount())
})
- it("preserves a genuine parent unread when a child fallback becomes locatable", () => {
- const queryClient = new QueryClient()
- queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(true))
- recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-1")
-
- reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
-
- expect(parentUnread(queryClient)).toBe(true)
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )).toEqual({})
+ it("ignores incomplete child metadata while normalizing", () => {
+ const response = envelope()
+ response.channels[0] = { ...response.channels[0]!, serverId: undefined }
+ expect(normalizeForumSidebarEnvelope(response, null, 0).channelMetas).toEqual({})
})
- it("preserves a parent unread that arrives while a child fallback is pending", () => {
- const queryClient = new QueryClient()
- queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
- recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-1")
- expect(setForumSidebarParentUnreadBase(queryClient, "server-1", "forum-1", true)).toBe(true)
-
- reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
+ it("removes only bounded-base misses that could displace the authoritative top five", async () => {
+ const { queryClient, registry } = await setup()
+ const now = Date.now()
+ const stale = envelopeFor([
+ "post-archived",
+ "post-left",
+ "post-retained",
+ "Z-retained",
+ "post-expired",
+ "post-invalid",
+ ])
+ stale.channels[0]!.activityAt = new Date(now - 30_000).toISOString()
+ stale.channels[0]!.lastMessageAt = stale.channels[0]!.activityAt
+ stale.channels[1]!.activityAt = new Date(now - 40_000).toISOString()
+ stale.channels[1]!.lastMessageAt = stale.channels[1]!.activityAt
+ stale.channels[2]!.activityAt = new Date(now - 180_000).toISOString()
+ stale.channels[2]!.lastMessageAt = stale.channels[2]!.activityAt
+ stale.channels[3]!.activityAt = new Date(now - 120_000).toISOString()
+ stale.channels[3]!.lastMessageAt = stale.channels[3]!.activityAt
+ stale.channels[4]!.activityAt = new Date(now - (73 * 60 * 60 * 1000)).toISOString()
+ stale.channels[4]!.lastMessageAt = stale.channels[4]!.activityAt
+ stale.channels[5]!.activityAt = "invalid"
+ stale.channels[5]!.lastMessageAt = "invalid"
+ publish(queryClient, stale)
+ const fresh = envelopeFor(["z-fresh", "y-fresh", "x-fresh", "w-fresh", "a-cutoff"])
+ for (const channel of fresh.channels) {
+ channel.activityAt = new Date(now - 120_000).toISOString()
+ channel.lastMessageAt = channel.activityAt
+ }
+ apiFetchMock.mockResolvedValue({ ...fresh, canonicalChannels: fresh.channels })
+
+ const result = await reconcileForumSidebarNotifyMemberships(queryClient, "server-1")
+
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(result.removedIds).toEqual(expect.arrayContaining(["post-archived", "post-left"]))
+ expect(result.removedIds).not.toContain("post-expired")
+ await waitFor(() => {
+ expect(registry.collections.channelMemberships.get("post-archived:viewer:notify"))
+ .toBeUndefined()
+ expect(registry.collections.channelMemberships.get("post-left:viewer:notify"))
+ .toBeUndefined()
+ })
+ expect(registry.collections.channelMemberships.get("post-retained:viewer:notify"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("Z-retained:viewer:notify"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("z-fresh:viewer:notify"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("post-archived:viewer:access"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("post-left:viewer:access"))
+ .toBeDefined()
+ })
+
+ it("uses one authoritative reconnect fetch with an active base observer", async () => {
+ const { queryClient, wrapper } = await setup()
+ apiFetchMock.mockResolvedValue(envelope())
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
+ )
+ await waitFor(() => expect(rendered.result.current.isSuccess).toBe(true))
+ apiFetchMock.mockClear()
- expect(parentUnread(queryClient)).toBe(true)
- })
+ await reconcileForumSidebarNotifyMemberships(queryClient, "server-1")
- it("keeps the parent fallback while another unread child is still unlisted", () => {
- const queryClient = new QueryClient()
- queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
- recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-1")
- recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-2")
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )?.["forum-1"]?.childIds).toEqual(["post-1", "post-2"])
-
- reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
- expect(parentUnread(queryClient)).toBe(true)
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )?.["forum-1"]?.childIds).toEqual(["post-2"])
-
- reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1", "post-2"])
- expect(parentUnread(queryClient)).toBe(false)
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ rendered.unmount()
})
- it("transfers a loaded unread child back to its parent when top-five/expiry hides it", async () => {
- apiFetchMock
- .mockResolvedValueOnce(envelope(["post-1"]))
- .mockResolvedValueOnce(envelope([]))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- queryClient.setQueryData(communityKeys.server("server-1"), {
- ...serverDetail(true),
- forumUnreadState: {
- "forum-1": { baseUnread: false, childIds: ["post-1"] },
- },
- })
+ 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"]))
+ removeCanonicalCommunityChannelMembership(queryClient, "post-ws", "notify")
+ let settle!: (value: SidebarThreadEnvelope) => void
+ apiFetchMock.mockReturnValue(new Promise<SidebarThreadEnvelope>((resolve) => {
+ settle = resolve
+ }))
- let renderer: ReturnType<typeof rtlRender>
- const renders: string[][] = []
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- })
- await waitFor(() => renders.at(-1)?.[0] === "post-1")
- await waitFor(() => Object.keys(
- queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- ) ?? {},
- ).length === 0)
-
- expect(parentUnread(queryClient)).toBe(false)
- await act(async () => {
- await queryClient.invalidateQueries({
- queryKey: communityKeys.forumSidebarThreads("server-1"),
- })
- })
- await waitFor(() => renders.at(-1)?.length === 0)
- await waitFor(() => parentUnread(queryClient))
+ const pending = reconcileForumSidebarNotifyMemberships(queryClient, "server-1")
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ setCanonicalCommunityChannelMembership(
+ queryClient,
+ "post-ws",
+ "notify",
+ true,
+ { event: true },
+ )
+ settle(envelopeFor(["post-fresh"]))
+ await pending
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )).toEqual({
- "forum-1": { baseUnread: false, childIds: ["post-1"] },
- })
- renderer!.unmount()
+ expect(registry.collections.channelMemberships.get("post-ws:viewer:notify"))
+ .toBeDefined()
})
- it("does not create a fallback after an explicit leave/delete/archive removal", () => {
- const queryClient = new QueryClient()
- queryClient.setQueryData(communityKeys.server("server-1"), {
- ...serverDetail(false),
- forumUnreadState: {
- "forum-1": { baseUnread: false, childIds: ["post-1"] },
- },
- })
- reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", ["post-1"])
+ it("keeps warm DB rows visible while the HTTP transport is stalled", async () => {
+ const { queryClient, wrapper } = await setup()
+ publish(queryClient)
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
- removeForumSidebarUnreadChild(queryClient, "server-1", "post-1")
- reconcileForumSidebarUnreadFallbacks(queryClient, "server-1", [])
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
+ )
- expect(parentUnread(queryClient)).toBe(false)
- expect(queryClient.getQueryData<ServerDetail>(
- communityKeys.server("server-1"),
- )?.forumUnreadState?.["forum-1"]?.childIds).toEqual([])
- })
+ await waitFor(() => expect(rendered.result.current.threads).toEqual([
+ expect.objectContaining({ id: "post-1", title: "Canonical title", unread: false }),
+ ]))
+ expect(rendered.result.current.projectionReady).toBe(true)
+ expect(rendered.result.current.fetchStatus).toBe("fetching")
+ rendered.unmount()
+ await invalidateForumSidebarBaseExact(queryClient, "server-1")
+ })
+
+ it("removes a restored notify row displaced by the fresh bounded window", async () => {
+ const { queryClient, registry, wrapper } = await setup()
+ const restored = envelopeFor([
+ "post-6",
+ "post-5",
+ "post-4",
+ "post-3",
+ "post-2",
+ ])
+ publish(queryClient, restored)
+ const fresh = envelopeFor([
+ "post-5",
+ "post-4",
+ "post-3",
+ "post-2",
+ "post-1",
+ ])
+ for (const channel of fresh.channels) {
+ channel.activityAt = restored.channels[0]!.activityAt
+ channel.lastMessageAt = channel.activityAt
+ }
+ apiFetchMock.mockResolvedValue({ ...fresh, canonicalChannels: fresh.channels })
- it("clears a hidden fallback when a canonical refetch removes access or participation", async () => {
- apiFetchMock.mockResolvedValue(envelope([]))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- queryClient.setQueryData(communityKeys.server("server-1"), {
- ...serverDetail(true),
- forumUnreadState: {
- "forum-1": { baseUnread: false, childIds: ["post-inaccessible"] },
- },
- })
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
+ )
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )?.["forum-1"]?.childIds[0] === "post-inaccessible")
+ await waitFor(() => expect(rendered.result.current.isSuccess).toBe(true))
+ await waitFor(() => expect(rendered.result.current.threads.map(({ id }) => id)).toEqual([
+ "post-5",
+ "post-4",
+ "post-3",
+ "post-2",
+ "post-1",
+ ]))
+ expect(registry.collections.channelMemberships.get("post-6:viewer:notify"))
+ .toBeUndefined()
+ expect(registry.collections.channelMemberships.get("post-6:viewer:access"))
+ .toBeDefined()
+ rendered.unmount()
+ })
+
+ it("keeps an unverified cold empty projection pending while HTTP is stalled", async () => {
+ const { queryClient, wrapper } = await setup()
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
+
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
+ )
+ await waitFor(() => expect(rendered.result.current.fetchStatus).toBe("fetching"))
await act(async () => {
- queryClient.setQueryData(communityKeys.server("server-1"), {
- ...serverDetail(false),
- forumUnreadState: {
- "forum-1": { baseUnread: false, childIds: [] },
- },
- })
+ await new Promise((resolve) => setTimeout(resolve, 0))
})
- await waitFor(() => Object.keys(
- queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- ) ?? {},
- ).length === 0)
-
- expect(parentUnread(queryClient)).toBe(false)
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )).toEqual({})
- renderer!.unmount()
+ expect(rendered.result.current.threads).toEqual([])
+ expect(rendered.result.current.projectionReady).toBe(false)
+ rendered.unmount()
+ await invalidateForumSidebarBaseExact(queryClient, "server-1")
})
- it("migrates a missing-child fallback dot to the child after the sidebar refetch", async () => {
- apiFetchMock.mockResolvedValue(envelope(["post-missing"]))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const sidebarKey = communityKeys.forumSidebarThreads("server-1")
- queryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, {
- ...envelope([]),
- threads: [],
- serverClockOffsetMs: 0,
- })
- queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
-
- // message.create invalidates the missing row; unread.bump temporarily owns
- // the parent fallback while that refetch is outstanding.
- await queryClient.invalidateQueries({ queryKey: communityKeys.forumSidebarThreads("server-1") })
- recordForumSidebarChildUnread(queryClient, "server-1", "forum-1", "post-missing")
- expect(parentUnread(queryClient)).toBe(true)
-
- let renderer: ReturnType<typeof rtlRender>
- const renders: string[][] = []
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- })
- await waitFor(() => renders.at(-1)?.[0] === "post-missing")
- await waitFor(() => !parentUnread(queryClient))
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(true)
- expect(parentUnread(queryClient)).toBe(false)
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )).toEqual({})
-
- queryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, (data) =>
- patchForumSidebarUnread(data, "post-missing", false),
+ it("publishes an HTTP response once and renders later WS edits from the same rows", async () => {
+ const { queryClient, wrapper } = await setup()
+ apiFetchMock.mockResolvedValue(envelope())
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
)
- expect(queryClient.getQueryData<ForumSidebarQueryData>(sidebarKey)?.threads[0]?.unread).toBe(false)
- expect(parentUnread(queryClient)).toBe(false)
- renderer!.unmount()
- })
- it("expires live activity 72h after the event instead of reusing the old serverNow", async () => {
- vi.useFakeTimers()
- vi.setSystemTime(new Date("2026-08-08T00:00:00.000Z"))
- apiFetchMock.mockResolvedValue(envelope(["thread-1"]))
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: Infinity } },
- })
- const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries")
- let renderer: ReturnType<typeof rtlRender>
- const renders: string[][] = []
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- })
- await act(async () => {
- await vi.advanceTimersByTimeAsync(0)
- })
- expect(renders.at(-1)).toEqual(["thread-1"])
- invalidateSpy.mockClear()
- apiFetchMock.mockRejectedValueOnce(new Error("offline"))
-
- act(() => vi.advanceTimersByTime(10 * 60 * 60 * 1000))
- const key = communityKeys.forumSidebarThreads("server-1")
- await act(async () => {
- queryClient.setQueryData<ForumSidebarQueryData>(key, (data) =>
- patchForumSidebarActivity(
- data,
- "thread-1",
- "forum-1",
- "2026-08-08T10:00:00.000Z",
- ),
- )
- await vi.advanceTimersByTimeAsync(0)
- })
-
- act(() => vi.advanceTimersByTime((72 * 60 * 60 * 1000) + 24))
- expect(invalidateSpy).not.toHaveBeenCalled()
- await act(async () => { await vi.advanceTimersByTimeAsync(1) })
- expect(invalidateSpy).toHaveBeenCalledWith({
- queryKey: communityKeys.forumSidebarThreads("server-1"),
- exact: true,
- refetchType: "active",
- })
- await act(async () => { await vi.advanceTimersByTimeAsync(1) })
- expect(queryClient.getQueryData<ForumSidebarQueryData>(key)?.threads).toEqual([])
- expect(JSON.stringify(queryClient.getQueryData(key))).not.toContain("thread-1")
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "thread-1"),
- )).toMatchObject({ id: "thread-1", parentChannelId: "forum-1" })
- expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "opener-thread-1"),
- )).toEqual({ id: "opener-thread-1", content: "title-thread-1" })
- expect(renders.at(-1)).toEqual([])
- renderer!.unmount()
+ await waitFor(() => expect(rendered.result.current.threads[0]?.title)
+ .toBe("Canonical title"))
+ act(() => projectCommunityWsEventToDb(queryClient, {
+ type: "community:message.edited",
+ channelId: "forum-1",
+ messageId: "opener-1",
+ content: "WS title",
+ }))
+ await waitFor(() => expect(rendered.result.current.threads[0]?.title).toBe("WS title"))
})
- it("retains a warm canonical route through expiry and offline refresh until navigation and GC", async () => {
- vi.useFakeTimers()
- vi.setSystemTime(new Date("2026-08-08T00:00:00.000Z"))
- apiFetchMock.mockRejectedValue(new Error("offline"))
- const source = envelope(["canonical-a"])
- source.channels[0]!.expiresAt = "2026-08-08T00:00:00.100Z"
- const normalized = normalizeForumSidebarEnvelope({
- ...source,
- canonicalChannels: source.channels,
- retainedChannel: null,
- }, null, 0)
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
- queryClient.setQueryData(
- communityKeys.forumSidebarThreads("server-1"),
- { ...normalized.base, verifiedEpoch: 0 },
+ it("normalizes a persisted default opener before one successful canonical publish", async () => {
+ const { queryClient, wrapper } = await setup()
+ const response = envelope()
+ response.included.parentMessages[0]!.type = "default" as never
+ apiFetchMock.mockResolvedValue(response)
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", "post-1"),
+ { wrapper },
)
- const renders: string[][] = []
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- await vi.advanceTimersByTimeAsync(0)
- })
- expect(renders.at(-1)).toEqual(["canonical-a"])
-
- await act(async () => {
- renderer!.rerender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: "canonical-a",
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- await vi.advanceTimersByTimeAsync(0)
- })
- const retainedKey = communityKeys.forumSidebarRetained("server-1", "canonical-a")
- expect(queryClient.getQueryData<ForumSidebarThread>(retainedKey)?.id).toBe("canonical-a")
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(126)
- })
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads).toEqual([])
- expect(renders.at(-1)).toEqual(["canonical-a"])
-
- await act(async () => {
- renderer!.rerender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- await vi.advanceTimersByTimeAsync(0)
- })
- expect(renders.at(-1)).toEqual([])
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync((5 * 60 * 1000) + 1)
- })
- expect(queryClient.getQueryState(retainedKey)).toBeUndefined()
- renderer!.unmount()
+ await waitFor(() => expect(rendered.result.current.isSuccess).toBe(true))
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(getCanonicalCommunityMessages(queryClient)).toContainEqual(
+ expect.objectContaining({ id: "opener-1", type: "chat" }),
+ )
+ rendered.unmount()
})
- it("keeps the cached list painted while a retainId-specific view is loading", async () => {
- let resolveRetained: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock
- .mockResolvedValueOnce(envelope(["thread-1"]))
- .mockImplementationOnce(() => new Promise((resolve) => {
- resolveRetained = resolve
- }))
+ it("stores opener-archive exclusion without archiving the child route", async () => {
+ const { queryClient, registry, wrapper } = await setup()
+ publish(queryClient)
+ const rendered = renderHook(
+ () => useForumSidebarProjection("server-1", null, Date.now()),
+ { wrapper },
+ )
+ await waitFor(() => expect(rendered.result.current?.threads).toHaveLength(1))
- const renders: string[][] = []
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
+ await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", true)
})
- await waitFor(() => renders.at(-1)?.[0] === "thread-1")
- const switchRenderStart = renders.length
+ await waitFor(() => expect(rendered.result.current?.threads).toEqual([]))
+ expect(registry.collections.channels.get("post-1")).toMatchObject({ archived: false })
+ expect(registry.collections.channelMemberships.get("post-1:viewer:access"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("post-1:viewer:notify"))
+ .toBeUndefined()
await act(async () => {
- renderer!.rerender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: "thread-2",
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
+ await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", false)
})
-
- expect(renders.slice(switchRenderStart)).not.toContainEqual([])
- expect(renders.at(-1)).toEqual(["thread-1"])
- expect(apiFetchMock.mock.calls[1]?.[0]).toContain("retainId=thread-2")
-
- await act(async () => {
- resolveRetained?.(envelope(["thread-2"]))
- })
- await waitFor(() => renders.at(-1)?.[0] === "thread-2")
- expect(renders.at(-1)).toEqual(["thread-2"])
- expect(renders.slice(switchRenderStart)).not.toContainEqual([])
- renderer!.unmount()
+ await waitFor(() => expect(rendered.result.current?.threads).toHaveLength(1))
+ expect(registry.collections.channelMemberships.get("post-1:viewer:notify"))
+ .toBeDefined()
})
- it("projects opener titles and patches activity/removal without mutating the source", () => {
- const source = envelope(["thread-1", "thread-2"])
- const threads = projectForumSidebarThreads(source)
- const data = { ...source, threads, serverClockOffsetMs: 0 }
-
- expect(threads.map((thread) => thread.title)).toEqual(["title-thread-1", "title-thread-2"])
- const patched = patchForumSidebarActivity(
- data,
- "thread-1",
- "forum-1",
- "2026-08-09T00:00:00.000Z",
- )
- expect(patched?.threads[0]?.id).toBe("thread-1")
- expect(patched?.threads[0]?.expiresAt).toBe("2026-08-12T00:00:00.000Z")
- expect(data.threads[0]?.activityAt).toBe("2026-08-08T00:00:00.000Z")
- expect(removeForumSidebarThread(patched, "thread-1")?.threads.map((thread) => thread.id))
- .toEqual(["thread-2"])
- expect(patchForumSidebarUnread(data, "thread-1", false)?.threads[0]?.unread).toBe(false)
- })
-})
+ it("keeps only request-clock data in the transport cache under a DB provider", async () => {
+ const { queryClient, wrapper } = await setup()
+ apiFetchMock.mockResolvedValue(envelope())
+ const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
-describe("forum sidebar Stage B resources", () => {
- it("retains only child routes whose exact metadata confirms a forum parent", () => {
- expect(resolveForumSidebarRouteCandidate("general", ["general", "forum"], true)).toBeNull()
- expect(resolveForumSidebarRouteCandidate("post-1", ["general", "forum"], true)).toBe("post-1")
- expect(resolveForumSidebarRouteCandidate("thread-1", ["general", "forum"], false)).toBeNull()
- expect(resolveForumSidebarRouteCandidate("post-1", ["general", "forum"], null)).toBeNull()
- expect(resolveForumSidebarRouteCandidate("post-1", null, true)).toBeNull()
+ await waitFor(() => expect(queryClient.getQueryData<{
+ threads: unknown[]
+ serverNow: string
+ }>(communityKeys.forumSidebarThreads("server-1")))
+ .toMatchObject({ threads: [], serverNow: expect.any(String) }))
+ rendered.unmount()
})
- it("requires positive forum ownership evidence", () => {
- const queryClient = new QueryClient()
- expect(hasForumSidebarOwnershipEvidence(queryClient, "server-1", "child-1"))
- .toBe(false)
-
- const detail = serverDetail(false)
- detail.categories[0]!.channels.push({
- id: "general-1",
- name: "General",
- type: "text",
- active: false,
- unread: false,
- muted: false,
- })
- queryClient.setQueryData(communityKeys.server("server-1"), detail)
- queryClient.setQueryData(communityKeys.channelMeta("server-1", "child-1"), {
- id: "child-1",
- serverId: "server-1",
- name: "Thread",
- type: "thread",
- parentChannelId: "general-1",
- parentMessageId: "message-1",
- creatorId: "user-1",
- archived: false,
- activityAt: "2026-08-08T00:00:00.000Z",
- verifiedEpoch: 0,
- })
- queryClient.setQueryData(
- communityKeys.forumSidebarRetained("server-1", "child-1"),
- projectForumSidebarThreads(envelope(["child-1"]))[0],
- )
- expect(hasForumSidebarOwnershipEvidence(queryClient, "server-1", "child-1"))
- .toBe(false)
-
- queryClient.setQueryData(communityKeys.channelMeta("server-1", "child-1"), {
- ...queryClient.getQueryData<ChildChannelMeta>(
- communityKeys.channelMeta("server-1", "child-1"),
- )!,
- parentChannelId: "forum-1",
+ it("keeps providerless normalization explicit for pure tests", () => {
+ const normalized = normalizeForumSidebarEnvelope(envelope(), null, 0)
+ expect(deriveForumSidebarProjection(
+ normalized.base,
+ null,
+ { "forum-1": { baseUnread: false, childIds: ["post-1"] } },
+ Date.parse(normalized.base.serverNow),
+ )).toEqual({
+ threads: [expect.objectContaining({ id: "post-1", unread: true })],
+ parentUnread: { "forum-1": false },
})
- expect(hasForumSidebarOwnershipEvidence(queryClient, "server-1", "child-1"))
- .toBe(true)
})
- it("settles an omitted text-thread candidate without deleting exact metadata", async () => {
- apiFetchMock.mockResolvedValue({
- ...envelope([]),
- canonicalChannels: [],
- retainedChannel: null,
- })
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const detail = serverDetail(false)
- detail.categories[0]!.channels.push({
- id: "general-1",
- name: "General",
- type: "text",
- active: false,
- unread: false,
- muted: false,
- })
- queryClient.setQueryData(communityKeys.server("server-1"), detail)
- let renderer: ReturnType<typeof rtlRender>
- const tree = (retainId: string | null) => React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId, onRender: () => undefined }),
- )
- await act(async () => {
- renderer = rtlRender(tree(null))
- })
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
- const meta: ChildChannelMeta = {
- id: "thread-1",
- serverId: "server-1",
- name: "Thread",
- type: "thread",
- parentChannelId: "general-1",
- parentMessageId: "message-1",
- creatorId: "user-1",
- archived: false,
- activityAt: "2026-08-08T00:00:00.000Z",
- verifiedEpoch: 0,
- }
- queryClient.setQueryData(communityKeys.channelMeta("server-1", "thread-1"), meta)
-
- await act(async () => {
- renderer!.rerender(tree("thread-1"))
- })
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarRetained("server-1", "thread-1"),
- )?.status === "success")
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 25))
- })
+ it("preserves system opener types at the canonical ingress boundary", () => {
+ const response = envelope()
+ response.included.parentMessages[0]!.type = "system"
- expect(apiFetchMock).toHaveBeenCalledTimes(2)
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "thread-1"),
- )).toEqual(meta)
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarRetained("server-1", "thread-1"),
- )).toBeNull()
- renderer!.unmount()
+ expect(normalizeForumSidebarEnvelope(response, null, 0).openerHints["opener-1"])
+ .toEqual(expect.objectContaining({ type: "system" }))
})
- it("uses one cold combined request and seeds sibling resources before base settles", async () => {
- const canonical = envelope(["base-1"])
- const retained = envelope(["retained-1"])
- apiFetchMock.mockResolvedValue({
- ...canonical,
- canonicalChannels: canonical.channels,
- retainedChannel: retained.channels[0],
- included: {
- parentMessages: [
- ...canonical.included.parentMessages,
- ...retained.included.parentMessages,
- ],
- },
- })
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "retained-1", onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- expect(apiFetchMock).toHaveBeenCalledTimes(1)
- expect(apiFetchMock.mock.calls[0]?.[0]).toContain("retainId=retained-1")
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarRetained("server-1", "retained-1"),
- )).toMatchObject({ id: "retained-1" })
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "retained-1"),
- )).toMatchObject({ id: "retained-1" })
- expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "opener-retained-1"),
- )).toEqual({ id: "opener-retained-1", content: "title-retained-1" })
- renderer!.unmount()
- })
-
- it("does not restart the first request when enablement and the route candidate arrive together", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const tree = (retainId: string | null, enabled: boolean) => React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId,
- enabled,
- onRender: () => undefined,
- }),
- )
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(tree(null, false))
- })
- await act(async () => {
- renderer!.rerender(tree("retained-1", true))
- await new Promise((resolve) => setTimeout(resolve, 10))
- })
- expect(apiFetchMock).toHaveBeenCalledTimes(1)
- expect(apiFetchMock.mock.calls[0]?.[0]).toContain("retainId=retained-1")
-
- const canonical = envelope(["base-1"])
- const retained = envelope(["retained-1"])
- await act(async () => resolveRequest?.({
- ...canonical,
- canonicalChannels: canonical.channels,
- retainedChannel: retained.channels[0],
- included: {
- parentMessages: [
- ...canonical.included.parentMessages,
- ...retained.included.parentMessages,
- ],
- },
+ it("expires a canonical row 72h after its latest activity", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-09-26T00:00:00.000Z"))
+ const { queryClient, wrapper } = await setup()
+ publish(queryClient, envelopeFor(["post-1"]))
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
+ const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })
+ expect(rendered.result.current.threads.map(({ id }) => id)).toEqual(["post-1"])
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync((72 * 60 * 60 * 1000) + 50)
+ })
+ expect(rendered.result.current.threads).toEqual([])
+ rendered.unmount()
+ await invalidateForumSidebarBaseExact(queryClient, "server-1")
+ })
+
+ it("deduplicates one cold request across a StrictMode-style remount", async () => {
+ const { wrapper } = await setup()
+ let resolveRequest!: (value: SidebarThreadEnvelope) => void
+ apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveRequest = resolve }))
+ const first = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ first.unmount()
+ const second = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ await act(async () => resolveRequest({
+ ...envelopeFor([]),
+ canonicalChannels: [],
+ retainedChannel: envelopeFor(["post-1"]).channels[0],
+ retainedDisposition: "eligible",
+ included: envelopeFor(["post-1"]).included,
}))
- renderer!.unmount()
+ await waitFor(() => expect(second.result.current.threads[0]?.id).toBe("post-1"))
+ second.unmount()
})
- it("shares one cold request across an asynchronous StrictMode-style remount", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const renders: string[][] = []
- const tree = () => React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: "retained-1",
- onRender: (ids) => renders.push(ids),
- }),
- )
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(tree())
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 1)
- act(() => renderer!.unmount())
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 10))
- renderer = rtlRender(tree())
- })
- expect(apiFetchMock).toHaveBeenCalledTimes(1)
-
- const canonical = envelope(["base-1"])
- const retained = envelope(["retained-1"])
- await act(async () => resolveRequest?.({
- ...canonical,
- canonicalChannels: canonical.channels,
+ it("restarts a cold request when the retained route candidate changes", async () => {
+ const { wrapper } = await setup()
+ let resolveSecond!: (value: SidebarThreadEnvelope) => void
+ apiFetchMock
+ .mockReturnValueOnce(new Promise(() => {}))
+ .mockReturnValueOnce(new Promise((resolve) => { resolveSecond = resolve }))
+ let retainId: string | null = null
+ const rendered = renderHook(() => useForumSidebarThreads("server-1", retainId), { wrapper })
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
+ retainId = "post-b"
+ rendered.rerender()
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ const retained = envelopeFor(["post-b"])
+ await act(async () => resolveSecond({
+ ...envelopeFor([]),
+ canonicalChannels: [],
retainedChannel: retained.channels[0],
- included: {
- parentMessages: [
- ...canonical.included.parentMessages,
- ...retained.included.parentMessages,
- ],
- },
+ retainedDisposition: "eligible",
+ included: retained.included,
}))
- await waitFor(() => renders.at(-1)?.includes("retained-1") ?? false)
-
- expect(apiFetchMock).toHaveBeenCalledTimes(1)
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "retained-1"),
- )).toMatchObject({ id: "retained-1" })
- renderer!.unmount()
- })
-
- it("does not seed resources when an unmounted consumer loses the response race", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "retained-1", onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 1)
- const canonical = envelope(["base-1"])
- const retained = envelope(["retained-1"])
- await act(async () => {
- renderer!.unmount()
- resolveRequest?.({
- ...canonical,
- canonicalChannels: canonical.channels,
- retainedChannel: retained.channels[0],
- included: {
- parentMessages: [
- ...canonical.included.parentMessages,
- ...retained.included.parentMessages,
- ],
- },
- })
- await Promise.resolve()
- })
-
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarThreads("server-1"),
- )).toBeUndefined()
- expect(queryClient.getQueriesData({
- queryKey: communityKeys.channelMetaRoot("server-1"),
- })).toEqual([])
- expect(queryClient.getQueriesData({
- queryKey: communityKeys.forumOpenerHintRoot("server-1"),
- })).toEqual([])
+ await waitFor(() => expect(rendered.result.current.threads[0]?.id).toBe("post-b"))
+ expect(apiFetchMock.mock.calls[1]?.[0]).toContain("retainId=post-b")
+ rendered.unmount()
})
- it("does not relabel an old in-flight response with a newer access epoch", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const renders: string[][] = []
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 1)
-
- await act(async () => {
+ it("accepts an in-flight response across a transport-only reconnect", async () => {
+ const { wrapper } = await setup()
+ 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(() => {
useCommunityWsStore.getState().markAccessDisconnected()
useCommunityWsStore.getState().markAccessConnected()
- resolveRequest?.(envelope(["base-1"]))
})
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.verifiedEpoch).toBe(0)
- expect(useCommunityWsStore.getState().accessEpoch).toBe(1)
- expect(renders.at(-1)).toEqual([])
- renderer!.unmount()
+ await act(async () => resolveRequest(envelopeFor(["post-1"])))
+ await waitFor(() => expect(rendered.result.current.threads[0]?.id).toBe("post-1"))
+ rendered.unmount()
})
- it("keeps an already-rendered sidebar snapshot visible while WS is disconnected", async () => {
- apiFetchMock.mockResolvedValue(envelope(["base-1"]))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const renders: string[][] = []
- let renderer!: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, {
- retainId: null,
- onRender: (ids) => renders.push(ids),
- }),
- ),
- )
- })
- await waitFor(() => renders.at(-1)?.includes("base-1") === true)
-
- await act(async () => {
- useCommunityWsStore.getState().markAccessDisconnected()
- })
+ it("folds in-flight title, activity, and removal deltas into one canonical publish", async () => {
+ const { queryClient, wrapper } = await setup()
+ 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())
+ patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "live title")
+ patchForumSidebarActivityExact(
+ queryClient, "server-1", "post-1", "forum-1", "2026-09-26T10:00:00.000Z",
+ )
+ patchForumSidebarActivityExact(
+ queryClient, "server-1", "missing", "forum-1", "2026-09-26T10:00:00.000Z",
+ )
+ removeForumSidebarThreadExact(queryClient, "server-1", "post-2")
+ await act(async () => resolveRequest(envelopeFor(["post-1", "post-2"])))
+ await waitFor(() => expect(rendered.result.current.threads).toEqual([
+ expect.objectContaining({
+ id: "post-1",
+ title: "live title",
+ activityAt: "2026-09-26T10:00:00.000Z",
+ }),
+ ]))
+ expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-2"))
+ .toBe(false)
+ rendered.unmount()
+ })
- expect(renders.at(-1)).toEqual(["base-1"])
- renderer.unmount()
+ it("folds an in-flight activity delta into an eligible retained row", async () => {
+ const { queryClient, wrapper } = await setup()
+ let resolveRequest!: (value: SidebarThreadEnvelope) => void
+ apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveRequest = resolve }))
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", "post-1"),
+ { wrapper },
+ )
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ patchForumSidebarActivityExact(
+ queryClient, "server-1", "post-1", "forum-1", "2026-09-26T11:00:00.000Z",
+ )
+ removeForumSidebarThreadExact(queryClient, "server-1", "post-1")
+ restoreForumSidebarThreadInflight("server-1", "post-1")
+ const retained = envelopeFor(["post-1"])
+ await act(async () => resolveRequest({
+ ...envelopeFor([]),
+ canonicalChannels: [],
+ retainedChannel: retained.channels[0],
+ retainedDisposition: "eligible",
+ included: retained.included,
+ }))
+ await waitFor(() => expect(rendered.result.current.threads[0]?.activityAt)
+ .toBe("2026-09-26T11:00:00.000Z"))
+ rendered.unmount()
})
- it("replays a title patch that lands while the canonical request is in flight", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ),
- )
+ it("publishes a negative retained response without a matching projected thread", async () => {
+ const { wrapper } = await setup()
+ const retained = envelopeFor(["post-1"])
+ apiFetchMock.mockResolvedValue({
+ ...envelopeFor([]),
+ canonicalChannels: [],
+ retainedChannel: retained.channels[0],
+ retainedDisposition: "opener-archived",
+ included: retained.included,
})
- patchForumSidebarTitleExact(queryClient, "server-1", "base-1", "live title")
- await act(async () => resolveRequest?.(envelope(["base-1"])))
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads[0]?.title).toBe("live title")
- expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "opener-base-1"),
- )).toEqual({ id: "opener-base-1", content: "live title" })
- renderer!.unmount()
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", "post-1"),
+ { wrapper },
+ )
+ await waitFor(() => expect(rendered.result.current.isSuccess).toBe(true))
+ expect(rendered.result.current.threads).toEqual([])
+ rendered.unmount()
})
- it("replays in-flight activity into the exact metadata seed", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ),
- )
- })
- patchForumSidebarActivityExact(
- queryClient,
- "server-1",
- "base-1",
- "forum-1",
- "2026-08-09T00:00:00.000Z",
+ it("aborts an unobserved cold request after the StrictMode grace", async () => {
+ vi.useFakeTimers()
+ const { wrapper } = await setup()
+ let requestSignal: AbortSignal | undefined
+ apiFetchMock.mockImplementation((_url: string, init: RequestInit) => {
+ requestSignal = init.signal as AbortSignal
+ return new Promise(() => {})
+ })
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", "post-1"),
+ { wrapper },
)
- await act(async () => resolveRequest?.(envelope(["base-1"])))
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads[0]?.activityAt).toBe("2026-08-09T00:00:00.000Z")
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "base-1"),
- )).toMatchObject({ activityAt: "2026-08-09T00:00:00.000Z" })
- renderer!.unmount()
+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ rendered.unmount()
+ await act(async () => { await vi.advanceTimersByTimeAsync(51) })
+ expect(requestSignal?.aborted).toBe(true)
+ })
+
+ it("keeps invalid canonical activity literal and removes children by parent", async () => {
+ const { queryClient } = await setup()
+ publish(queryClient)
+ patchForumSidebarTitleExact(queryClient, "server-1", "post-1", "updated title")
+ expect(getCanonicalCommunityMessages(queryClient).find(({ id }) => id === "opener-1")?.content)
+ .toBe("updated title")
+ patchForumSidebarActivityExact(queryClient, "server-1", "post-1", "forum-1", "invalid")
+ expect(getForumSidebarBase(queryClient, "server-1").threads[0]?.expiresAt).toBe("invalid")
+ removeForumSidebarProjectionExact(queryClient, "server-1", "post-1")
+ removeForumSidebarChildrenForParent(queryClient, "server-1", "forum-1")
+ expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-1"))
+ .toBe(false)
})
- it("does not let a delayed response revive removed metadata or opener hints", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ it("renders providerless transport data and schedules its next expiry", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ),
- )
- })
- removeForumSidebarThreadExact(queryClient, "server-1", "base-1")
- await act(async () => resolveRequest?.(envelope(["base-1"])))
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads).toEqual([])
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "base-1"),
- )).toBeUndefined()
- expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "opener-base-1"),
- )).toBeUndefined()
- renderer!.unmount()
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ )
+ apiFetchMock.mockResolvedValue(envelopeFor(["post-1", "post-2"]))
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
+ )
+ await waitFor(() => expect(rendered.result.current.threads[0]?.id).toBe("post-1"))
+ expect(rendered.result.current.projectionReady).toBe(true)
+ rendered.unmount()
+ queryClient.clear()
})
- it("does not let a stale eligible retained response override an in-flight archive", async () => {
- let resolveStale: ((value: SidebarThreadEnvelope) => void) | undefined
+ it("does not let a stale retained response revive an archived row", async () => {
+ const { queryClient, wrapper } = await setup()
+ let resolveStale!: (value: SidebarThreadEnvelope) => void
apiFetchMock
- .mockImplementationOnce(() => new Promise((resolve) => { resolveStale = resolve }))
+ .mockReturnValueOnce(new Promise((resolve) => { resolveStale = resolve }))
.mockResolvedValueOnce({
- ...envelope([]),
+ ...envelopeFor([]),
canonicalChannels: [],
retainedChannel: null,
retainedDisposition: "opener-archived",
})
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "post-1", onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 1)
-
+ const rendered = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
await act(async () => {
await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", true)
})
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- const canonical = envelope(["post-2"])
- const retained = envelope(["post-1"])
- await act(async () => {
- resolveStale?.({
- ...canonical,
- canonicalChannels: canonical.channels,
- retainedChannel: retained.channels[0],
- retainedDisposition: "eligible",
- included: {
- parentMessages: [
- ...canonical.included.parentMessages,
- ...retained.included.parentMessages,
- ],
- },
- })
- await Promise.resolve()
- })
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads).toEqual([])
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarRetained("server-1", "post-1"),
- )).toBeNull()
- renderer!.unmount()
- })
-
- it("allows a failed optimistic removal to accept the restored server row", async () => {
- let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ),
- )
- })
- removeForumSidebarThreadExact(queryClient, "server-1", "base-1")
- restoreForumSidebarThreadInflight("server-1", "base-1")
- await act(async () => resolveRequest?.(envelope(["base-1"])))
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads.map((thread) => thread.id)).toEqual(["base-1"])
- renderer!.unmount()
- })
-
- it("restarts a cold request when the route candidate changes", async () => {
- let resolveFirst: ((value: SidebarThreadEnvelope) => void) | undefined
- let resolveSecond: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock
- .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve }))
- .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 1)
- await act(async () => {
- renderer!.rerender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "post-b", onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 2)
- const first = envelope(["base-a"])
- const secondBase = envelope(["base-a"])
- const secondRetained = envelope(["post-b"])
- await act(async () => resolveFirst?.(first))
- await act(async () => resolveSecond?.({
- ...secondBase,
- canonicalChannels: secondBase.channels,
- retainedChannel: secondRetained.channels[0],
- included: {
- parentMessages: [
- ...secondBase.included.parentMessages,
- ...secondRetained.included.parentMessages,
- ],
- },
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ const retained = envelopeFor(["post-1"])
+ await act(async () => resolveStale({
+ ...envelopeFor([]),
+ canonicalChannels: [],
+ retainedChannel: retained.channels[0],
+ retainedDisposition: "eligible",
+ included: retained.included,
}))
- await waitFor(() => queryClient.getQueryData<ForumSidebarThread | null>(
- communityKeys.forumSidebarRetained("server-1", "post-b"),
- )?.id === "post-b")
-
- expect(apiFetchMock.mock.calls[1]?.[0]).toContain("retainId=post-b")
- expect(queryClient.getQueryData<ForumSidebarThread | null>(
- communityKeys.forumSidebarRetained("server-1", "post-b"),
- )?.id).toBe("post-b")
- renderer!.unmount()
+ await act(async () => Promise.resolve())
+ expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-1"))
+ .toBe(false)
+ rendered.unmount()
})
- it("clears an exact negative retained result on a grant without touching siblings", async () => {
- const queryClient = new QueryClient()
- const negative = envelope([])
- apiFetchMock.mockResolvedValueOnce({
- ...negative,
+ it("does not revive a row when grant races archive and removal", async () => {
+ const { queryClient } = await setup()
+ let resolveGrant!: (value: SidebarThreadEnvelope) => void
+ apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveGrant = resolve }))
+ const grant = grantForumSidebarChild(queryClient, "server-1", "post-1")
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ removeForumSidebarThreadExact(queryClient, "server-1", "post-1")
+ await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", true)
+ const retained = envelopeFor(["post-1"])
+ resolveGrant({
+ ...envelopeFor([]),
canonicalChannels: [],
- retainedChannel: null,
- retainedDisposition: "genuine-negative",
- })
- queryClient.setQueryData(communityKeys.forumSidebarRetained("server-1", "post-1"), null)
- queryClient.setQueryData(
- communityKeys.forumSidebarRetained("server-1", "post-2"),
- { id: "post-2" },
- )
-
- await grantForumSidebarChild(queryClient, "server-1", "post-1")
-
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarRetained("server-1", "post-1"),
- )).toBeNull()
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarRetained("server-1", "post-2"),
- )).toEqual({ id: "post-2" })
- })
-
- it("archive-tag eviction preserves route resources and hidden unread ownership", async () => {
- const queryClient = new QueryClient()
- const source = envelope(["post-1", "post-2"])
- const normalized = normalizeForumSidebarEnvelope({
- ...source,
- canonicalChannels: source.channels,
- retainedChannel: source.channels[0],
+ retainedChannel: retained.channels[0],
retainedDisposition: "eligible",
- }, "post-1", 0)
- const baseKey = communityKeys.forumSidebarThreads("server-1")
- const retainedKey = communityKeys.forumSidebarRetained("server-1", "post-1")
- const metaKey = communityKeys.channelMeta("server-1", "post-1")
- const hintKey = communityKeys.forumOpenerHint("server-1", "opener-post-1")
- const fallbackKey = communityKeys.forumSidebarUnreadFallbacks("server-1")
- queryClient.setQueryData(baseKey, normalized.base)
- queryClient.setQueryData(retainedKey, normalized.retained)
- queryClient.setQueryData(metaKey, normalized.channelMetas["post-1"])
- queryClient.setQueryData(hintKey, normalized.openerHints["opener-post-1"])
- queryClient.setQueryData<ForumSidebarUnreadFallbackState>(fallbackKey, {
- "forum-1": { baseUnread: false, childIds: ["post-1"] },
- })
-
- await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", true)
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(baseKey)?.threads.map(({ id }) => id))
- .toEqual(["post-2"])
- expect(queryClient.getQueryState(retainedKey)).toBeUndefined()
- expect(queryClient.getQueryData(metaKey)).toEqual(normalized.channelMetas["post-1"])
- expect(queryClient.getQueryData(hintKey)).toEqual(normalized.openerHints["opener-post-1"])
- expect(queryClient.getQueryData(fallbackKey)).toEqual({
- "forum-1": { baseUnread: false, childIds: ["post-1"] },
+ included: retained.included,
})
- expect(queryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)
+ await grant
+ expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-1"))
+ .toBe(false)
})
- it("tag-only unarchive clears retained null and waits for authoritative ranking", async () => {
- const queryClient = new QueryClient()
- const source = envelope(["post-2"])
- const normalized = normalizeForumSidebarEnvelope({
- ...source,
- canonicalChannels: source.channels,
- retainedChannel: null,
- }, null, 0)
- const baseKey = communityKeys.forumSidebarThreads("server-1")
- const retainedKey = communityKeys.forumSidebarRetained("server-1", "post-1")
- const metaKey = communityKeys.channelMeta("server-1", "post-1")
- const hintKey = communityKeys.forumOpenerHint("server-1", "opener-post-1")
- queryClient.setQueryData(baseKey, normalized.base)
- queryClient.setQueryData(retainedKey, null)
- queryClient.setQueryData(metaKey, { id: "post-1", parentMessageId: "opener-post-1" })
- queryClient.setQueryData(hintKey, { id: "opener-post-1", content: "Post one" })
+ it("clears an in-flight removal delta when an unarchive wins", async () => {
+ const { queryClient } = await setup()
+ apiFetchMock.mockImplementation((_url: string, init: RequestInit) => new Promise(
+ (_resolve, reject) => init.signal?.addEventListener(
+ "abort",
+ () => reject(new DOMException("Aborted", "AbortError")),
+ { once: true },
+ ),
+ ))
+ const grant = grantForumSidebarChild(queryClient, "server-1", "post-1")
+ .catch(() => undefined)
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
await reconcileForumSidebarArchiveTag(queryClient, "server-1", "post-1", false)
-
- expect(queryClient.getQueryData<ForumSidebarQueryData>(baseKey)?.threads.map(({ id }) => id))
- .toEqual(["post-2"])
- expect(queryClient.getQueryState(retainedKey)).toBeUndefined()
- expect(queryClient.getQueryData(metaKey)).toEqual({
- id: "post-1",
- parentMessageId: "opener-post-1",
- })
- expect(queryClient.getQueryData(hintKey)).toEqual({
- id: "opener-post-1",
- content: "Post one",
- })
- expect(queryClient.getQueryState(baseKey)?.isInvalidated).toBe(true)
+ await grant
})
- it("preserves hidden unread ownership for an authoritative archived-opener negative", async () => {
- apiFetchMock.mockResolvedValue({
- ...envelope([]),
- canonicalChannels: [],
- retainedChannel: null,
- retainedDisposition: "opener-archived",
- })
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- queryClient.setQueryData(communityKeys.server("server-1"), {
- ...serverDetail(true),
- forumUnreadState: {
- "forum-1": { baseUnread: false, childIds: ["private-post"] },
- },
- })
- queryClient.setQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- { "forum-1": { baseUnread: false, childIds: ["private-post"] } },
- )
- queryClient.setQueryData(communityKeys.channelMeta("server-1", "private-post"), {
- id: "private-post",
+ it("treats a negative retained result as notify evidence, not access revocation", async () => {
+ const { queryClient, registry } = await setup()
+ publish(queryClient)
+ publishCommunityForumSidebar(queryClient, {
serverId: "server-1",
- name: "Private post",
- type: "thread",
- parentChannelId: "forum-1",
- parentMessageId: "private-opener",
- creatorId: "user-1",
- archived: false,
- activityAt: "2026-08-08T00:00:00.000Z",
- verifiedEpoch: 0,
- })
- queryClient.setQueryData(
- communityKeys.forumOpenerHint("server-1", "private-opener"),
- { id: "private-opener", content: "Private title" },
- )
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "private-post", onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarRetained("server-1", "private-post"),
- )?.status === "success")
-
- expect(queryClient.getQueryData<ServerDetail>(
- communityKeys.server("server-1"),
- )?.forumUnreadState?.["forum-1"]).toEqual({
- baseUnread: false,
- childIds: ["private-post"],
+ channels: [],
+ openers: [],
+ negativeRetain: { id: "post-1", disposition: "opener-archived" },
+ proof: {
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
})
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )).toEqual({ "forum-1": { baseUnread: false, childIds: ["private-post"] } })
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "private-post"),
- )).toMatchObject({ id: "private-post" })
- expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "private-opener"),
- )).toEqual({ id: "private-opener", content: "Private title" })
- renderer!.unmount()
+
+ expect(registry.collections.channels.get("post-1")).toMatchObject({ archived: false })
+ expect(registry.collections.channelMemberships.get("post-1:viewer:access"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("post-1:viewer:notify"))
+ .toBeUndefined()
})
- it("clears a negative retained projection without deleting exact route metadata", async () => {
+ it("clears hidden unread ownership when a canonical refetch removes participation", async () => {
+ const { queryClient, registry, wrapper } = await setup()
+ publish(queryClient)
apiFetchMock.mockResolvedValue({
- ...envelope([]),
+ ...envelopeFor([]),
canonicalChannels: [],
retainedChannel: null,
retainedDisposition: "genuine-negative",
})
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- queryClient.setQueryData(communityKeys.server("server-1"), {
- ...serverDetail(true),
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", "post-1"),
+ { wrapper },
+ )
+
+ await waitFor(() => expect(rendered.result.current).toMatchObject({
+ threads: [],
+ parentUnread: {},
+ }))
+ expect(registry.collections.channels.get("post-1")).toMatchObject({ unread: false })
+ expect(registry.collections.channelMemberships.get("post-1:viewer:access"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("post-1:viewer:notify"))
+ .toBeUndefined()
+ rendered.unmount()
+ })
+
+ it("keeps cold hidden-child unread ownership in canonical rows", async () => {
+ const { registry, wrapper } = await setup()
+ ingestServerDetail(registry, {
+ id: "server-1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer", categories: [{
+ id: "cat-1", name: "Forums", channels: [{
+ id: "forum-1", name: "forum", active: false, unread: false, type: "forum",
+ }],
+ }],
forumUnreadState: {
- "forum-1": { baseUnread: true, childIds: ["private-post"] },
+ "forum-1": { baseUnread: false, childIds: ["hidden-child"] },
},
})
- queryClient.setQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- { "forum-1": { baseUnread: true, childIds: ["private-post"] } },
- )
- queryClient.setQueryData(
- communityKeys.forumSidebarRetained("server-1", "private-post"),
- {
- ...projectForumSidebarThreads(envelope(["private-post"]))[0],
- parentMessageId: "private-opener",
- },
- )
- queryClient.setQueryData(
- communityKeys.channelMeta("server-1", "private-post"),
- {
- id: "private-post",
- serverId: "server-1",
- name: "Private post",
- type: "thread",
- parentChannelId: "forum-1",
- parentMessageId: "private-opener",
- creatorId: "user-1",
- archived: false,
- activityAt: "2026-08-08T00:00:00.000Z",
- verifiedEpoch: 0,
- },
- )
- queryClient.setQueryData(
- communityKeys.forumOpenerHint("server-1", "private-opener"),
- { id: "private-opener", content: "Private title" },
+ const rendered = renderHook(
+ () => useForumSidebarProjection("server-1", null, Date.now()),
+ { wrapper },
)
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "private-post", onRender: () => undefined }),
- ),
- )
+ await waitFor(() => expect(rendered.result.current).toEqual({
+ threads: [],
+ parentUnread: { "forum-1": true },
+ }))
+ expect(registry.collections.channels.get("hidden-child")).toMatchObject({
+ type: "thread", parentChannelId: "forum-1", parentMessageId: null, unread: true,
})
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.status === "success")
-
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarRetained("server-1", "private-post"),
- )).toBeNull()
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "private-post"),
- )).toMatchObject({ id: "private-post", parentChannelId: "forum-1" })
- expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "private-opener"),
- )).toEqual({ id: "private-opener", content: "Private title" })
- expect(queryClient.getQueryData<ServerDetail>(
- communityKeys.server("server-1"),
- )?.forumUnreadState?.["forum-1"]).toEqual({ baseUnread: true, childIds: [] })
- expect(parentUnread(queryClient)).toBe(true)
- expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
- communityKeys.forumSidebarUnreadFallbacks("server-1"),
- )).toEqual({})
- renderer!.unmount()
})
- it("settles an active negative retained query without restarting it", async () => {
- apiFetchMock.mockResolvedValue({
- ...envelope([]),
- canonicalChannels: [],
- retainedChannel: null,
- retainedDisposition: "genuine-negative",
- })
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const accessEpoch = useCommunityWsStore.getState().accessEpoch
- const base = normalizeForumSidebarEnvelope(envelope([]), null).base
- queryClient.setQueryData(
- communityKeys.forumSidebarThreads("server-1"),
- { ...base, verifiedEpoch: accessEpoch },
+ it("aggregates persisted unread child ownership even without notify membership", async () => {
+ const { queryClient, wrapper } = await setup()
+ publish(queryClient)
+ removeCanonicalCommunityChannelMembership(queryClient, "post-1", "notify")
+ const rendered = renderHook(
+ () => useForumSidebarProjection("server-1", null, Date.now()),
+ { wrapper },
)
- queryClient.setQueryData(
- communityKeys.channelMeta("server-1", "private-post"),
- {
- id: "private-post",
- serverId: "server-1",
- name: "Private post",
- type: "thread",
- parentChannelId: "forum-1",
- parentMessageId: "private-opener",
- creatorId: "user-1",
- archived: false,
- activityAt: "2026-08-08T00:00:00.000Z",
- verifiedEpoch: accessEpoch,
- },
- )
- queryClient.setQueryData(
- communityKeys.forumOpenerHint("server-1", "private-opener"),
- { id: "private-opener", content: "Private title" },
- )
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "private-post", onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => queryClient.getQueryState(
- communityKeys.forumSidebarRetained("server-1", "private-post"),
- )?.status === "success")
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 50))
- })
-
- expect(apiFetchMock).toHaveBeenCalledTimes(1)
- expect(queryClient.getQueryData(
- communityKeys.forumSidebarRetained("server-1", "private-post"),
- )).toBeNull()
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "private-post"),
- )).toMatchObject({ id: "private-post", parentChannelId: "forum-1" })
- expect(queryClient.getQueryData(
- communityKeys.forumOpenerHint("server-1", "private-opener"),
- )).toEqual({ id: "private-opener", content: "Private title" })
- renderer!.unmount()
- })
-
- it("force-restarts an in-flight request on grant instead of reusing its negative response", async () => {
- let resolveFirst: ((value: SidebarThreadEnvelope) => void) | undefined
- let resolveSecond: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock
- .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve }))
- .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: "post-granted", onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 1)
- act(() => { void grantForumSidebarChild(queryClient, "server-1", "post-granted") })
- await waitFor(() => apiFetchMock.mock.calls.length === 2)
-
- const granted = envelope(["post-granted"])
- await act(async () => resolveSecond?.({
- ...granted,
- canonicalChannels: granted.channels,
- retainedChannel: granted.channels[0],
- }))
- await waitFor(() => queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads[0]?.id === "post-granted")
- await act(async () => resolveFirst?.({
- ...envelope([]),
- canonicalChannels: [],
- retainedChannel: null,
+ await waitFor(() => expect(rendered.result.current).toEqual({
+ threads: [],
+ parentUnread: { "forum-1": true },
}))
-
- expect(apiFetchMock).toHaveBeenCalledTimes(2)
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads.map((thread) => thread.id)).toEqual(["post-granted"])
- expect(queryClient.getQueryData(
- communityKeys.channelMeta("server-1", "post-granted"),
- )).toMatchObject({ id: "post-granted", verifiedEpoch: 0 })
- renderer!.unmount()
})
- it("force-restarts an old-epoch request before reconnect validation", async () => {
- let resolveFirst: ((value: SidebarThreadEnvelope) => void) | undefined
- let resolveSecond: ((value: SidebarThreadEnvelope) => void) | undefined
- apiFetchMock
- .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve }))
- .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve }))
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- let renderer: ReturnType<typeof rtlRender>
- await act(async () => {
- renderer = rtlRender(
- React.createElement(
- QueryClientProvider,
- { client: queryClient },
- React.createElement(Capture, { retainId: null, onRender: () => undefined }),
- ),
- )
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 1)
- let reconnectWork!: Promise<void>
- await act(async () => {
- useCommunityWsStore.getState().markAccessDisconnected()
- useCommunityWsStore.getState().markAccessConnected()
- reconnectWork = invalidateForumSidebarBaseExact(queryClient, "server-1")
- })
- await waitFor(() => apiFetchMock.mock.calls.length === 2)
- expect(queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.fetchStatus).toBe("fetching")
-
- await act(async () => resolveSecond?.(envelope(["epoch-1"])))
- await reconnectWork
- await waitFor(() => queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )?.threads[0]?.id === "epoch-1")
- await act(async () => resolveFirst?.(envelope(["epoch-0"])))
-
- expect(apiFetchMock).toHaveBeenCalledTimes(2)
- expect(queryClient.getQueryState(
- communityKeys.forumSidebarThreads("server-1"),
- )?.fetchStatus).toBe("idle")
- expect(queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads("server-1"),
- )).toMatchObject({
- verifiedEpoch: 1,
- threads: [expect.objectContaining({ id: "epoch-1" })],
- })
- expect(queryClient.getQueryState(
- communityKeys.channelMeta("server-1", "epoch-0"),
- )).toBeUndefined()
- renderer!.unmount()
- })
-
- it("normalizes one canonical base plus one exact retained resource", () => {
- const source = {
- ...envelope(["base-1", "base-2"]),
- canonicalChannels: envelope(["base-1", "base-2"]).channels,
- retainedChannel: envelope(["retained-1"]).channels[0],
- included: {
- parentMessages: [
- { id: "opener-base-1", content: "Base 1" },
- { id: "opener-base-2", content: "Base 2" },
- { id: "opener-retained-1", content: "Retained 1" },
- ],
- },
- }
-
- const normalized = normalizeForumSidebarEnvelope(source, "retained-1", 0)
-
- expect(normalized.base.threads.map((thread) => thread.id)).toEqual(["base-1", "base-2"])
- expect(normalized.retained?.id).toBe("retained-1")
- expect(normalized.channelMetas["retained-1"]).toMatchObject({
- id: "retained-1",
- parentMessageId: "opener-retained-1",
- })
- expect(normalized.openerHints["opener-retained-1"]).toEqual({
- id: "opener-retained-1",
- content: "Retained 1",
+ it("uses exact scope attention beyond the bounded item window for thread dots", async () => {
+ const { queryClient, registry, wrapper } = await setup()
+ publish(queryClient)
+ ingestAttentionSnapshot(registry, {
+ scopes: [{
+ scopeId: "post-1",
+ channelId: "post-1",
+ serverId: "server-1",
+ parentChannelId: "forum-1",
+ ordinaryUnread: false,
+ lastUnreadSeq: 101,
+ lastAttentionSeq: 101,
+ attentionCount: 101,
+ }],
+ items: [],
+ limit: 100,
+ truncated: true,
})
- expect(normalized.openerHints["opener-retained-1"]).not.toHaveProperty("authorId")
- expect(JSON.stringify(normalized.base)).not.toContain("retained-1")
- expect(JSON.stringify(normalized.base)).not.toContain("Retained 1")
- })
- it("removes a child and opener from every exact resource without raw base residue", () => {
- const source = envelope(["base-1"])
- const normalized = normalizeForumSidebarEnvelope({
- ...source,
- canonicalChannels: source.channels,
- retainedChannel: null,
- }, null, 0)
- const queryClient = new QueryClient()
- queryClient.setQueryData(communityKeys.forumSidebarThreads("server-1"), normalized.base)
- queryClient.setQueryData(
- communityKeys.forumSidebarRetained("server-1", "base-1"),
- normalized.base.threads[0],
- )
- queryClient.setQueryData(
- communityKeys.channelMeta("server-1", "base-1"),
- normalized.channelMetas["base-1"],
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
)
- queryClient.setQueryData(
- communityKeys.forumOpenerHint("server-1", "opener-base-1"),
- normalized.openerHints["opener-base-1"],
- )
-
- removeForumSidebarThreadExact(queryClient, "server-1", "base-1")
-
- expect(JSON.stringify(queryClient.getQueryData(
- communityKeys.forumSidebarThreads("server-1"),
- ))).not.toContain("base-1")
- expect(queryClient.getQueryState(
- communityKeys.forumSidebarRetained("server-1", "base-1"),
- )).toBeUndefined()
- expect(queryClient.getQueryState(
- communityKeys.channelMeta("server-1", "base-1"),
- )).toBeUndefined()
- expect(queryClient.getQueryState(
- communityKeys.forumOpenerHint("server-1", "opener-base-1"),
- )).toBeUndefined()
- })
-
- it("keeps a positive retained resource but does not duplicate a canonical child", () => {
- const source = {
- ...envelope(["base-1"]),
- canonicalChannels: envelope(["base-1"]).channels,
- retainedChannel: envelope(["base-1"]).channels[0],
- }
-
- const normalized = normalizeForumSidebarEnvelope(source, "base-1", 0)
- expect(normalized.retained?.id).toBe("base-1")
- expect(deriveForumSidebarProjection(
- normalized.base,
- normalized.retained,
- {},
- Date.parse("2026-08-08T00:00:00.000Z"),
- ).threads.map((thread) => thread.id)).toEqual(["base-1"])
- })
- it("derives child and parent unread from one ownership snapshot", () => {
- const source = envelope(["base-1", "base-2"])
- const normalized = normalizeForumSidebarEnvelope({
- ...source,
- canonicalChannels: source.channels,
- retainedChannel: envelope(["retained-1"]).channels[0],
- }, "retained-1", 0)
- const ownership = {
- "forum-1": {
- baseUnread: false,
- childIds: ["base-2", "retained-1"],
- },
- }
-
- const active = deriveForumSidebarProjection(
- normalized.base,
- normalized.retained,
- ownership,
- Date.parse("2026-08-08T01:00:00.000Z"),
- 2,
+ await waitFor(() => expect(rendered.result.current).toMatchObject({
+ threads: [expect.objectContaining({ id: "post-1", unread: true })],
+ parentUnread: { "forum-1": true },
+ }))
+ expect(registry.collections.attentionItems.size).toBe(0)
+ rendered.unmount()
+ })
+
+ it("restores a warm persisted sidebar while HTTP is stalled", async () => {
+ await clearPersistedCache("viewer")
+ const { queryClient } = await setup()
+ publish(queryClient)
+ const persister = createIdbPersister("viewer")
+ await persister.persistClient({
+ timestamp: Date.now(),
+ buster: PERSIST_BUSTER,
+ clientState: dehydrate(queryClient),
+ })
+ const restored = await persister.restoreClient()
+ expect(restored).toBeDefined()
+ const restoredClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ hydrate(restoredClient, restored!.clientState)
+ const restoredRegistry = createCommunityDbRegistry(restoredClient, "viewer")
+ restoredRegistry.captureRestoredCollections()
+ await restoredRegistry.preload()
+ const unregister = registerCommunityDbRegistry(restoredRegistry)
+ cleanups.push(
+ unregister,
+ restoredRegistry.cleanup.bind(restoredRegistry),
+ () => clearPersistedCache("viewer"),
)
- expect(active.threads.map((thread) => [thread.id, thread.unread])).toEqual([
- ["retained-1", true],
- ["base-1", false],
- ])
- expect(active.parentUnread["forum-1"]).toBe(true)
-
- const inactive = deriveForumSidebarProjection(
- normalized.base,
- null,
- ownership,
- Date.parse("2026-08-08T01:00:00.000Z"),
- 2,
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: restoredClient },
+ createElement(CommunityDbProvider, { registry: restoredRegistry }, children),
)
- expect(inactive.threads.map((thread) => [thread.id, thread.unread])).toEqual([
- ["base-1", false],
- ["base-2", true],
- ])
- expect(inactive.parentUnread["forum-1"]).toBe(true)
- })
-
- it("prunes expired base rows before a refresh can succeed", () => {
- const source = envelope(["expired", "fresh"])
- source.channels[0]!.expiresAt = "2026-08-08T00:30:00.000Z"
- source.channels[1]!.expiresAt = "2026-08-08T02:00:00.000Z"
- const normalized = normalizeForumSidebarEnvelope({
- ...source,
- canonicalChannels: source.channels,
- retainedChannel: null,
- }, null, 0)
-
- const projection = deriveForumSidebarProjection(
- normalized.base,
- null,
- {},
- Date.parse("2026-08-08T01:00:00.000Z"),
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
+ const rendered = renderHook(
+ () => useForumSidebarThreads("server-1", null),
+ { wrapper },
)
- expect(projection.threads.map((thread) => thread.id)).toEqual(["fresh"])
+ await waitFor(() => expect(rendered.result.current.threads[0]?.id).toBe("post-1"))
+ expect(rendered.result.current.fetchStatus).toBe("fetching")
+ rendered.unmount()
+ await invalidateForumSidebarBaseExact(restoredClient, "server-1")
})
})
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 a114112e2..01672a698 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -2,17 +2,30 @@
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"
import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
+import { compareAsciiSqliteBinary } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
-import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
-import type { ServerDetail } from "@/hooks/community/use-servers"
import { useCommunityWsStore } from "@/stores/community/ws"
-import { getActiveAccountUnreadProjection } from "./account-unread-projection"
-import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
import {
- reservedUnreadExclusion,
- selectUnreadPresentation,
-} from "./unread-presentation"
+ useAttentionScopes,
+ useForumSidebarProjection,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import {
+ captureCommunityLiveSnapshotToken,
+ getCanonicalCommunityChannelMemberships,
+ getCanonicalCommunityChannels,
+ getCanonicalCommunityMessages,
+ patchCanonicalCommunityChannel,
+ patchCanonicalCommunityMessage,
+ publishCommunityForumSidebar,
+ removeCanonicalCommunityChannelMembership,
+ removeCanonicalCommunityChannel,
+ setCanonicalCommunityChannelMembership,
+ type CommunityFreshQueryProof,
+} from "@/lib/community-db/sync"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
export type ForumSidebarThread = {
id: string
@@ -24,6 +37,9 @@ export type ForumSidebarThread = {
unread: boolean
}
+const subscribeToNoRestoredForumProjection = () => () => {}
+const noRestoredForumProjection = () => false
+
type ForumSidebarRetainedDisposition =
| "eligible"
| "opener-archived"
@@ -49,12 +65,19 @@ export type SidebarThreadEnvelope = {
retainedChannel?: SidebarThreadEnvelope["channels"][number] | null
retainedDisposition?: ForumSidebarRetainedDisposition | null
included: {
- parentMessages: Array<{ id: string; content: string; seq?: number; channelId?: string }>
+ parentMessages: Array<{
+ id: string
+ content: string
+ seq?: number
+ channelId?: string
+ type?: string
+ }>
}
serverNow: string
}
export type ForumSidebarQueryData = {
+ /** Empty with a DB registry; only the explicit providerless test boundary uses rows. */
threads: ForumSidebarThread[]
verifiedEpoch: number
serverNow: string
@@ -79,6 +102,7 @@ export type ForumOpenerHint = {
content: string
seq?: number
channelId?: string
+ type?: "chat" | "system"
}
export type NormalizedForumSidebarEnvelope = {
@@ -89,285 +113,96 @@ export type NormalizedForumSidebarEnvelope = {
openerHints: Record<string, ForumOpenerHint>
}
-export function resolveForumSidebarRouteCandidate(
- channelId: string | null,
- topLevelChannelIds: Iterable<string> | null,
- parentIsForum: boolean | null | undefined,
-) {
- if (!channelId || !topLevelChannelIds || !parentIsForum) return null
- return new Set(topLevelChannelIds).has(channelId) ? null : channelId
-}
+/** Source-compatible shape only; no unread fallback cache is stored. */
+export type ForumSidebarUnreadFallbackState = Record<string, {
+ baseUnread: boolean
+ childIds: string[]
+}>
type InflightDelta = {
activity: Map<string, { parentChannelId: string; activityAt: string }>
titles: Map<string, string>
removed: Set<string>
- archiveRemovals: Map<string, number>
}
type InflightRecord = {
promise: Promise<NormalizedForumSidebarEnvelope>
delta: InflightDelta
candidate: string | null
- generation: number
controller: AbortController
signals: Set<AbortSignal>
abortTimer: ReturnType<typeof setTimeout> | null
}
-const inflight = new Map<string, InflightRecord>()
-let nextInflightGeneration = 0
-
-function recordInflightDelta(
- serverId: string,
- update: (delta: InflightDelta) => void,
-) {
- const record = inflight.get(serverId)
- if (record) update(record.delta)
-}
-
-export type ForumSidebarUnreadFallbackState = Record<string, {
- baseUnread: boolean
- childIds: string[]
-}>
-
const SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000
const STRICT_MODE_ABORT_GRACE_MS = 50
+const inflight = new Map<string, InflightRecord>()
-function parentUnread(cache: ServerDetail | undefined, parentChannelId: string): boolean {
- return !!cache?.categories.some((category) =>
- category.channels.some((channel) => channel.id === parentChannelId && channel.unread),
- )
-}
-
-/** Record canonical child unread ownership and project it to the loaded row or parent fallback. */
-export function recordForumSidebarChildUnread(
- queryClient: QueryClient,
- serverId: string,
- parentChannelId: string,
- childChannelId: string,
- loaded = false,
-) {
- const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
- const serverKey = communityKeys.server(serverId)
- const cachedServer = queryClient.getQueryData<ServerDetail>(serverKey)
- const canonicalBaseUnread = cachedServer?.forumUnreadState?.[parentChannelId]?.baseUnread
- ?? parentUnread(cachedServer, parentChannelId)
- queryClient.setQueryData<ServerDetail | undefined>(serverKey, (cache) => {
- if (!cache) return cache
- const current = cache.forumUnreadState?.[parentChannelId]
- const baseUnread = current?.baseUnread ?? canonicalBaseUnread
- const childIds = current?.childIds.includes(childChannelId)
- ? current.childIds
- : [...(current?.childIds ?? []), childChannelId]
- const next = {
- ...cache,
- forumUnreadState: {
- ...cache.forumUnreadState,
- [parentChannelId]: { baseUnread, childIds },
- },
- }
- const hidden = (queryClient.getQueryData<ForumSidebarUnreadFallbackState>(key)
- ?.[parentChannelId]?.childIds ?? [])
- .filter((id) => !loaded || id !== childChannelId)
- return patchChannelUnread(
- next,
- parentChannelId,
- baseUnread || !loaded || hidden.length > 0,
- )
- })
- queryClient.setQueryData<ForumSidebarUnreadFallbackState>(key, (state = {}) => {
- const current = state[parentChannelId]
- const baseUnread = current?.baseUnread ?? canonicalBaseUnread
- const childIds = loaded
- ? (current?.childIds ?? []).filter((id) => id !== childChannelId)
- : current?.childIds.includes(childChannelId)
- ? current.childIds
- : [...(current?.childIds ?? []), childChannelId]
- if (childIds.length === 0) {
- if (!current) return state
- const next = { ...state }
- delete next[parentChannelId]
- return next
- }
- return {
- ...state,
- [parentChannelId]: { baseUnread, childIds },
- }
- })
-}
-
-/** Update the genuine parent contribution while preserving missing children. */
-export function setForumSidebarParentUnreadBase(
- queryClient: QueryClient,
- serverId: string,
- parentChannelId: string,
- unread: boolean,
-): boolean {
- const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
- const state = queryClient.getQueryData<ForumSidebarUnreadFallbackState>(key)
- const current = state?.[parentChannelId]
- let handled = false
- queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(serverId), (cache) => {
- if (!cache?.forumUnreadState?.[parentChannelId]) return cache
- handled = true
- const entry = cache.forumUnreadState[parentChannelId]!
- return patchChannelUnread({
- ...cache,
- forumUnreadState: {
- ...cache.forumUnreadState,
- [parentChannelId]: { ...entry, baseUnread: unread },
- },
- }, parentChannelId, unread || (current?.childIds.length ?? 0) > 0)
- })
- if (current) {
- queryClient.setQueryData<ForumSidebarUnreadFallbackState>(key, {
- ...state,
- [parentChannelId]: { ...current, baseUnread: unread },
- })
- handled = true
- }
- return handled
-}
-
-/**
- * Re-project fallback ownership from the canonical unread child set. Loaded
- * children own their own dots; only unread children omitted by the sidebar's
- * 72h / top-five projection light the parent. Re-deriving (rather than merely
- * removing loaded ids) is what preserves visible → hidden transitions.
- */
-export function reconcileForumSidebarUnreadFallbacks(
- queryClient: QueryClient,
- serverId: string,
- loadedChildIds: Iterable<string>,
+export function resolveForumSidebarRouteCandidate(
+ channelId: string | null,
+ topLevelChannelIds: Iterable<string> | null,
+ parentIsForum: boolean | null | undefined,
) {
- const loaded = new Set(loadedChildIds)
- const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
- let fallbackState: ForumSidebarUnreadFallbackState = {}
- queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(serverId), (cache) => {
- if (!cache?.forumUnreadState) return cache
- let next: ServerDetail | undefined = cache
- for (const [parentChannelId, entry] of Object.entries(cache.forumUnreadState)) {
- const childIds = entry.childIds.filter((id) => !loaded.has(id))
- if (childIds.length > 0) {
- fallbackState = {
- ...fallbackState,
- [parentChannelId]: { baseUnread: entry.baseUnread, childIds },
- }
- }
- next = patchChannelUnread(
- next,
- parentChannelId,
- entry.baseUnread || childIds.length > 0,
- )
- }
- return next
- })
- queryClient.setQueryData(key, fallbackState)
+ if (!channelId || !topLevelChannelIds || !parentIsForum) return null
+ return new Set(topLevelChannelIds).has(channelId) ? null : channelId
}
-/** Remove a child's canonical unread ownership after read/leave/delete/archive. */
-export function removeForumSidebarUnreadChild(
- queryClient: QueryClient,
- serverId: string,
- childChannelId: string,
+export function hasForumSidebarThread(
+ data: ForumSidebarQueryData | undefined,
+ threadId: string,
) {
- const key = communityKeys.forumSidebarUnreadFallbacks(serverId)
- queryClient.setQueryData<ForumSidebarUnreadFallbackState>(key, (state = {}) => {
- let next = state
- for (const [parentChannelId, entry] of Object.entries(state)) {
- if (!entry.childIds.includes(childChannelId)) continue
- const childIds = entry.childIds.filter((id) => id !== childChannelId)
- next = { ...state }
- if (childIds.length === 0) delete next[parentChannelId]
- else next[parentChannelId] = { ...entry, childIds }
- break
- }
- return next
- })
- queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(serverId), (cache) => {
- if (!cache?.forumUnreadState) return cache
- const found = Object.entries(cache.forumUnreadState)
- .find(([, entry]) => entry.childIds.includes(childChannelId))
- if (!found) return cache
- const [parentChannelId, entry] = found
- const childIds = entry.childIds.filter((id) => id !== childChannelId)
- const next = {
- ...cache,
- forumUnreadState: {
- ...cache.forumUnreadState,
- [parentChannelId]: { ...entry, childIds },
- },
- }
- const hiddenChildIds = queryClient
- .getQueryData<ForumSidebarUnreadFallbackState>(key)
- ?.[parentChannelId]?.childIds ?? []
- const unread = entry.baseUnread || hiddenChildIds.length > 0
- return patchChannelUnread(next, parentChannelId, unread)
- })
+ return !!data?.threads.some((thread) => thread.id === threadId)
}
-export function hasForumSidebarThread(data: ForumSidebarQueryData | undefined, threadId: string) {
- return !!data?.threads.some((thread) => thread.id === threadId)
+function compareThreads(left: ForumSidebarThread, right: ForumSidebarThread) {
+ return compareAsciiSqliteBinary(left.parentChannelId, right.parentChannelId)
+ || compareAsciiSqliteBinary(right.activityAt, left.activityAt)
+ || compareAsciiSqliteBinary(right.id, left.id)
}
-export function patchForumSidebarActivity(
- data: ForumSidebarQueryData | undefined,
+function patchForumSidebarActivity(
+ data: ForumSidebarQueryData,
threadId: string,
parentChannelId: string,
activityAt: string,
-): ForumSidebarQueryData | undefined {
- if (!data || !hasForumSidebarThread(data, threadId)) return data
+): ForumSidebarQueryData {
+ if (!data.threads.some((thread) => (
+ thread.id === threadId && thread.parentChannelId === parentChannelId
+ ))) return data
const expiresAt = new Date(Date.parse(activityAt) + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()
- const threads = data.threads
- .map((thread) => thread.id === threadId ? { ...thread, activityAt, expiresAt } : thread)
- .sort((a, b) => {
- if (a.parentChannelId !== b.parentChannelId) return a.parentChannelId < b.parentChannelId ? -1 : 1
- if (a.activityAt !== b.activityAt) return a.activityAt > b.activityAt ? -1 : 1
- return a.id === b.id ? 0 : a.id > b.id ? -1 : 1
- })
- // Ignore metadata from a malformed/mismatched event rather than moving the
- // loaded row under a different forum. The event's parent id is still checked
- // by callers before deciding whether a missing row requires a refetch.
- if (!threads.some((thread) => thread.id === threadId && thread.parentChannelId === parentChannelId)) return data
- return { ...data, threads }
-}
-
-function patchForumSidebarTitle(
- data: ForumSidebarQueryData | undefined,
- threadId: string,
- title: string,
-): ForumSidebarQueryData | undefined {
- if (!data) return data
return {
...data,
- threads: data.threads.map((thread) => thread.id === threadId ? { ...thread, title } : thread),
+ threads: data.threads
+ .map((thread) => thread.id === threadId
+ ? { ...thread, activityAt, expiresAt }
+ : thread)
+ .sort(compareThreads),
}
}
-export function patchForumSidebarUnread(
- data: ForumSidebarQueryData | undefined,
+function patchForumSidebarTitle(
+ data: ForumSidebarQueryData,
threadId: string,
- unread: boolean,
-): ForumSidebarQueryData | undefined {
- if (!data || !hasForumSidebarThread(data, threadId)) return data
+ title: string,
+) {
return {
...data,
- threads: data.threads.map((thread) => thread.id === threadId ? { ...thread, unread } : thread),
+ threads: data.threads.map((thread) => (
+ thread.id === threadId ? { ...thread, title } : thread
+ )),
}
}
-export function removeForumSidebarThread(
- data: ForumSidebarQueryData | undefined,
+function removeForumSidebarThread(
+ data: ForumSidebarQueryData,
threadId: string,
-): ForumSidebarQueryData | undefined {
- if (!data) return data
+) {
return { ...data, threads: data.threads.filter((thread) => thread.id !== threadId) }
}
-export function projectForumSidebarThreads(data: SidebarThreadEnvelope): ForumSidebarThread[] {
+function projectForumSidebarThreads(data: SidebarThreadEnvelope) {
const openerById = new Map(data.included.parentMessages.map((message) => [message.id, message]))
- return data.channels.flatMap((channel) => {
+ return data.channels.flatMap((channel): ForumSidebarThread[] => {
if (!channel.parentChannelId || !channel.parentMessageId) return []
return [{
id: channel.id,
@@ -381,24 +216,12 @@ export function projectForumSidebarThreads(data: SidebarThreadEnvelope): ForumSi
})
}
-function projectChannels(
- channels: SidebarThreadEnvelope["channels"],
- parentMessages: SidebarThreadEnvelope["included"]["parentMessages"],
-): ForumSidebarThread[] {
- return projectForumSidebarThreads({
- channels,
- included: { parentMessages },
- serverNow: "",
- })
-}
-
function childMeta(
channel: SidebarThreadEnvelope["channels"][number],
): ChildChannelMeta | null {
- if (
- !channel.serverId || !channel.type || !channel.parentChannelId ||
- !channel.parentMessageId
- ) return null
+ if (!channel.serverId || !channel.type || !channel.parentChannelId || !channel.parentMessageId) {
+ return null
+ }
return {
id: channel.id,
serverId: channel.serverId,
@@ -419,20 +242,20 @@ export function normalizeForumSidebarEnvelope(
serverClockOffsetOverride?: number,
): NormalizedForumSidebarEnvelope {
const canonicalChannels = envelope.canonicalChannels ?? envelope.channels
- const threads = projectChannels(canonicalChannels, envelope.included.parentMessages)
- const serverNowMs = Date.parse(envelope.serverNow)
const base: ForumSidebarQueryData = {
- threads,
+ threads: projectForumSidebarThreads({ ...envelope, channels: canonicalChannels }),
serverNow: envelope.serverNow,
verifiedEpoch: -1,
- serverClockOffsetMs: serverClockOffsetOverride ??
- (Number.isFinite(serverNowMs) ? serverNowMs - Date.now() : 0),
+ serverClockOffsetMs: serverClockOffsetOverride ?? (() => {
+ const serverNowMs = Date.parse(envelope.serverNow)
+ return Number.isFinite(serverNowMs) ? serverNowMs - Date.now() : 0
+ })(),
}
const retainedChannel = retainId && envelope.retainedChannel?.id === retainId
? envelope.retainedChannel
: null
const retained = retainedChannel
- ? projectChannels([retainedChannel], envelope.included.parentMessages)[0] ?? null
+ ? projectForumSidebarThreads({ ...envelope, channels: [retainedChannel] })[0] ?? null
: null
const retainedDisposition = retainId
? envelope.retainedDisposition ?? (retained ? "eligible" : "genuine-negative")
@@ -445,10 +268,10 @@ export function normalizeForumSidebarEnvelope(
if (meta) channelMetas[meta.id] = meta
}
const openerHints = Object.fromEntries(
- envelope.included.parentMessages.map(({ id, content, seq, channelId }) => [
- id,
- { id, content, ...(seq === undefined ? {} : { seq }), ...(channelId ? { channelId } : {}) },
- ]),
+ envelope.included.parentMessages.map((message) => [message.id, {
+ ...message,
+ type: message.type === "system" ? "system" : "chat",
+ } satisfies ForumOpenerHint]),
)
return { base, retained, retainedDisposition, channelMetas, openerHints }
}
@@ -456,52 +279,255 @@ export function normalizeForumSidebarEnvelope(
export function deriveForumSidebarProjection(
base: ForumSidebarQueryData | undefined,
activeExtra: ForumSidebarThread | null | undefined,
- ownership: ServerDetail["forumUnreadState"] | undefined,
+ ownership: ForumSidebarUnreadFallbackState | undefined,
nowMs = Date.now(),
limitPerParent = 5,
) {
- if (!base) return { threads: [] as ForumSidebarThread[], parentUnread: {} as Record<string, boolean> }
+ if (!base) {
+ return { threads: [] as ForumSidebarThread[], parentUnread: {} as Record<string, boolean> }
+ }
const serverNowMs = nowMs + base.serverClockOffsetMs
let threads = base.threads.filter((thread) => {
- const expiresAt = Date.parse(thread.expiresAt)
- return !Number.isFinite(expiresAt) || expiresAt > serverNowMs
+ const expiry = Date.parse(thread.expiresAt)
+ return !Number.isFinite(expiry) || expiry > serverNowMs
})
if (activeExtra && !threads.some((thread) => thread.id === activeExtra.id)) {
- const siblings = threads.filter((thread) => thread.parentChannelId === activeExtra.parentChannelId)
- const otherParents = threads.filter((thread) => thread.parentChannelId !== activeExtra.parentChannelId)
- threads = [...otherParents, ...siblings.slice(0, Math.max(0, limitPerParent - 1)), activeExtra]
- .sort((a, b) => {
- if (a.parentChannelId !== b.parentChannelId) return a.parentChannelId < b.parentChannelId ? -1 : 1
- if (a.activityAt !== b.activityAt) return a.activityAt > b.activityAt ? -1 : 1
- return a.id === b.id ? 0 : a.id > b.id ? -1 : 1
- })
+ threads = [
+ ...threads.filter((thread) => thread.parentChannelId !== activeExtra.parentChannelId),
+ ...threads
+ .filter((thread) => thread.parentChannelId === activeExtra.parentChannelId)
+ .slice(0, Math.max(0, limitPerParent - 1)),
+ activeExtra,
+ ].sort(compareThreads)
}
- const renderedIds = new Set(threads.map((thread) => thread.id))
+ const rendered = new Set(threads.map((thread) => thread.id))
threads = threads.map((thread) => ({
...thread,
- unread: ownership?.[thread.parentChannelId]?.childIds.includes(thread.id) ?? thread.unread,
+ unread: ownership?.[thread.parentChannelId]?.childIds.includes(thread.id)
+ ?? thread.unread,
}))
const parentUnread: Record<string, boolean> = {}
for (const [parentId, state] of Object.entries(ownership ?? {})) {
- parentUnread[parentId] = state.baseUnread || state.childIds.some((id) => !renderedIds.has(id))
+ parentUnread[parentId] = state.baseUnread
+ || state.childIds.some((childId) => !rendered.has(childId))
}
return { threads, parentUnread }
}
-export function getForumSidebarBase(queryClient: QueryClient, serverId: string) {
- return queryClient.getQueryData<ForumSidebarQueryData>(
- communityKeys.forumSidebarThreads(serverId),
- )
+function sidebarUrl(serverId: string, retainId: string | null) {
+ const params = new URLSearchParams({
+ type: "thread",
+ parentType: "forum",
+ participating: "true",
+ activeWithin: "72h",
+ limitPerParent: "5",
+ include: "parentMessage",
+ })
+ if (retainId) params.set("retainId", retainId)
+ return `/api/community/servers/${serverId}/channels?${params.toString()}`
+}
+
+function attachInflightSignal(
+ serverId: string,
+ record: InflightRecord,
+ signal?: AbortSignal,
+) {
+ if (!signal || record.signals.has(signal)) return
+ if (record.abortTimer !== null) globalThis.clearTimeout(record.abortTimer)
+ record.abortTimer = null
+ record.signals.add(signal)
+ const release = () => {
+ record.signals.delete(signal)
+ if (record.signals.size > 0 || record.abortTimer !== null) return
+ record.abortTimer = globalThis.setTimeout(() => {
+ record.abortTimer = null
+ if (inflight.get(serverId) === record && record.signals.size === 0) {
+ record.controller.abort()
+ }
+ }, STRICT_MODE_ABORT_GRACE_MS)
+ }
+ if (signal.aborted) release()
+ else signal.addEventListener("abort", release, { once: true })
+}
+
+function fetchForumSidebar(
+ serverId: string,
+ retainId: string | null,
+ signal?: AbortSignal,
+) {
+ const pending = inflight.get(serverId)
+ if (pending?.candidate === retainId && !pending.controller.signal.aborted) {
+ attachInflightSignal(serverId, pending, signal)
+ return pending.promise
+ }
+ if (pending) pending.controller.abort()
+ const controller = new AbortController()
+ const delta: InflightDelta = {
+ activity: new Map(),
+ titles: new Map(),
+ removed: new Set(),
+ }
+ const request = apiFetch<SidebarThreadEnvelope>(sidebarUrl(serverId, retainId), {
+ signal: controller.signal,
+ }).then((envelope) => normalizeForumSidebarEnvelope(envelope, retainId))
+ .then((normalized) => {
+ let base = normalized.base
+ let retained = normalized.retained
+ const channelMetas = { ...normalized.channelMetas }
+ const openerHints = { ...normalized.openerHints }
+ for (const [childId, update] of delta.activity) {
+ base = patchForumSidebarActivity(base, childId, update.parentChannelId, update.activityAt)
+ if (retained?.id === childId) {
+ retained = {
+ ...retained,
+ activityAt: update.activityAt,
+ expiresAt: new Date(
+ Date.parse(update.activityAt) + SIDEBAR_ACTIVITY_WINDOW_MS,
+ ).toISOString(),
+ }
+ }
+ if (channelMetas[childId]) {
+ channelMetas[childId] = { ...channelMetas[childId], activityAt: update.activityAt }
+ }
+ }
+ for (const [childId, title] of delta.titles) {
+ base = patchForumSidebarTitle(base, childId, title)
+ if (retained?.id === childId) retained = { ...retained, title }
+ const meta = channelMetas[childId]
+ if (meta && openerHints[meta.parentMessageId]) {
+ openerHints[meta.parentMessageId] = {
+ ...openerHints[meta.parentMessageId],
+ content: title,
+ }
+ }
+ }
+ for (const childId of delta.removed) {
+ const meta = channelMetas[childId]
+ if (meta) delete openerHints[meta.parentMessageId]
+ delete channelMetas[childId]
+ base = removeForumSidebarThread(base, childId)
+ if (retained?.id === childId) retained = null
+ }
+ return { ...normalized, base, retained, channelMetas, openerHints }
+ }).finally(() => {
+ const current = inflight.get(serverId)
+ if (current?.promise !== request) return
+ if (current.abortTimer !== null) globalThis.clearTimeout(current.abortTimer)
+ inflight.delete(serverId)
+ })
+ const record: InflightRecord = {
+ promise: request,
+ delta,
+ candidate: retainId,
+ controller,
+ signals: new Set(),
+ abortTimer: null,
+ }
+ inflight.set(serverId, record)
+ attachInflightSignal(serverId, record, signal)
+ return request
+}
+
+function recordInflightDelta(serverId: string, update: (delta: InflightDelta) => void) {
+ const record = inflight.get(serverId)
+ if (record) update(record.delta)
}
-function getForumSidebarRetained(
+function publishNormalizedForumSidebar(
queryClient: QueryClient,
serverId: string,
- childId: string,
+ normalized: NormalizedForumSidebarEnvelope,
+ retainId: string | null,
+ signal: AbortSignal | undefined,
+ token: ReturnType<typeof captureCommunityLiveSnapshotToken>,
) {
- return queryClient.getQueryData<ForumSidebarThread | null>(
- communityKeys.forumSidebarRetained(serverId, childId),
+ const threads = [
+ ...normalized.base.threads,
+ ...(normalized.retainedDisposition === "eligible" && normalized.retained
+ ? [normalized.retained]
+ : []),
+ ]
+ const byId = new Map(threads.map((thread) => [thread.id, thread]))
+ const participatingIds = new Set(normalized.base.threads.map((thread) => thread.id))
+ if (normalized.retainedDisposition === "eligible" && normalized.retained) {
+ participatingIds.add(normalized.retained.id)
+ }
+ publishCommunityForumSidebar(queryClient, {
+ serverId,
+ channels: Object.values(normalized.channelMetas).flatMap((meta) => {
+ const thread = byId.get(meta.id)
+ return thread ? [{
+ id: meta.id,
+ name: meta.name,
+ parentChannelId: meta.parentChannelId,
+ parentMessageId: meta.parentMessageId,
+ activityAt: thread.activityAt,
+ unread: thread.unread,
+ serverId: meta.serverId,
+ type: meta.type,
+ creatorId: meta.creatorId,
+ archived: meta.archived,
+ lastMessageAt: thread.activityAt,
+ participating: participatingIds.has(meta.id),
+ }] : []
+ }),
+ openers: Object.values(normalized.openerHints),
+ negativeRetain: retainId && normalized.retainedDisposition !== "eligible"
+ ? {
+ id: retainId,
+ disposition: normalized.retainedDisposition ?? "genuine-negative",
+ }
+ : null,
+ proof: { token, signal },
+ })
+}
+
+function canonicalSidebarBase(queryClient: QueryClient, serverId: string) {
+ const participating = new Set(
+ getCanonicalCommunityChannelMemberships(queryClient)
+ .filter((membership) => membership.relation === "notify")
+ .map((membership) => membership.channelId),
)
+ const messages = new Map(
+ getCanonicalCommunityMessages(queryClient).map((message) => [message.id, message]),
+ )
+ const transport = queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads(serverId),
+ )
+ return {
+ threads: getCanonicalCommunityChannels(queryClient)
+ .filter((channel) => (
+ channel.serverId === serverId
+ && channel.type === "thread"
+ && !channel.archived
+ && participating.has(channel.id)
+ && channel.parentChannelId
+ && channel.parentMessageId
+ ))
+ .map((channel) => {
+ const activityAt = channel.lastMessageAt ?? ""
+ const activityMs = Date.parse(activityAt)
+ return {
+ id: channel.id,
+ parentChannelId: channel.parentChannelId!,
+ parentMessageId: channel.parentMessageId!,
+ title: messages.get(channel.parentMessageId!)?.content ?? channel.name,
+ activityAt,
+ expiresAt: Number.isFinite(activityMs)
+ ? new Date(activityMs + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()
+ : activityAt,
+ unread: channel.unread,
+ }
+ })
+ .sort(compareThreads),
+ verifiedEpoch: useCommunityWsStore.getState().accessEpoch,
+ serverNow: transport?.serverNow ?? new Date().toISOString(),
+ serverClockOffsetMs: transport?.serverClockOffsetMs ?? 0,
+ } satisfies ForumSidebarQueryData
+}
+
+export function getForumSidebarBase(queryClient: QueryClient, serverId: string) {
+ return canonicalSidebarBase(queryClient, serverId)
}
export function isKnownNonForumSidebarChannel(
@@ -509,18 +535,12 @@ export function isKnownNonForumSidebarChannel(
serverId: string,
channelId: string,
) {
- const server = queryClient.getQueryData<ServerDetail>(communityKeys.server(serverId))
- const topLevel = server?.categories
- .flatMap((category) => category.channels)
- .find((channel) => channel.id === channelId)
- if (topLevel) return topLevel.type !== "forum"
- const meta = queryClient.getQueryData<ChildChannelMeta>(
- communityKeys.channelMeta(serverId, channelId),
- )
- if (!meta) return false
- const parent = server?.categories
- .flatMap((category) => category.channels)
- .find((channel) => channel.id === meta.parentChannelId)
+ const channels = getCanonicalCommunityChannels(queryClient)
+ const channel = channels.find((candidate) => candidate.id === channelId)
+ if (!channel) return false
+ if (channel.serverId !== serverId) return true
+ if (channel.type !== "thread") return channel.type !== "forum"
+ const parent = channels.find((candidate) => candidate.id === channel.parentChannelId)
return !!parent && parent.type !== "forum"
}
@@ -529,10 +549,11 @@ export function isForumSidebarParent(
serverId: string,
parentChannelId: string,
) {
- return queryClient.getQueryData<ServerDetail>(communityKeys.server(serverId))
- ?.categories.some((category) => category.channels.some(
- (channel) => channel.id === parentChannelId && channel.type === "forum",
- )) ?? false
+ return getCanonicalCommunityChannels(queryClient).some((channel) => (
+ channel.id === parentChannelId
+ && channel.serverId === serverId
+ && channel.type === "forum"
+ ))
}
export function hasForumSidebarOwnershipEvidence(
@@ -540,29 +561,20 @@ export function hasForumSidebarOwnershipEvidence(
serverId: string,
childId: string,
) {
- if (isKnownNonForumSidebarChannel(queryClient, serverId, childId)) return false
- if (hasForumSidebarThread(getForumSidebarBase(queryClient, serverId), childId)) return true
- if (getForumSidebarRetained(queryClient, serverId, childId)) return true
- const server = queryClient.getQueryData<ServerDetail>(communityKeys.server(serverId))
- if (Object.values(server?.forumUnreadState ?? {}).some(
- (state) => state.childIds.includes(childId),
- )) return true
- const meta = queryClient.getQueryData<ChildChannelMeta>(
- communityKeys.channelMeta(serverId, childId),
- )
- return !!meta && isForumSidebarParent(queryClient, serverId, meta.parentChannelId)
+ return getCanonicalCommunityChannels(queryClient).some((channel) => (
+ channel.id === childId && channel.serverId === serverId && channel.type === "thread"
+ ))
}
-function patchRetained(
+export function removeForumSidebarUnreadChild(
queryClient: QueryClient,
- serverId: string,
- childId: string,
- patch: (thread: ForumSidebarThread) => ForumSidebarThread,
+ _serverId: string,
+ childChannelId: string,
) {
- queryClient.setQueryData<ForumSidebarThread | null | undefined>(
- communityKeys.forumSidebarRetained(serverId, childId),
- (thread) => thread ? patch(thread) : thread,
- )
+ patchCanonicalCommunityChannel(queryClient, childChannelId, (row) => ({
+ ...row,
+ unread: false,
+ }))
}
export function patchForumSidebarActivityExact(
@@ -575,19 +587,9 @@ export function patchForumSidebarActivityExact(
recordInflightDelta(serverId, (delta) => {
delta.activity.set(childId, { parentChannelId, activityAt })
})
- queryClient.setQueryData<ForumSidebarQueryData | undefined>(
- communityKeys.forumSidebarThreads(serverId),
- (data) => patchForumSidebarActivity(data, childId, parentChannelId, activityAt),
- )
- patchRetained(queryClient, serverId, childId, (thread) => ({
- ...thread,
- activityAt,
- expiresAt: new Date(Date.parse(activityAt) + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString(),
- }))
- queryClient.setQueryData<ChildChannelMeta | undefined>(
- communityKeys.channelMeta(serverId, childId),
- (meta) => meta ? { ...meta, activityAt } : meta,
- )
+ patchCanonicalCommunityChannel(queryClient, childId, (row) => (
+ row.parentChannelId === parentChannelId ? { ...row, lastMessageAt: activityAt } : row
+ ))
}
export function patchForumSidebarTitleExact(
@@ -596,20 +598,14 @@ export function patchForumSidebarTitleExact(
childId: string,
title: string,
) {
- recordInflightDelta(serverId, (delta) => {
- delta.titles.set(childId, title)
- })
- queryClient.setQueryData<ForumSidebarQueryData | undefined>(
- communityKeys.forumSidebarThreads(serverId),
- (data) => patchForumSidebarTitle(data, childId, title),
- )
- patchRetained(queryClient, serverId, childId, (thread) => ({ ...thread, title }))
- const meta = queryClient.getQueryData<ChildChannelMeta>(communityKeys.channelMeta(serverId, childId))
- if (meta) {
- queryClient.setQueryData<ForumOpenerHint | undefined>(
- communityKeys.forumOpenerHint(serverId, meta.parentMessageId),
- (hint) => hint ? { ...hint, content: title } : hint,
- )
+ recordInflightDelta(serverId, (delta) => delta.titles.set(childId, title))
+ const channel = getCanonicalCommunityChannels(queryClient)
+ .find((candidate) => candidate.id === childId && candidate.serverId === serverId)
+ if (channel?.parentMessageId) {
+ patchCanonicalCommunityMessage(queryClient, channel.parentMessageId, (row) => ({
+ ...row,
+ content: title,
+ }))
}
}
@@ -618,24 +614,8 @@ export function removeForumSidebarThreadExact(
serverId: string,
childId: string,
) {
- const meta = queryClient.getQueryData<ChildChannelMeta>(
- communityKeys.channelMeta(serverId, childId),
- )
- const parentMessageId = meta?.parentMessageId ??
- getForumSidebarRetained(queryClient, serverId, childId)?.parentMessageId ??
- getForumSidebarBase(queryClient, serverId)?.threads
- .find((thread) => thread.id === childId)?.parentMessageId
- removeForumSidebarProjectionExact(queryClient, serverId, childId)
- queryClient.removeQueries({
- queryKey: communityKeys.channelMeta(serverId, childId),
- exact: true,
- })
- if (parentMessageId) {
- queryClient.removeQueries({
- queryKey: communityKeys.forumOpenerHint(serverId, parentMessageId),
- exact: true,
- })
- }
+ recordInflightDelta(serverId, (delta) => delta.removed.add(childId))
+ removeCanonicalCommunityChannel(queryClient, childId)
}
export function removeForumSidebarProjectionExact(
@@ -643,71 +623,48 @@ export function removeForumSidebarProjectionExact(
serverId: string,
childId: string,
) {
- removeForumSidebarBaseProjectionExact(queryClient, serverId, childId, "genuine")
- queryClient.removeQueries({
- queryKey: communityKeys.forumSidebarRetained(serverId, childId),
- exact: true,
- })
+ recordInflightDelta(serverId, (delta) => delta.removed.add(childId))
+ removeCanonicalCommunityChannelMembership(queryClient, childId, "notify")
+ removeForumSidebarUnreadChild(queryClient, serverId, childId)
}
-function removeForumSidebarBaseProjectionExact(
+export function restoreForumSidebarThreadInflight(serverId: string, childId: string) {
+ recordInflightDelta(serverId, (delta) => delta.removed.delete(childId))
+}
+
+export function removeForumSidebarChildrenForParent(
queryClient: QueryClient,
serverId: string,
- childId: string,
- cause: "genuine" | "archive-tag" = "genuine",
+ parentChannelId: string,
) {
- const record = inflight.get(serverId)
- if (record) {
- record.delta.removed.add(childId)
- if (cause === "archive-tag") {
- record.delta.archiveRemovals.set(childId, record.generation)
- } else {
- record.delta.archiveRemovals.delete(childId)
- }
+ for (const child of getCanonicalCommunityChannels(queryClient)) {
+ if (
+ child.serverId === serverId
+ && child.type === "thread"
+ && child.parentChannelId === parentChannelId
+ ) removeForumSidebarThreadExact(queryClient, serverId, child.id)
}
- queryClient.setQueryData<ForumSidebarQueryData | undefined>(
- communityKeys.forumSidebarThreads(serverId),
- (data) => removeForumSidebarThread(data, childId),
- )
}
-/** Undo only the in-flight removal tombstone after an optimistic HTTP failure. */
-export function restoreForumSidebarThreadInflight(
+export async function invalidateForumSidebarBaseExact(
+ queryClient: QueryClient,
serverId: string,
- childId: string,
) {
- recordInflightDelta(serverId, (delta) => {
- if (!delta.archiveRemovals.has(childId)) delta.removed.delete(childId)
- })
+ const pending = inflight.get(serverId)
+ if (pending) {
+ if (pending.abortTimer !== null) globalThis.clearTimeout(pending.abortTimer)
+ pending.controller.abort()
+ inflight.delete(serverId)
+ }
+ const queryKey = communityKeys.forumSidebarThreads(serverId)
+ await queryClient.cancelQueries({ queryKey, exact: true })
+ await queryClient.invalidateQueries({ queryKey, exact: true, refetchType: "active" })
}
-export function removeForumSidebarChildrenForParent(
+async function fetchForumSidebarBaseExact(
queryClient: QueryClient,
serverId: string,
- parentChannelId: string,
) {
- const childIds = new Set(
- getForumSidebarBase(queryClient, serverId)?.threads
- .filter((thread) => thread.parentChannelId === parentChannelId)
- .map((thread) => thread.id) ?? [],
- )
- for (const [, meta] of queryClient.getQueriesData<ChildChannelMeta>({
- queryKey: communityKeys.channelMetaRoot(serverId),
- })) {
- if (meta?.parentChannelId === parentChannelId) childIds.add(meta.id)
- }
- for (const [, thread] of queryClient.getQueriesData<ForumSidebarThread | null>({
- queryKey: communityKeys.forumSidebarRetainedRoot(serverId),
- })) {
- if (thread?.parentChannelId === parentChannelId) childIds.add(thread.id)
- }
- for (const childId of childIds) {
- removeForumSidebarUnreadChild(queryClient, serverId, childId)
- removeForumSidebarThreadExact(queryClient, serverId, childId)
- }
-}
-
-export async function invalidateForumSidebarBaseExact(queryClient: QueryClient, serverId: string) {
const pending = inflight.get(serverId)
if (pending) {
if (pending.abortTimer !== null) globalThis.clearTimeout(pending.abortTimer)
@@ -716,11 +673,143 @@ export async function invalidateForumSidebarBaseExact(queryClient: QueryClient,
}
const queryKey = communityKeys.forumSidebarThreads(serverId)
await queryClient.cancelQueries({ queryKey, exact: true })
- await queryClient.invalidateQueries({
+ await queryClient.invalidateQueries({ queryKey, exact: true, refetchType: "none" })
+
+ const registry = getCommunityDbRegistry(queryClient)
+ const unreadProjection = getActiveAccountUnreadProjection(queryClient)
+ const confirmation = unreadProjection.beginAccessConfirmation()
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ const requestEpoch = useCommunityWsStore.getState().accessEpoch
+ let normalized: NormalizedForumSidebarEnvelope | undefined
+ let proof: CommunityFreshQueryProof | undefined
+ await queryClient.fetchQuery({
queryKey,
- exact: true,
- refetchType: "active",
+ staleTime: 0,
+ queryFn: async ({ signal }) => {
+ normalized = await fetchForumSidebar(serverId, null, signal)
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError")
+ proof = { token, signal }
+ publishNormalizedForumSidebar(
+ queryClient,
+ serverId,
+ normalized,
+ null,
+ signal,
+ token,
+ )
+ unreadProjection.confirmAccessScopes(
+ normalized.base.threads.map((thread) => ({
+ kind: "channel" as const,
+ channelId: thread.id,
+ })),
+ confirmation,
+ )
+ return {
+ ...normalized.base,
+ threads: registry ? [] : normalized.base.threads,
+ verifiedEpoch: requestEpoch,
+ }
+ },
})
+ if (!normalized || !proof) throw new Error("Forum sidebar base fetch did not settle")
+ return { normalized, proof }
+}
+
+/**
+ * Reconciles persisted viewer-notify rows after a socket gap. The base
+ * response is intentionally bounded (72h / five per parent), so ordinary
+ * absence is not negative evidence. A missing local row is removable only
+ * when it is inside the fresh server window and either the server returned
+ * fewer than five siblings or the row would sort above the server's fifth
+ * result. Lower-ranked misses cannot displace the authoritative top five and
+ * are retained without an unbounded retainId request fan-out.
+ */
+export async function reconcileForumSidebarNotifyMemberships(
+ queryClient: QueryClient,
+ serverId: string,
+) {
+ // One authoritative query-cache fetch both refreshes active observers and
+ // supplies the bounded negative proof. Avoid invalidating into a first
+ // active refetch and then issuing a second direct request.
+ const { normalized, proof } = await fetchForumSidebarBaseExact(queryClient, serverId)
+ return reconcileForumSidebarNotifyMembershipsFromBase(
+ queryClient,
+ serverId,
+ normalized.base,
+ proof,
+ )
+}
+
+function reconcileForumSidebarNotifyMembershipsFromBase(
+ queryClient: QueryClient,
+ serverId: string,
+ base: ForumSidebarQueryData,
+ proof: CommunityFreshQueryProof,
+ protectedRetainId: string | null = null,
+) {
+ const channels = getCanonicalCommunityChannels(queryClient)
+ const channelById = new Map(channels.map((channel) => [channel.id, channel]))
+ const notifyIds = new Set(
+ getCanonicalCommunityChannelMemberships(queryClient)
+ .filter((membership) => membership.relation === "notify")
+ .map((membership) => membership.channelId),
+ )
+ const candidates = channels.filter((channel) => (
+ channel.serverId === serverId
+ && channel.type === "thread"
+ && notifyIds.has(channel.id)
+ && !!channel.parentChannelId
+ && channelById.get(channel.parentChannelId)?.type === "forum"
+ ))
+
+ const baseIds = new Set(base.threads.map((thread) => thread.id))
+ const baseByParent = new Map<string, ForumSidebarThread[]>()
+ for (const thread of base.threads) {
+ baseByParent.set(thread.parentChannelId, [
+ ...(baseByParent.get(thread.parentChannelId) ?? []),
+ thread,
+ ])
+ }
+ const serverNowMs = Date.parse(base.serverNow)
+ const removedIds: string[] = []
+ for (const channel of candidates) {
+ if (
+ channel.id === protectedRetainId
+ || baseIds.has(channel.id)
+ || !channel.parentChannelId
+ ) continue
+ const activityAt = channel.lastMessageAt ?? ""
+ const activityMs = Date.parse(activityAt)
+ if (
+ Number.isFinite(serverNowMs)
+ && Number.isFinite(activityMs)
+ && activityMs + SIDEBAR_ACTIVITY_WINDOW_MS <= serverNowMs
+ ) continue
+ const siblings = (baseByParent.get(channel.parentChannelId) ?? [])
+ .slice()
+ .sort(compareThreads)
+ const candidate = {
+ id: channel.id,
+ parentChannelId: channel.parentChannelId,
+ parentMessageId: channel.parentMessageId ?? "",
+ title: channel.name,
+ activityAt,
+ expiresAt: Number.isFinite(activityMs)
+ ? new Date(activityMs + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()
+ : activityAt,
+ unread: channel.unread,
+ }
+ if (siblings.length >= 5 && compareThreads(candidate, siblings[4]!) > 0) continue
+ publishCommunityForumSidebar(queryClient, {
+ serverId,
+ channels: [],
+ openers: [],
+ negativeRetain: { id: channel.id, disposition: "genuine-negative" },
+ proof,
+ })
+ removedIds.push(channel.id)
+ }
+ return { removedIds }
}
export async function grantForumSidebarChild(
@@ -729,52 +818,17 @@ export async function grantForumSidebarChild(
childId: string,
) {
const unreadProjection = getActiveAccountUnreadProjection(queryClient)
- const accessConfirmation = unreadProjection.beginAccessConfirmation()
- recordInflightDelta(serverId, (delta) => {
- delta.removed.delete(childId)
- })
- void queryClient.cancelQueries({
- queryKey: communityKeys.forumSidebarRetained(serverId, childId),
- exact: true,
- })
- queryClient.removeQueries({
- queryKey: communityKeys.forumSidebarRetained(serverId, childId),
- exact: true,
- })
- queryClient.removeQueries({
- queryKey: communityKeys.channelMeta(serverId, childId),
- exact: true,
- })
- await invalidateForumSidebarBaseExact(queryClient, serverId)
- if (hasForumSidebarThread(getForumSidebarBase(queryClient, serverId), childId)) {
- unreadProjection.confirmAccessScopes(
- [{ kind: "channel", channelId: childId }],
- accessConfirmation,
- )
- return
- }
-
- // The base query may be inactive, and its activity window may omit the
- // newly re-granted child. A retained fetch is the authoritative access
- // check for that exact child; only a positive result releases its fence.
- const requestEpoch = useCommunityWsStore.getState().accessEpoch
+ const confirmation = unreadProjection.beginAccessConfirmation()
+ const token = captureCommunityLiveSnapshotToken(queryClient)
const normalized = await fetchForumSidebar(serverId, childId)
- seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, childId)
- queryClient.setQueryData(
- communityKeys.forumSidebarThreads(serverId),
- { ...normalized.base, verifiedEpoch: requestEpoch },
- )
- queryClient.setQueryData(
- communityKeys.forumSidebarRetained(serverId, childId),
- normalized.retained,
- )
+ publishNormalizedForumSidebar(queryClient, serverId, normalized, childId, undefined, token)
if (
hasForumSidebarThread(normalized.base, childId)
|| normalized.retainedDisposition === "eligible" && normalized.retained?.id === childId
) {
unreadProjection.confirmAccessScopes(
[{ kind: "channel", channelId: childId }],
- accessConfirmation,
+ confirmation,
)
}
}
@@ -785,222 +839,16 @@ export function reconcileForumSidebarArchiveTag(
childId: string,
archived: boolean,
) {
- const retainedKey = communityKeys.forumSidebarRetained(serverId, childId)
if (archived) {
- removeForumSidebarBaseProjectionExact(
- queryClient,
- serverId,
- childId,
- "archive-tag",
- )
- queryClient.removeQueries({ queryKey: retainedKey, exact: true })
- return invalidateForumSidebarBaseExact(queryClient, serverId)
- }
- const record = inflight.get(serverId)
- if (record && record.delta.archiveRemovals.get(childId) === record.generation) {
- record.delta.archiveRemovals.delete(childId)
- record.delta.removed.delete(childId)
- }
- const retainedState = queryClient.getQueryState<ForumSidebarThread | null>(retainedKey)
- const resetRetained = retainedState?.data === null || retainedState?.fetchStatus === "fetching"
- ? queryClient.cancelQueries({ queryKey: retainedKey, exact: true }).then(() => {
- queryClient.removeQueries({ queryKey: retainedKey, exact: true })
- })
- : Promise.resolve()
- return resetRetained.then(() => {
- return invalidateForumSidebarBaseExact(queryClient, serverId)
- })
-}
-
-function sidebarUrl(serverId: string, retainId: string | null) {
- const params = new URLSearchParams({
- type: "thread",
- parentType: "forum",
- participating: "true",
- activeWithin: "72h",
- limitPerParent: "5",
- include: "parentMessage",
- })
- if (retainId) params.set("retainId", retainId)
- return `/api/community/servers/${serverId}/channels?${params.toString()}`
-}
-
-function attachInflightSignal(
- serverId: string,
- record: InflightRecord,
- signal?: AbortSignal,
-) {
- if (!signal || record.signals.has(signal)) return
- if (record.abortTimer !== null) {
- globalThis.clearTimeout(record.abortTimer)
- record.abortTimer = null
- }
- record.signals.add(signal)
- const release = () => {
- record.signals.delete(signal)
- if (record.signals.size > 0 || record.abortTimer !== null) return
- record.abortTimer = globalThis.setTimeout(() => {
- record.abortTimer = null
- if (inflight.get(serverId) === record && record.signals.size === 0) {
- record.controller.abort()
- }
- }, STRICT_MODE_ABORT_GRACE_MS)
- }
- if (signal.aborted) release()
- else signal.addEventListener("abort", release, { once: true })
-}
-
-function fetchForumSidebar(serverId: string, retainId: string | null, signal?: AbortSignal) {
- const pending = inflight.get(serverId)
- if (pending?.candidate === retainId && !pending.controller.signal.aborted) {
- attachInflightSignal(serverId, pending, signal)
- return pending.promise
- }
- if (pending) {
- if (pending.abortTimer !== null) globalThis.clearTimeout(pending.abortTimer)
- pending.controller.abort()
- inflight.delete(serverId)
+ removeCanonicalCommunityChannelMembership(queryClient, childId, "notify")
+ } else {
+ setCanonicalCommunityChannelMembership(queryClient, childId, "notify", true)
}
- const controller = new AbortController()
- const generation = ++nextInflightGeneration
- const delta: InflightDelta = {
- activity: new Map(),
- titles: new Map(),
- removed: new Set(),
- archiveRemovals: new Map(),
- }
- const request = apiFetch<SidebarThreadEnvelope>(sidebarUrl(serverId, retainId), {
- signal: controller.signal,
+ recordInflightDelta(serverId, (delta) => {
+ if (archived) delta.removed.add(childId)
+ else delta.removed.delete(childId)
})
- .then((envelope) => normalizeForumSidebarEnvelope(envelope, retainId))
- .then((normalized) => {
- let base: ForumSidebarQueryData | undefined = normalized.base
- let retained = normalized.retained
- let retainedDisposition = normalized.retainedDisposition
- const channelMetas = { ...normalized.channelMetas }
- const openerHints = { ...normalized.openerHints }
- for (const [childId, update] of delta.activity) {
- base = patchForumSidebarActivity(
- base,
- childId,
- update.parentChannelId,
- update.activityAt,
- )
- if (retained?.id === childId) {
- retained = {
- ...retained,
- activityAt: update.activityAt,
- expiresAt: new Date(
- Date.parse(update.activityAt) + SIDEBAR_ACTIVITY_WINDOW_MS,
- ).toISOString(),
- }
- }
- if (channelMetas[childId]) {
- channelMetas[childId] = {
- ...channelMetas[childId],
- activityAt: update.activityAt,
- }
- }
- }
- for (const [childId, title] of delta.titles) {
- base = patchForumSidebarTitle(base, childId, title)
- if (retained?.id === childId) retained = { ...retained, title }
- const meta = channelMetas[childId]
- if (meta && openerHints[meta.parentMessageId]) {
- openerHints[meta.parentMessageId] = {
- ...openerHints[meta.parentMessageId],
- content: title,
- }
- }
- }
- for (const childId of delta.removed) {
- const meta = channelMetas[childId]
- if (meta) delete openerHints[meta.parentMessageId]
- delete channelMetas[childId]
- base = removeForumSidebarThread(base, childId)
- if (retained?.id === childId) {
- if (
- retainedDisposition === "eligible"
- && retainId === childId
- && delta.archiveRemovals.get(childId) === generation
- ) {
- retainedDisposition = "opener-archived"
- }
- retained = null
- }
- }
- return {
- ...normalized,
- base: base ?? normalized.base,
- retained,
- retainedDisposition,
- channelMetas,
- openerHints,
- }
- })
- .finally(() => {
- const current = inflight.get(serverId)
- if (current?.promise !== request) return
- if (current.abortTimer !== null) globalThis.clearTimeout(current.abortTimer)
- inflight.delete(serverId)
- })
- const record: InflightRecord = {
- promise: request,
- delta,
- candidate: retainId,
- generation,
- controller,
- signals: new Set(),
- abortTimer: null,
- }
- inflight.set(serverId, record)
- attachInflightSignal(serverId, record, signal)
- return request
-}
-
-function seedForumSidebarResources(
- queryClient: QueryClient,
- serverId: string,
- normalized: NormalizedForumSidebarEnvelope,
- verifiedEpoch: number,
- retainId: string | null,
-) {
- if (
- retainId &&
- !normalized.retained &&
- !hasForumSidebarThread(normalized.base, retainId) &&
- hasForumSidebarOwnershipEvidence(queryClient, serverId, retainId)
- ) {
- if (normalized.retainedDisposition !== "opener-archived") {
- removeForumSidebarUnreadChild(queryClient, serverId, retainId)
- }
- // The retained query owns its negative result. Removing that active query
- // here makes `retained=null` immediately eligible to refetch in a loop.
- removeForumSidebarBaseProjectionExact(
- queryClient,
- serverId,
- retainId,
- normalized.retainedDisposition === "opener-archived"
- ? "archive-tag"
- : "genuine",
- )
- }
- for (const meta of Object.values(normalized.channelMetas)) {
- queryClient.setQueryData(
- communityKeys.channelMeta(serverId, meta.id),
- { ...meta, verifiedEpoch },
- )
- }
- for (const hint of Object.values(normalized.openerHints)) {
- queryClient.setQueryData(communityKeys.forumOpenerHint(serverId, hint.id), hint)
- }
-}
-
-function throwIfConsumerAborted(signal: AbortSignal) {
- if (!signal.aborted) return
- const error = new Error("Aborted")
- error.name = "AbortError"
- throw error
+ return invalidateForumSidebarBaseExact(queryClient, serverId)
}
export function useForumSidebarThreads(
@@ -1008,227 +856,149 @@ export function useForumSidebarThreads(
retainId: string | null,
enabled = true,
) {
+ const registry = useOptionalCommunityDbRegistry()
+ const restoredForumProjection = useSyncExternalStore(
+ registry?.subscribeRestoredCollections ?? subscribeToNoRestoredForumProjection,
+ () => Boolean(
+ registry?.hasRestoredCollection("channels")
+ && registry.hasRestoredCollection("channelMemberships")
+ && registry.hasRestoredCollection("messages"),
+ ),
+ noRestoredForumProjection,
+ )
const queryClient = useQueryClient()
+ const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const unreadProjection = useMemo(
() => getActiveAccountUnreadProjection(queryClient),
[queryClient],
)
- const unreadVersion = useSyncExternalStore(
+ useSyncExternalStore(
unreadProjection.subscribe,
unreadProjection.getSnapshot,
unreadProjection.getSnapshot,
)
- const reservationTarget = useInboxProjectionTarget(queryClient)
- const unreadExclusion = useMemo(
- () => reservedUnreadExclusion(reservationTarget, "channels"),
- [reservationTarget],
- )
- const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
- const previousRetainId = useRef(retainId)
- // Observe (without fetching) the already-canonical ServerDetail cache so a
- // fresh `/unreads` result re-runs attribution even when the sidebar rows did
- // not change. This is essential for access/archive/participation removal:
- // those must clear a prior fallback instead of being mistaken for expiry.
- const serverDetailQuery = useQuery<ServerDetail>({
- queryKey: communityKeys.server(serverId),
- queryFn: () => Promise.reject(new Error("server detail observer only")),
- enabled: false,
- })
- const query = useQuery({
+ const query = useQuery<ForumSidebarQueryData>({
queryKey: communityKeys.forumSidebarThreads(serverId),
enabled: !!serverId && enabled,
staleTime: Infinity,
queryFn: async ({ signal }) => {
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
- const accessConfirmation = unreadProjection.beginAccessConfirmation()
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ const confirmation = unreadProjection.beginAccessConfirmation()
const requestEpoch = useCommunityWsStore.getState().accessEpoch
const normalized = await fetchForumSidebar(serverId, retainId, signal)
- throwIfConsumerAborted(signal)
- seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, retainId)
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError")
+ if (registry) {
+ publishNormalizedForumSidebar(
+ queryClient,
+ serverId,
+ normalized,
+ retainId,
+ signal,
+ token,
+ )
+ reconcileForumSidebarNotifyMembershipsFromBase(
+ queryClient,
+ serverId,
+ normalized.base,
+ { token, signal },
+ normalized.retainedDisposition === "eligible"
+ ? normalized.retained?.id ?? null
+ : null,
+ )
+ }
unreadProjection.confirmAccessScopes(
[
...normalized.base.threads,
...(normalized.retainedDisposition === "eligible" && normalized.retained
? [normalized.retained]
: []),
- ].map((thread) => ({
- kind: "channel" as const,
- channelId: thread.id,
- })),
- accessConfirmation,
+ ].map((thread) => ({ kind: "channel" as const, channelId: thread.id })),
+ confirmation,
)
- if (retainId) {
- queryClient.setQueryData(
- communityKeys.forumSidebarRetained(serverId, retainId),
- normalized.retained,
- )
+ return {
+ ...normalized.base,
+ threads: registry ? [] : normalized.base.threads,
+ verifiedEpoch: requestEpoch,
}
- return { ...normalized.base, verifiedEpoch: requestEpoch }
},
})
+ const previousRetainId = useRef(retainId)
useEffect(() => {
if (previousRetainId.current === retainId) return
previousRetainId.current = retainId
- if (query.fetchStatus !== "fetching") return
- if (inflight.get(serverId)?.candidate === retainId) return
- void queryClient.cancelQueries({
- queryKey: communityKeys.forumSidebarThreads(serverId),
- exact: true,
- }).then(() => invalidateForumSidebarBaseExact(queryClient, serverId))
- }, [query.fetchStatus, queryClient, retainId, serverId])
- useEffect(() => {
- if (!retainId) return
- const canonical = query.data?.threads.find((thread) => thread.id === retainId)
- if (!canonical) return
- const key = communityKeys.forumSidebarRetained(serverId, retainId)
- if (queryClient.getQueryState(key)?.status === "success") return
- queryClient.setQueryData(key, canonical)
- }, [query.data, queryClient, retainId, serverId])
- const retainedKey = communityKeys.forumSidebarRetained(serverId, retainId ?? "__none__")
- const retainedState = queryClient.getQueryState<ForumSidebarThread | null>(retainedKey)
- const retainIsCanonical = !!retainId && hasForumSidebarThread(query.data, retainId)
- const retainedQuery = useQuery<ForumSidebarThread | null>({
- queryKey: retainedKey,
- enabled: enabled && !!retainId && query.isSuccess && query.fetchStatus === "idle" &&
- !retainIsCanonical && retainedState?.status !== "success",
- staleTime: Infinity,
- gcTime: 5 * 60 * 1000,
- queryFn: async ({ signal }) => {
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
- const accessConfirmation = unreadProjection.beginAccessConfirmation()
- const requestEpoch = useCommunityWsStore.getState().accessEpoch
- const normalized = await fetchForumSidebar(serverId, retainId, signal)
- throwIfConsumerAborted(signal)
- seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, retainId)
- if (normalized.retainedDisposition === "eligible" && normalized.retained) {
- unreadProjection.confirmAccessScopes(
- [{ kind: "channel", channelId: normalized.retained.id }],
- accessConfirmation,
- )
- }
- queryClient.setQueryData(
- communityKeys.forumSidebarThreads(serverId),
- { ...normalized.base, verifiedEpoch: requestEpoch },
- )
- return normalized.retained
- },
- })
- const [trustedBase, setTrustedBase] = useState<{
- serverId: string
- data: ForumSidebarQueryData
- } | null>(null)
+ void invalidateForumSidebarBaseExact(queryClient, serverId)
+ }, [queryClient, retainId, serverId])
+
+ const [clockNowMs, setClockNowMs] = useState<number | null>(null)
useEffect(() => {
- if (query.data?.verifiedEpoch !== accessEpoch) return
- setTrustedBase({ serverId, data: query.data })
- }, [accessEpoch, query.data, serverId])
- const renderableBase = query.data?.verifiedEpoch === accessEpoch
- ? query.data
- : trustedBase?.serverId === serverId ? trustedBase.data : undefined
+ const timeout = globalThis.setTimeout(() => setClockNowMs(Date.now()), 0)
+ return () => globalThis.clearTimeout(timeout)
+ }, [])
+ const serverNowMs = clockNowMs === null
+ ? null
+ : clockNowMs + (query.data?.serverClockOffsetMs ?? 0)
+ const canonical = useForumSidebarProjection(serverId, retainId, serverNowMs)
+ const attentionScopes = useAttentionScopes()
+ const providerless = useMemo(
+ () => clockNowMs === null
+ ? { threads: [], parentUnread: {} }
+ : deriveForumSidebarProjection(query.data, null, undefined, clockNowMs),
+ [clockNowMs, query.data],
+ )
+ const structuralProjection = registry
+ ? canonical ?? { threads: [], parentUnread: {} }
+ : providerless
const projection = useMemo(() => {
- void unreadVersion
- const raw = deriveForumSidebarProjection(
- renderableBase,
- renderableBase ? retainedQuery.data : null,
- serverDetailQuery.data?.forumUnreadState,
- )
- const family = `server-detail:${serverId}` as const
- const sourceByChannel = new Map(
- (serverDetailQuery.data?.unreadSources ?? []).map((source) => [source.channelId, source]),
- )
- const threads = raw.threads.map((thread) => {
- const source = sourceByChannel.get(thread.id)
- const unread = selectUnreadPresentation({
- accountUnread: unreadProjection.projectUnread(
- family,
- thread.id,
- thread.unread,
- source?.lastUnreadSeq,
- "channels",
- unreadExclusion,
- ),
- }).effectiveUnread
- if (unread === thread.unread) return thread
- return { ...thread, unread }
- })
- const renderedChildIds = new Set(threads.map((thread) => thread.id))
- let parentChanged = false
- let parentUnread = raw.parentUnread
- for (const [parentId, state] of Object.entries(
- serverDetailQuery.data?.forumUnreadState ?? {},
- )) {
- const unread = unreadProjection.projectForumParentUnread(
- serverId,
- parentId,
- state.baseUnread || raw.parentUnread[parentId] === true,
- sourceByChannel.get(parentId)?.lastUnreadSeq,
- renderedChildIds,
- unreadExclusion,
- )
- if (unread === raw.parentUnread[parentId]) continue
- if (!parentChanged) parentUnread = { ...raw.parentUnread }
- parentChanged = true
- parentUnread[parentId] = unread
+ if (!registry) return structuralProjection
+ const relevant = attentionScopes.filter((scope) => scope.serverId === serverId)
+ const unreadByScope = new Map(relevant.map((scope) => [
+ scope.scopeId,
+ scope.ordinaryUnread || scope.attentionCount > 0,
+ ]))
+ const parentUnread: Record<string, boolean> = {}
+ for (const scope of relevant) {
+ if (scope.parentChannelId && unreadByScope.get(scope.scopeId)) {
+ parentUnread[scope.parentChannelId] = true
+ } else if (!scope.parentChannelId) {
+ parentUnread[scope.channelId] = unreadByScope.get(scope.scopeId) ?? false
+ }
}
return {
- threads: threads.every((thread, index) => thread === raw.threads[index])
- ? raw.threads
- : threads,
+ threads: structuralProjection.threads.map((thread) => ({
+ ...thread,
+ unread: unreadByScope.get(thread.id) ?? false,
+ })),
parentUnread,
}
- }, [
- renderableBase,
- retainedQuery.data,
- serverDetailQuery.data?.forumUnreadState,
- serverDetailQuery.data?.unreadSources,
- unreadExclusion,
- serverId,
- unreadProjection,
- unreadVersion,
- ])
-
- useEffect(() => {
- if (!query.data) return
- reconcileForumSidebarUnreadFallbacks(
- queryClient,
- serverId,
- projection.threads.map((thread) => thread.id),
- )
- }, [projection.threads, query.data, queryClient, serverDetailQuery.data?.forumUnreadState, serverId])
+ }, [attentionScopes, registry, serverId, structuralProjection])
- // Expire rows against the server's clock without polling. The currently
- // retained route is deliberately excluded: it remains visible until the
- // viewer leaves it, even when its ordinary 72h expiry is already past.
useEffect(() => {
- const data = query.data
- if (!data) return
- const serverNowMs = Date.now() + data.serverClockOffsetMs
- const nextExpiry = data.threads
+ if (serverNowMs === null) return
+ const nextExpiry = projection.threads
+ .filter((thread) => thread.id !== retainId)
.map((thread) => Date.parse(thread.expiresAt))
- .filter((expiresAt) => Number.isFinite(expiresAt))
- .sort((a, b) => a - b)[0]
+ .filter((expiry) => Number.isFinite(expiry) && expiry > serverNowMs)
+ .sort((left, right) => left - right)[0]
if (nextExpiry === undefined) return
- const timeout = globalThis.setTimeout(() => {
- const current = getForumSidebarBase(queryClient, serverId)
- const currentServerNow = Date.now() + (current?.serverClockOffsetMs ?? 0)
- for (const thread of current?.threads ?? []) {
- if (Date.parse(thread.expiresAt) > currentServerNow) continue
- if (thread.id === retainId) {
- queryClient.setQueryData<ForumSidebarQueryData | undefined>(
- communityKeys.forumSidebarThreads(serverId),
- (value) => removeForumSidebarThread(value, thread.id),
- )
- } else {
- removeForumSidebarProjectionExact(queryClient, serverId, thread.id)
- }
- }
- void invalidateForumSidebarBaseExact(queryClient, serverId)
- }, Math.max(0, nextExpiry - serverNowMs) + 25)
+ const timeout = globalThis.setTimeout(
+ () => setClockNowMs(Date.now()),
+ Math.max(0, nextExpiry - serverNowMs) + 25,
+ )
return () => globalThis.clearTimeout(timeout)
- }, [query.data, queryClient, retainId, serverId])
+ }, [projection.threads, retainId, serverNowMs])
return {
...query,
threads: projection.threads,
parentUnread: projection.parentUnread,
+ projectionReady: query.isError || (
+ clockNowMs !== null
+ && (registry
+ ? query.data !== undefined
+ || restoredForumProjection
+ || (canonical?.threads.length ?? 0) > 0
+ : query.data !== undefined)
+ ),
+ verifiedEpoch: accessEpoch,
}
}
diff --git a/src/web/src/hooks/community/use-friends.dom.test.ts b/src/web/src/hooks/community/use-friends.dom.test.ts
index e2cea7903..aded9e34a 100644
--- a/src/web/src/hooks/community/use-friends.dom.test.ts
+++ b/src/web/src/hooks/community/use-friends.dom.test.ts
@@ -5,6 +5,13 @@ import { renderHook, waitFor } from "@/test/react-dom-harness"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
+const canonicalProfiles = vi.hoisted(() => ({
+ current: new Map<string, Record<string, unknown>>(),
+}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalProfilesByUserId: () => canonicalProfiles.current,
+}))
+
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
@@ -20,6 +27,7 @@ beforeEach(() => {
apiFetchMock.mockReset()
useCommunityWsStore.getState().reset()
useCommunityWsStore.getState().activateProfileAccount("viewer")
+ canonicalProfiles.current = new Map()
})
describe("useFriends / friendsQueryFn", () => {
@@ -64,11 +72,6 @@ describe("useFriends / friendsQueryFn", () => {
expect(data.friends).toHaveLength(1)
expect(data.blocked).toHaveLength(2)
expect(data.pending).toHaveLength(1)
- expect(useCommunityWsStore.getState().profilesByUserId).toMatchObject(new Map([
- ["friend_1", expect.objectContaining({ name: "n", avatarVersion: 1 })],
- ["blocked_1", expect.objectContaining({ name: "b", avatarVersion: 2 })],
- ["pending_1", expect.objectContaining({ name: "p", avatarVersion: 3 })],
- ]))
expect(apiFetchMock).toHaveBeenCalledTimes(3)
expect(apiFetchMock.mock.calls.map((call) => call[0]).sort()).toEqual([
"/api/community/friends/accepted",
@@ -107,40 +110,57 @@ describe("useFriends / friendsQueryFn", () => {
statusText: "",
sub: "legacy presentation",
},
+ {
+ id: "missing",
+ userId: "friend_missing",
+ name: "missing friend",
+ discriminator: "0003",
+ avatar: "missing",
+ avatarVersion: 0,
+ status: "offline",
+ sub: "missing presentation",
+ },
+ ],
+ pending: [
+ {
+ id: "p1", userId: "pending_1", name: "raw pending", avatar: "raw",
+ avatarVersion: 1, kind: "incoming",
+ },
+ {
+ id: "p-missing", userId: "pending_missing", name: "missing pending",
+ avatar: "missing", avatarVersion: 0, kind: "outgoing",
+ },
],
- pending: [{
- id: "p1",
- userId: "pending_1",
- name: "raw pending",
- avatar: "raw",
- avatarVersion: 1,
- kind: "incoming",
- }],
blocked: [
{ id: "b1", userId: "blocked_1", name: "raw blocked", avatar: "raw", avatarVersion: 1 },
{ id: "legacy-blocked", name: "legacy blocked", avatar: "legacy", avatarVersion: 0 },
+ { id: "missing-blocked", userId: "blocked_missing", name: "missing blocked", avatar: "missing", avatarVersion: 0 },
],
}
queryClient.setQueryData(communityKeys.friends(), raw)
- const store = useCommunityWsStore.getState()
- store.patchProfiles(store.beginProfileSnapshot(), [
- {
+ canonicalProfiles.current = new Map([
+ ["friend_1", {
id: "friend_1",
- identityAbout: { name: "Global Friend", discriminator: "0042" },
- avatar: { avatar: "friend-global", avatarVersion: 4 },
+ name: "Global Friend",
+ discriminator: "0042",
+ avatar: "friend-global",
+ avatarVersion: 4,
presence: "online",
- status: { statusEmoji: "🌿", statusText: "Here" },
- },
- {
+ statusEmoji: "🌿",
+ statusText: "Here",
+ }],
+ ["pending_1", {
id: "pending_1",
- identityAbout: { name: "Global Pending" },
- avatar: { avatar: "pending-global", avatarVersion: 5 },
- },
- {
+ name: "Global Pending",
+ avatar: "pending-global",
+ avatarVersion: 5,
+ }],
+ ["blocked_1", {
id: "blocked_1",
- identityAbout: { name: "Global Blocked" },
- avatar: { avatar: "blocked-global", avatarVersion: 6 },
- },
+ name: "Global Blocked",
+ avatar: "blocked-global",
+ avatarVersion: 6,
+ }],
])
const rendered = renderHook(() => useFriends(), {
wrapper: wrapperFor(queryClient),
@@ -158,12 +178,14 @@ describe("useFriends / friendsQueryFn", () => {
sub: "raw presentation",
}),
expect.objectContaining({ name: "legacy", sub: "legacy presentation" }),
+ expect.objectContaining({ name: "missing friend", sub: "missing presentation" }),
])
expect(rendered.result.current.pending[0]).toMatchObject({
name: "Global Pending",
avatar: "pending-global",
avatarVersion: 5,
})
+ expect(rendered.result.current.pending[1]).toMatchObject({ name: "missing pending" })
expect(rendered.result.current.blocked).toEqual([
expect.objectContaining({
name: "Global Blocked",
@@ -171,6 +193,7 @@ describe("useFriends / friendsQueryFn", () => {
avatarVersion: 6,
}),
expect.objectContaining({ name: "legacy blocked" }),
+ expect.objectContaining({ name: "missing blocked" }),
])
expect(queryClient.getQueryData(communityKeys.friends())).toBe(raw)
})
diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.ts
index fa2def064..8d2b7425a 100644
--- a/src/web/src/hooks/community/use-friends.ts
+++ b/src/web/src/hooks/community/use-friends.ts
@@ -10,7 +10,7 @@ import {
} from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import type { Friend, PendingRequest, BlockedUser } from "@/lib/community/models/people"
-import { useProfilesByUserId } from "@/stores/community/ws"
+import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
/**
@@ -110,14 +110,13 @@ export function useFriends(): UseQueryResult<FriendsResponse> & {
queryFn: friendsQueryFn,
placeholderData: keepPreviousData,
})
- const profilesByUserId = useProfilesByUserId()
+ const profilesByUserId = useCanonicalProfilesByUserId()
const friends = useMemo(
() => (query.data?.friends ?? EMPTY_FRIENDS).map((friend) => {
if (!friend.userId) return friend
- const profile = readCommunityProfile(
- profilesByUserId.get(friend.userId),
- friend.userId,
- )
+ const canonical = profilesByUserId.get(friend.userId)
+ if (!canonical) return friend
+ const profile = readCommunityProfile(canonical, friend.userId)
return {
...friend,
name: profile.name,
@@ -133,10 +132,9 @@ export function useFriends(): UseQueryResult<FriendsResponse> & {
)
const pending = useMemo(
() => (query.data?.pending ?? EMPTY_PENDING).map((request) => {
- const profile = readCommunityProfile(
- profilesByUserId.get(request.userId),
- request.userId,
- )
+ const canonical = profilesByUserId.get(request.userId)
+ if (!canonical) return request
+ const profile = readCommunityProfile(canonical, request.userId)
return {
...request,
name: profile.name,
@@ -149,10 +147,9 @@ export function useFriends(): UseQueryResult<FriendsResponse> & {
const blocked = useMemo(
() => (query.data?.blocked ?? EMPTY_BLOCKED).map((entry) => {
if (!entry.userId) return entry
- const profile = readCommunityProfile(
- profilesByUserId.get(entry.userId),
- entry.userId,
- )
+ const canonical = profilesByUserId.get(entry.userId)
+ if (!canonical) return entry
+ const profile = readCommunityProfile(canonical, entry.userId)
return {
...entry,
name: profile.name,
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 75675b06c..495b991c3 100644
--- a/src/web/src/hooks/community/use-inbox.dom.test.ts
+++ b/src/web/src/hooks/community/use-inbox.dom.test.ts
@@ -4,6 +4,19 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ CommunityDbProvider,
+} from "@/lib/community-db/projections"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import {
+ getCanonicalCommunityMessages,
+ ingestServers,
+ purgeCommunityServer,
+} from "@/lib/community-db/sync"
+import { getAccountUnreadProjection } from "./account-unread-projection"
import {
disposeInboxReadReservation,
inboxChannelRowTarget,
@@ -20,8 +33,315 @@ beforeEach(() => {
apiFetchMock.mockReset()
})
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+async function mountRailOnlyInbox() {
+ const message = {
+ id: "message-rail-only",
+ seq: 1,
+ type: "chat" as const,
+ authorId: "author",
+ authorName: "Author",
+ content: "visible before detail loads",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ attachments: [{
+ kind: "file" as const,
+ name: "evidence.txt",
+ url: "/evidence.txt",
+ size: "1 KB",
+ }],
+ }
+ const server = {
+ serverId: "server-rail-only",
+ serverName: "Rail only",
+ channels: [{
+ channelId: "channel-detail-pending",
+ channelName: "Detail pending",
+ lastMessageAt: "2026-09-25T00:00:00.000Z",
+ lastUnreadSeq: 1,
+ mentionCount: 1,
+ children: [],
+ }],
+ }
+ const mention = {
+ id: "mention-rail-only",
+ server: "Rail only",
+ serverId: server.serverId,
+ channel: "Detail pending",
+ channelId: server.channels[0].channelId,
+ m: message,
+ }
+ const marked = {
+ id: "marked-rail-only",
+ server: "Rail only",
+ serverId: server.serverId,
+ channel: "Detail pending",
+ channelId: server.channels[0].channelId,
+ m: message,
+ }
+ const unreadsData = { friendRequests: [], servers: [server], dms: [], truncated: false }
+ const mentionsData = { mentions: [mention], truncated: false }
+ const markedData = { marked: [marked] }
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ getAccountUnreadProjection(queryClient, "viewer").setNotificationPolicy({})
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ useCommunityWsStore.getState().reset()
+ useCommunityWsStore.getState().activateProfileAccount("viewer")
+ ingestServers(registry, {
+ servers: [{
+ id: "server-canonical-match",
+ name: "Canonical match",
+ initial: "C",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "owner",
+ }],
+ })
+ queryClient.setQueryData(communityKeys.servers(), {
+ servers: [{
+ id: server.serverId,
+ name: server.serverName,
+ initial: "R",
+ active: false,
+ unread: true,
+ mentions: 1,
+ ownerId: "owner",
+ unreadSources: [{
+ channelId: server.channels[0].channelId,
+ lastUnreadSeq: 1,
+ }],
+ mentionSources: [{
+ channelId: server.channels[0].channelId,
+ count: 1,
+ lastSeq: 1,
+ }],
+ }, {
+ id: "server-canonical-match",
+ name: "Canonical match raw",
+ initial: "C",
+ active: false,
+ unread: true,
+ mentions: 0,
+ ownerId: "owner",
+ unreadSources: [{
+ channelId: "channel-canonical-match",
+ lastUnreadSeq: 2,
+ }],
+ }],
+ })
+ queryClient.setQueryData(communityKeys.inboxUnreads(), unreadsData)
+ queryClient.setQueryData(communityKeys.inboxMentions(), mentionsData)
+ queryClient.setQueryData(communityKeys.inboxMarked(), markedData)
+ queryClient.setQueryData(communityKeys.pins(server.channels[0].channelId), {
+ pins: [message],
+ })
+ apiFetchMock.mockReturnValue(new Promise(() => undefined))
+ const { useInboxMarked, useInboxMentions, useInboxUnreads } = await import("./use-inbox")
+ const { usePins } = await import("./use-channel-panels")
+ const { useServers } = await import("./use-servers")
+ let snapshot = {
+ unreadIds: [] as string[],
+ mentionIds: [] as string[],
+ markedIds: [] as string[],
+ pinIds: [] as string[],
+ attachmentNames: [] as string[],
+ railUnreadIds: [] as string[],
+ }
+ function Harness() {
+ const unreads = useInboxUnreads()
+ const mentions = useInboxMentions()
+ const marks = useInboxMarked(false)
+ const pins = usePins(server.channels[0].channelId)
+ const rail = useServers()
+ snapshot = {
+ unreadIds: unreads.servers.flatMap((entry) => entry.channels.map((channel) => channel.channelId)),
+ mentionIds: mentions.mentions.map((entry) => entry.m.id),
+ markedIds: marks.marked.map((entry) => entry.m.id),
+ pinIds: pins.pins.map((entry) => entry.id),
+ attachmentNames: [
+ ...marks.marked.flatMap((entry) => entry.m.attachments?.map((file) => file.name) ?? []),
+ ...pins.pins.flatMap((entry) => entry.attachments?.map((file) => file.name) ?? []),
+ ],
+ railUnreadIds: rail.servers.filter((entry) => entry.unread).map((entry) => entry.id),
+ }
+ return null
+ }
+ let renderer!: ReturnType<typeof rtlRender>
+ await act(async () => {
+ renderer = rtlRender(React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(
+ CommunityDbProvider,
+ { registry },
+ React.createElement(Harness),
+ ),
+ ))
+ })
+ return {
+ get snapshot() { return snapshot },
+ queryClient,
+ registry,
+ unreadsData,
+ mentionsData,
+ markedData,
+ dispose: async () => {
+ await act(async () => renderer.unmount())
+ registry["cleanup"]()
+ },
+ }
+}
+
describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
- it("passes friend requests through, seeds their profile, and exposes the outstanding boolean", async () => {
+ it("does not render raw message entities while the canonical store is empty", async () => {
+ const mounted = await mountRailOnlyInbox()
+
+ expect([...mounted.registry.collections.channels.keys()]).toEqual([])
+ expect([...mounted.registry.collections.messages.keys()]).toEqual([])
+ expect(mounted.snapshot).toEqual({
+ unreadIds: [],
+ mentionIds: [],
+ markedIds: [],
+ pinIds: [],
+ attachmentNames: [],
+ railUnreadIds: [],
+ })
+ await mounted.dispose()
+ })
+
+ it("keeps late Inbox rows hidden after an authoritative server purge", async () => {
+ const mounted = await mountRailOnlyInbox()
+ expect(mounted.snapshot.unreadIds).toEqual([])
+
+ await act(async () => {
+ purgeCommunityServer(mounted.registry, "server-rail-only")
+ mounted.queryClient.setQueryData(communityKeys.inboxUnreads(), mounted.unreadsData)
+ mounted.queryClient.setQueryData(communityKeys.inboxMentions(), mounted.mentionsData)
+ mounted.queryClient.setQueryData(communityKeys.inboxMarked(), mounted.markedData)
+ })
+
+ expect({
+ unreadIds: mounted.snapshot.unreadIds,
+ mentionIds: mounted.snapshot.mentionIds,
+ markedIds: mounted.snapshot.markedIds,
+ railUnreadIds: mounted.snapshot.railUnreadIds,
+ }).toEqual({
+ unreadIds: [],
+ mentionIds: [],
+ markedIds: [],
+ railUnreadIds: [],
+ })
+ await mounted.dispose()
+ })
+
+ it("does not project legacy Inbox child rows without canonical attention", async () => {
+ const data = {
+ friendRequests: [],
+ servers: [{
+ serverId: "s1",
+ serverName: "One",
+ channels: [{
+ channelId: "parent",
+ channelName: "Parent",
+ lastMessageAt: "2026-09-25T00:00:00.000Z",
+ lastUnreadSeq: 1,
+ mentionCount: 0,
+ hasDirectUnread: true,
+ children: [{
+ channelId: "child",
+ channelName: "Child",
+ lastMessageAt: "2026-09-25T00:00:01.000Z",
+ lastUnreadSeq: 2,
+ mentionCount: 0,
+ }],
+ }],
+ }],
+ dms: [],
+ truncated: false,
+ }
+ apiFetchMock.mockReturnValue(new Promise(() => undefined))
+ const { useInboxUnreads } = await import("./use-inbox")
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(communityKeys.inboxUnreads(), data)
+ const projection = getAccountUnreadProjection(queryClient, "viewer")
+ projection.setNotificationPolicy({})
+ let latest: ReturnType<typeof useInboxUnreads> | undefined
+ function Harness() {
+ latest = useInboxUnreads()
+ return null
+ }
+ let renderer!: ReturnType<typeof rtlRender>
+ await act(async () => {
+ renderer = rtlRender(React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Harness),
+ ))
+ })
+ expect(latest?.servers).toEqual([])
+
+ act(() => projection.retireAccessScope({ kind: "channel", channelId: "child" }))
+
+ expect(latest?.servers).toEqual([])
+ await act(async () => renderer.unmount())
+ })
+
+ it("uses the canonical DB rail when the raw servers query is absent", async () => {
+ apiFetchMock.mockReturnValue(new Promise(() => undefined))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const projection = getAccountUnreadProjection(queryClient, "viewer")
+ projection.setNotificationPolicy({})
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ ingestServers(registry, {
+ servers: [{
+ id: "db-only",
+ name: "DB only",
+ initial: "D",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "owner",
+ }],
+ })
+ const { useServers } = await import("./use-servers")
+ let serverIds: string[] = []
+ function Harness() {
+ serverIds = useServers().servers.map((server) => server.id)
+ return null
+ }
+ let renderer!: ReturnType<typeof rtlRender>
+ await act(async () => {
+ renderer = rtlRender(React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(
+ CommunityDbProvider,
+ { registry },
+ React.createElement(Harness),
+ ),
+ ))
+ })
+ await vi.waitFor(() => expect(serverIds).toEqual(["db-only"]))
+
+ act(() => projection.retireAccessScope({ kind: "server", serverId: "db-only" }))
+
+ expect(serverIds).toEqual([])
+ await act(async () => renderer.unmount())
+ await registry["cleanup"]()
+ })
+
+ it("does not project friend requests from the retired Inbox endpoint", async () => {
useCommunityWsStore.getState().reset()
useCommunityWsStore.getState().activateProfileAccount("viewer")
apiFetchMock.mockResolvedValueOnce({
@@ -50,13 +370,8 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
React.createElement(Harness),
))
- await vi.waitFor(() => expect(latest?.friendRequests).toHaveLength(1))
- expect(latest?.hasOutstandingFriendRequest).toBe(true)
- expect(useCommunityWsStore.getState().profilesByUserId.get("requester")).toMatchObject({
- name: "Ada",
- avatar: "avatar-url",
- avatarVersion: 7,
- })
+ expect(latest?.friendRequests).toEqual([])
+ expect(latest?.hasOutstandingFriendRequest).toBe(false)
expect(latest?.hasProjectedUnread).toBe(false)
await act(async () => renderer.unmount())
})
@@ -82,15 +397,9 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
await inboxUnreadsQueryFn()
- expect(useCommunityWsStore.getState().profilesByUserId.get("peer")).toMatchObject({
- name: "Grace",
- discriminator: "0007",
- avatar: "peer-avatar",
- avatarVersion: 8,
- })
})
- it("keeps last-good friend requests and their boolean after a stale refetch", async () => {
+ it("ignores last-good friend requests from the retired Inbox endpoint", async () => {
const request = {
id: "fr_1",
userId: "requester",
@@ -114,12 +423,11 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
{ client: qc },
React.createElement(Harness),
))
- await vi.waitFor(() => expect(latest?.friendRequests).toEqual([request]))
+ expect(latest?.friendRequests).toEqual([])
await qc.invalidateQueries({ queryKey: communityKeys.inboxUnreads(), exact: true })
- await vi.waitFor(() => expect(latest?.isError).toBe(true))
- expect(latest?.friendRequests).toEqual([request])
- expect(latest?.hasOutstandingFriendRequest).toBe(true)
+ expect(latest?.friendRequests).toEqual([])
+ expect(latest?.hasOutstandingFriendRequest).toBe(false)
expect(latest?.hasProjectedUnread).toBe(false)
await act(async () => renderer.unmount())
})
@@ -395,7 +703,7 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
disposeInboxReadReservation(qc)
})
- it("wires the production hook to its live QueryClient across rerenders", async () => {
+ it("keeps the visible hook read-only across rerenders", async () => {
apiFetchMock.mockResolvedValue({ servers: [], dms: [] })
const { useInboxUnreads } = await import("./use-inbox")
const qc = new QueryClient({
@@ -416,16 +724,16 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
await act(async () => {
renderer = rtlRender(tree)
})
- await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ expect(apiFetchMock).not.toHaveBeenCalled()
await act(async () => {
renderer.rerender(tree)
})
expect(renderer.container.querySelector("span")).toHaveAttribute("data-count", "0")
- expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(apiFetchMock).not.toHaveBeenCalled()
await act(async () => renderer.unmount())
})
- it("projects nested channel and DM reads while preserving unchanged rows", async () => {
+ it("ignores nested rows from the retired Inbox endpoint", async () => {
const removable = {
serverId: "s1",
serverName: "One",
@@ -493,15 +801,13 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
))
})
- expect(latest?.servers).toEqual([retained])
- expect(latest?.servers[0]).toBe(retained)
- expect(latest?.dms).toEqual([keptDm])
- expect(latest?.dms[0]).toBe(keptDm)
- expect(latest?.hasProjectedUnread).toBe(true)
+ expect(latest?.servers).toEqual([])
+ expect(latest?.dms).toEqual([])
+ expect(latest?.hasProjectedUnread).toBe(false)
await act(async () => renderer.unmount())
})
- it("projects one Inbox reservation into the feed aggregate and restores it on rollback", async () => {
+ it("does not let a legacy Inbox reservation create canonical attention", async () => {
const channel = {
channelId: "reserved",
channelName: "Reserved",
@@ -542,7 +848,7 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
React.createElement(Harness),
))
})
- expect(latest?.hasProjectedUnread).toBe(true)
+ expect(latest?.hasProjectedUnread).toBe(false)
let epoch = 0
await act(async () => {
@@ -557,12 +863,12 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
await act(async () => {
collapse!.rollbackProjection(epoch)
})
- expect(latest?.servers).toEqual([server])
- expect(latest?.hasProjectedUnread).toBe(true)
+ expect(latest?.servers).toEqual([])
+ expect(latest?.hasProjectedUnread).toBe(false)
await act(async () => renderer.unmount())
})
- it("keeps a child-only parent and clones only its changed channel path", async () => {
+ it("does not project a child-only parent from legacy Inbox data", async () => {
const child = {
channelId: "child",
channelName: "Post",
@@ -600,14 +906,11 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
React.createElement(Harness),
))
})
- expect(latest?.servers[0]).not.toBe(server)
- expect(latest?.servers[0]?.channels[0]).not.toBe(channel)
- expect(latest?.servers[0]?.channels[0]?.hasDirectUnread).toBe(false)
- expect(latest?.servers[0]?.channels[0]?.children[0]).toBe(child)
+ expect(latest?.servers).toEqual([])
await act(async () => renderer.unmount())
})
- it("retains legacy unread evidence after an absent rolling-deploy response", async () => {
+ it("does not retain legacy unread evidence after an absent response", async () => {
const data = {
servers: [{
serverId: "s1",
@@ -660,7 +963,7 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
await vi.waitFor(() => expect(latest?.servers).toEqual([]))
expect(latest?.servers).toEqual([])
expect(latest?.dms).toEqual([])
- expect(latest?.hasProjectedUnread).toBe(true)
+ expect(latest?.hasProjectedUnread).toBe(false)
await act(async () => renderer.unmount())
})
})
@@ -689,6 +992,34 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)
})
+ it("publishes only scoped embedded mention messages", async () => {
+ const message = {
+ id: "message-1",
+ type: "chat" as const,
+ seq: 4,
+ authorId: "author",
+ authorName: "Author",
+ content: "mention",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }
+ apiFetchMock.mockResolvedValueOnce({
+ mentions: [
+ { id: "scoped", server: "One", serverId: "s1", channel: "General", channelId: "c1", m: message },
+ { id: "unscoped", server: "One", serverId: "s1", channel: "General", m: { ...message, id: "message-2" } },
+ ],
+ truncated: false,
+ })
+ const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")
+ const { AccountUnreadProjection } = await import("./account-unread-projection")
+
+ const result = await inboxMentionsProjectedQueryFn(
+ new AccountUnreadProjection("u1"),
+ new QueryClient(),
+ )()
+
+ expect(result.mentions).toHaveLength(2)
+ })
+
it("cancels Mentions snapshot coverage when the transport fails", async () => {
apiFetchMock.mockRejectedValueOnce(new Error("offline"))
const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")
@@ -700,7 +1031,48 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
expect(projection.inspectForTests().pendingSnapshots).toBe(0)
})
- it("filters read mentions, preserves unscoped rows, and reports pending arrivals", async () => {
+ it("rejects a stale Mentions response before publishing its embedded message", async () => {
+ apiFetchMock.mockResolvedValueOnce({
+ mentions: [{
+ id: "attention-stale",
+ server: "One",
+ serverId: "s1",
+ channel: "General",
+ channelId: "c1",
+ m: {
+ id: "message-stale",
+ type: "chat",
+ seq: 4,
+ authorId: "author",
+ authorName: "Author",
+ content: "must not publish",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ },
+ }],
+ truncated: false,
+ stale: true,
+ })
+ const { inboxMentionsProjectedQueryFn } = await import("./use-inbox")
+ const { AccountUnreadProjection } = await import("./account-unread-projection")
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "u1")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const projection = new AccountUnreadProjection("u1")
+
+ try {
+ await expect(inboxMentionsProjectedQueryFn(projection, queryClient)())
+ .rejects.toThrow("stale D1 read")
+ expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
+ expect(projection.inspectForTests().pendingSnapshots).toBe(0)
+ expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)
+ } finally {
+ unregister()
+ await registry["cleanup"]()
+ }
+ })
+
+ it("ignores mentions from the retired Inbox endpoint", async () => {
const scoped = { id: "m1", channelId: "c1", m: { seq: 2 } }
const unscoped = { id: "m2", m: { seq: 1 } }
const data = { mentions: [scoped, unscoped], truncated: false }
@@ -725,13 +1097,12 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
React.createElement(Harness),
))
})
- expect(latest?.mentions).toEqual([unscoped])
- expect(latest?.mentions[0]).toBe(unscoped)
- expect(latest?.hasProjectedMention).toBe(true)
+ expect(latest?.mentions).toEqual([])
+ expect(latest?.hasProjectedMention).toBe(false)
await act(async () => renderer.unmount())
})
- it("suppresses same-sequence attention with an Unread reservation and keeps newer attention", async () => {
+ it("does not let legacy mention reservations mutate canonical attention", async () => {
const channel = {
channelId: "shared",
channelName: "Shared",
@@ -793,7 +1164,7 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
React.createElement(Harness),
))
})
- expect(mentions?.mentions).toEqual([same, newer])
+ expect(mentions?.mentions).toEqual([])
let epoch = 0
await act(async () => {
@@ -803,16 +1174,16 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
)
})
- expect(unreads?.servers).toEqual([server])
- expect(unreads?.hasProjectedUnread).toBe(true)
- expect(mentions?.mentions).toEqual([newer])
- expect(mentions?.hasProjectedMention).toBe(true)
+ expect(unreads?.servers).toEqual([])
+ expect(unreads?.hasProjectedUnread).toBe(false)
+ expect(mentions?.mentions).toEqual([])
+ expect(mentions?.hasProjectedMention).toBe(false)
await act(async () => {
collapse!.rollbackProjection(epoch)
})
- expect(unreads?.servers).toEqual([server])
- expect(mentions?.mentions).toEqual([same, newer])
+ expect(unreads?.servers).toEqual([])
+ expect(mentions?.mentions).toEqual([])
await act(async () => renderer.unmount())
})
@@ -838,7 +1209,7 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
await act(async () => renderer.unmount())
})
- it("retains a legacy mention after it falls outside a later window", async () => {
+ it("does not retain a legacy mention outside canonical attention", async () => {
const legacy = {
id: "legacy",
channelId: "c1",
@@ -869,13 +1240,145 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
})
await vi.waitFor(() => expect(latest?.mentions).toEqual([]))
expect(latest?.mentions).toEqual([])
- expect(latest?.hasProjectedMention).toBe(true)
+ expect(latest?.hasProjectedMention).toBe(false)
await act(async () => renderer.unmount())
})
})
-describe("eager Inbox query ownership", () => {
- it("keeps WS-live feeds fresh across observer remounts without duplicate reads", async () => {
+describe("canonical account attention query ownership", () => {
+ it("hydrates cold server and DM scope owners after attention refs arrive", async () => {
+ useCommunityWsStore.getState().reset()
+ useCommunityWsStore.getState().activateProfileAccount("viewer")
+ const directory = deferred<{ directory: Array<{
+ id: string
+ name: string
+ discriminator: string
+ channels: Array<{ id: string; name: string; type: "text" }>
+ }> }>()
+ const dms = deferred<{ conversations: Array<{
+ id: string
+ userId: string
+ name: string
+ discriminator: string
+ avatar: string
+ avatarVersion: number
+ status: "offline"
+ preview: string
+ unread: boolean
+ lastUnreadSeq: number
+ }> }>()
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url === "/api/community/users/me/attention") {
+ return Promise.resolve({
+ scopes: [{
+ scopeId: "channel-cold",
+ channelId: "channel-cold",
+ serverId: "server-cold",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 2,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }, {
+ scopeId: "dm-cold",
+ channelId: "dm-cold",
+ serverId: null,
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 3,
+ lastAttentionSeq: null,
+ attentionCount: 0,
+ }],
+ items: [],
+ limit: 100,
+ truncated: false,
+ })
+ }
+ if (url === "/api/community/users/me/channel-directory") return directory.promise
+ if (url === "/api/community/users/me/dms") return dms.promise
+ throw new Error(`unexpected request: ${url}`)
+ })
+ const { useInboxUnreads } = await import("./use-inbox")
+ const {
+ useAccountAttention,
+ useAccountAttentionScopeHydration,
+ } = await import("./use-account-attention")
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const registry = createCommunityDbRegistry(qc, "viewer")
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ let latest: ReturnType<typeof useInboxUnreads> | undefined
+ function Harness() {
+ useAccountAttention()
+ useAccountAttentionScopeHydration()
+ latest = useInboxUnreads()
+ return null
+ }
+ let renderer!: ReturnType<typeof rtlRender>
+ await act(async () => {
+ renderer = rtlRender(React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(
+ CommunityDbProvider,
+ { registry },
+ React.createElement(Harness),
+ ),
+ ))
+ })
+
+ await vi.waitFor(() => {
+ expect(latest?.pendingChannelIds).toEqual(expect.arrayContaining([
+ "channel-cold",
+ "dm-cold",
+ ]))
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/channel-directory")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/dms",
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ )
+ })
+ expect(latest?.servers).toEqual([])
+ expect(latest?.dms).toEqual([])
+
+ await act(async () => directory.resolve({
+ directory: [{
+ id: "server-cold",
+ name: "Cold server",
+ discriminator: "0042",
+ channels: [{ id: "channel-cold", name: "cold-channel", type: "text" }],
+ }],
+ }))
+ await vi.waitFor(() => expect(latest?.servers[0]?.channels[0]?.channelId)
+ .toBe("channel-cold"))
+ expect(latest?.dms).toEqual([])
+
+ await act(async () => dms.resolve({
+ conversations: [{
+ id: "dm-cold",
+ userId: "peer",
+ name: "Peer",
+ discriminator: "0002",
+ avatar: "",
+ avatarVersion: 1,
+ status: "offline",
+ preview: "",
+ unread: true,
+ lastUnreadSeq: 3,
+ }],
+ }))
+ await vi.waitFor(() => expect(latest?.dms[0]?.channelId).toBe("dm-cold"))
+ expect(latest?.pendingChannelIds).toEqual([])
+ expect(apiFetchMock.mock.calls.filter(
+ ([url]) => url === "/api/community/users/me/attention",
+ )).toHaveLength(1)
+
+ await act(async () => renderer.unmount())
+ unregister()
+ await registry["cleanup"]()
+ })
+
+ it("keeps visible Inbox projections transport-free across observer remounts", async () => {
apiFetchMock.mockImplementation((url: string) => Promise.resolve(
url.endsWith("/unreads")
? { servers: [], dms: [] }
@@ -897,30 +1400,37 @@ describe("eager Inbox query ownership", () => {
await act(async () => {
renderer = rtlRender(tree)
})
- await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ expect(apiFetchMock).not.toHaveBeenCalled()
await act(async () => renderer.unmount())
await act(async () => {
renderer = rtlRender(tree)
})
- expect(apiFetchMock).toHaveBeenCalledTimes(2)
- for (const queryKey of [
- communityKeys.inboxUnreads(),
- communityKeys.inboxMentions(),
- ]) {
- const options = qc.getQueryCache().find({ queryKey })?.options
- expect(options?.staleTime).toBe(Infinity)
- expect(options?.refetchOnReconnect).toBe(true)
- }
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ expect(qc.getQueryCache().find({ queryKey: communityKeys.accountAttention() })).toBeDefined()
+ expect(qc.getQueryCache().find({ queryKey: communityKeys.inboxUnreads() })).toBeUndefined()
+ expect(qc.getQueryCache().find({ queryKey: communityKeys.inboxMentions() })).toBeUndefined()
await qc.invalidateQueries({ queryKey: communityKeys.inbox() })
- await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(4))
+ expect(apiFetchMock).not.toHaveBeenCalled()
await act(async () => renderer.unmount())
})
})
describe("useInboxMarked", () => {
it("fetches the identity-aware marked feed only when enabled", async () => {
- apiFetchMock.mockResolvedValue({ marked: [] })
+ apiFetchMock.mockResolvedValue({ marked: [{
+ id: "mark-1",
+ channelId: "c1",
+ serverId: "s1",
+ m: {
+ id: "message-1",
+ type: "chat",
+ authorId: "author",
+ authorName: "Author",
+ content: "marked",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ },
+ }] })
const { useInboxMarked } = await import("./use-inbox")
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
function Harness() {
@@ -937,9 +1447,13 @@ describe("useInboxMarked", () => {
})
await vi.waitFor(() => {
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/marks")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/marks",
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ )
})
- expect(renderer.container.querySelector("span")).toHaveAttribute("data-count", "0")
+ await vi.waitFor(() => expect(renderer.container.querySelector("span"))
+ .toHaveAttribute("data-count", "1"))
act(() => renderer.unmount())
})
})
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index d1b8c466f..fbc911554 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -1,26 +1,30 @@
"use client"
-import { useEffect, useMemo, useSyncExternalStore } from "react"
-import { useQuery, useQueryClient, keepPreviousData, type UseQueryResult } from "@tanstack/react-query"
+import { useMemo, useSyncExternalStore } from "react"
+import { useQuery, useQueryClient, keepPreviousData, type QueryClient, type UseQueryResult } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import type { UnreadServer, UnreadDm, InboxFriendRequest, Mention, Marked } from "@/lib/community/models/inbox"
-import {
- inboxMentionRowTarget,
- reserveInboxUnreadsResponse,
-} from "./inbox-read-reservation"
+import { reserveInboxUnreadsResponse } from "./inbox-read-reservation"
import {
getActiveAccountUnreadProjection,
type AccountUnreadProjection,
type AccountUnreadSource,
} from "./account-unread-projection"
-import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
import {
- isInboxTargetReserved,
- reservedUnreadExclusion,
- selectUnreadPresentation,
-} from "./unread-presentation"
+ materializeCanonicalMessage,
+ useCanonicalChannelsById,
+ useCanonicalMessagesById,
+ useCanonicalProfilesByUserId,
+ useCanonicalServersById,
+ useDmProjection,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityEmbeddedMessages,
+} from "@/lib/community-db/sync"
+import { useAccountAttentionProjection } from "./use-account-attention"
class StaleReadError extends Error {
constructor() { super("stale D1 read"); this.name = "StaleReadError" }
@@ -31,10 +35,6 @@ function throwIfStale<T extends { stale?: boolean }>(v: T): T {
}
// Frozen empty fallbacks — see `use-servers.ts` for the rationale.
-const EMPTY_UNREADS: readonly UnreadServer[] = Object.freeze([])
-const EMPTY_DMS: readonly UnreadDm[] = Object.freeze([])
-const EMPTY_FRIEND_REQUESTS: readonly InboxFriendRequest[] = Object.freeze([])
-const EMPTY_MENTIONS: readonly Mention[] = Object.freeze([])
const EMPTY_MARKED: readonly Marked[] = Object.freeze([])
type ProjectedUnreadChild = UnreadServer["channels"][number]["children"][number] & {
@@ -186,148 +186,126 @@ export const inboxUnreadsProjectedQueryFn = (
}
}
-export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
- friendRequests: InboxFriendRequest[]
- servers: UnreadServer[]
- dms: UnreadDm[]
- pendingChannelIds: string[]
- hasProjectedUnread: boolean
- hasOutstandingFriendRequest: boolean
-} {
- const queryClient = useQueryClient()
- const unreadProjection = useMemo(
- () => getActiveAccountUnreadProjection(queryClient),
- [queryClient],
- )
- const unreadVersion = useSyncExternalStore(
- unreadProjection.subscribe,
- unreadProjection.getSnapshot,
- unreadProjection.getSnapshot,
- )
- const reservationTarget = useInboxProjectionTarget(queryClient)
- const channelExclusion = useMemo(
- () => reservedUnreadExclusion(reservationTarget, "channels"),
- [reservationTarget],
- )
- const dmExclusion = useMemo(
- () => reservedUnreadExclusion(reservationTarget, "dms"),
- [reservationTarget],
- )
- const queryFn = useMemo(
- () => inboxUnreadsProjectedQueryFn(queryClient, unreadProjection),
- [queryClient, unreadProjection],
- )
- const query = useQuery({
- queryKey: communityKeys.inboxUnreads(),
- queryFn,
- placeholderData: keepPreviousData,
- staleTime: Infinity,
- refetchOnReconnect: true,
- })
- useEffect(() => {
- if (!query.data) return
- const sources = inboxUnreadSources(query.data)
- unreadProjection.mergeSources("inbox-unreads", sources.channels, "channels")
- unreadProjection.mergeSources("inbox-unreads", sources.dms, "dms")
- unreadProjection.recordLegacySnapshot(query.data, [
- ...query.data.servers.flatMap((server) => server.channels.flatMap((channel) => [
- ...(channel.lastUnreadSeq === undefined && channel.hasDirectUnread !== false
- ? [{
- family: "inbox-unreads" as const,
- channelId: channel.channelId,
- serverId: server.serverId,
- }]
- : []),
- ...channel.children.flatMap((child) => child.lastUnreadSeq === undefined
- ? [{
- family: "inbox-unreads" as const,
- channelId: child.channelId,
- serverId: server.serverId,
- railChannelId: channel.channelId,
- }]
- : []),
- ])),
- ...query.data.dms.flatMap((dm) => dm.lastUnreadSeq === undefined
- ? [{ family: "inbox-unreads" as const, channelId: dm.channelId }]
- : []),
- ])
- }, [query.data, unreadProjection])
+export function useInboxUnreads() {
+ const query = useAccountAttentionProjection()
+ const channelsById = useCanonicalChannelsById()
+ const serversById = useCanonicalServersById()
+ const profilesById = useCanonicalProfilesByUserId()
+ const dmProjection = useDmProjection()
const projected = useMemo(() => {
- void unreadVersion
- const rawServers = query.data?.servers ?? (EMPTY_UNREADS as UnreadServer[])
- let serversChanged = false
- const servers = rawServers.flatMap((server) => {
- let channelsChanged = false
- const channels = server.channels.flatMap((channel) => {
- const children = channel.children.filter((child) => selectUnreadPresentation({
- accountUnread: unreadProjection.projectUnread(
- "inbox-unreads",
- child.channelId,
- true,
- child.lastUnreadSeq,
- "channels",
- channelExclusion,
- ),
- }).effectiveUnread)
- const direct = channel.hasDirectUnread !== false && selectUnreadPresentation({
- accountUnread: unreadProjection.projectUnread(
- "inbox-unreads",
- channel.channelId,
- true,
- channel.lastUnreadSeq,
- "channels",
- channelExclusion,
- ),
- }).effectiveUnread
- if (!direct && children.length === 0) {
- channelsChanged = true
- return []
+ const pendingChannelIds: string[] = []
+ const dmById = new Map((dmProjection ?? []).map((dm) => [dm.id, dm]))
+ const dms: UnreadDm[] = []
+ const grouped = new Map<string, Map<string, ProjectedUnreadChannel>>()
+ for (const scope of query.scopes) {
+ if (!scope.ordinaryUnread && scope.attentionCount <= 0) continue
+ const channel = channelsById.get(scope.channelId)
+ if (!channel) {
+ pendingChannelIds.push(scope.channelId)
+ continue
+ }
+ if (!scope.serverId) {
+ const dm = dmById.get(scope.channelId)
+ if (!dm) {
+ pendingChannelIds.push(scope.channelId)
+ continue
+ }
+ dms.push({
+ channelId: dm.id,
+ otherUserId: dm.userId,
+ otherUserName: dm.name,
+ otherUserDiscriminator: dm.discriminator,
+ otherUserAvatar: dm.avatar,
+ otherUserAvatarVersion: dm.avatarVersion,
+ lastMessageAt: channel.lastMessageAt ?? "",
+ lastUnreadSeq: scope.lastUnreadSeq,
+ })
+ continue
+ }
+ const serverChannels = grouped.get(scope.serverId) ?? new Map<string, ProjectedUnreadChannel>()
+ grouped.set(scope.serverId, serverChannels)
+ if (scope.parentChannelId) {
+ const parent = channelsById.get(scope.parentChannelId)
+ if (!parent) {
+ pendingChannelIds.push(scope.channelId)
+ continue
}
- const childrenChanged = children.length !== channel.children.length
- const directChanged = direct !== (channel.hasDirectUnread !== false)
- if (!childrenChanged && !directChanged) return [channel]
- channelsChanged = true
- return [{ ...channel, hasDirectUnread: direct, children }]
+ const parentRow = serverChannels.get(parent.id) ?? {
+ channelId: parent.id,
+ channelName: parent.name,
+ type: parent.type === "forum" ? "forum" : "text",
+ lastMessageAt: parent.lastMessageAt ?? "",
+ mentionCount: 0,
+ hasDirectUnread: false,
+ children: [],
+ }
+ parentRow.children.push({
+ channelId: channel.id,
+ channelName: channel.name,
+ type: "thread",
+ lastMessageAt: channel.lastMessageAt ?? "",
+ lastUnreadSeq: scope.lastUnreadSeq,
+ lastAttentionSeq: scope.lastAttentionSeq,
+ mentionCount: scope.attentionCount,
+ parentChannelId: parent.id,
+ ...(channel.parentMessageId ? { openerMessageId: channel.parentMessageId } : {}),
+ })
+ serverChannels.set(parent.id, parentRow)
+ continue
+ }
+ serverChannels.set(channel.id, {
+ channelId: channel.id,
+ channelName: channel.name,
+ type: channel.type === "forum" ? "forum" : "text",
+ lastMessageAt: channel.lastMessageAt ?? "",
+ lastUnreadSeq: scope.lastUnreadSeq,
+ lastAttentionSeq: scope.lastAttentionSeq,
+ mentionCount: scope.attentionCount,
+ hasDirectUnread: scope.ordinaryUnread,
+ children: serverChannels.get(channel.id)?.children ?? [],
})
- if (channels.length === 0) {
- serversChanged = true
+ }
+
+ const servers: UnreadServer[] = [...grouped].flatMap(([serverId, rows]) => {
+ const server = serversById.get(serverId)
+ if (!server) {
+ pendingChannelIds.push(...[...rows.values()].map((row) => row.channelId))
return []
}
- if (!channelsChanged) return [server]
- serversChanged = true
- return [{ ...server, channels }]
+ return [{
+ serverId,
+ serverName: server.name,
+ channels: [...rows.values()].sort((a, b) => b.lastMessageAt.localeCompare(a.lastMessageAt)),
+ }]
})
- const rawDms = query.data?.dms ?? (EMPTY_DMS as UnreadDm[])
- const dms = rawDms.filter((dm) => selectUnreadPresentation({
- accountUnread: unreadProjection.projectUnread(
- "inbox-unreads",
- dm.channelId,
- true,
- dm.lastUnreadSeq,
- "dms",
- dmExclusion,
- ),
- }).effectiveUnread)
- return {
- servers: serversChanged ? servers : rawServers,
- dms: dms.length === rawDms.length ? rawDms : dms,
- }
- }, [channelExclusion, dmExclusion, query.data, unreadProjection, unreadVersion])
+ const friendRequests: InboxFriendRequest[] = query.items
+ .filter((item) => item.kind === "friend_request")
+ .map((item) => {
+ const profile = profilesById.get(item.actorUserId)
+ return {
+ id: item.sourceId,
+ userId: item.actorUserId,
+ name: profile?.name ?? "Deleted user",
+ avatar: profile?.avatar ?? "",
+ avatarVersion: profile?.avatarVersion ?? null,
+ createdAt: item.createdAt,
+ pendingIdentity: !profile,
+ }
+ })
+ return { servers, dms, friendRequests, pendingChannelIds }
+ }, [channelsById, dmProjection, profilesById, query.items, query.scopes, serversById])
return {
...query,
- friendRequests: query.data?.friendRequests ?? (EMPTY_FRIEND_REQUESTS as InboxFriendRequest[]),
- servers: projected.servers ?? (EMPTY_UNREADS as UnreadServer[]),
- dms: projected.dms ?? (EMPTY_DMS as UnreadDm[]),
- pendingChannelIds: [
- ...unreadProjection.pendingChannelIds("inbox-unreads", "channels", channelExclusion),
- ...unreadProjection.pendingChannelIds("inbox-unreads", "dms", dmExclusion),
- ],
- hasProjectedUnread:
- projected.servers.length > 0
+ friendRequests: projected.friendRequests,
+ servers: projected.servers,
+ dms: projected.dms,
+ pendingChannelIds: projected.pendingChannelIds,
+ isProjectionPending: projected.pendingChannelIds.length > 0,
+ hasProjectedUnread: projected.servers.length > 0
|| projected.dms.length > 0
- || unreadProjection.hasPending("inbox-unreads", "channels", channelExclusion)
- || unreadProjection.hasPending("inbox-unreads", "dms", dmExclusion),
- hasOutstandingFriendRequest: (query.data?.friendRequests?.length ?? 0) > 0,
+ || projected.pendingChannelIds.length > 0,
+ hasOutstandingFriendRequest: projected.friendRequests.length > 0,
+ exactAttentionCount: query.scopes.reduce((total, scope) => total + scope.attentionCount, 0),
}
}
@@ -337,10 +315,11 @@ export type MentionsResponse = {
truncated?: boolean
}
-const inboxMentionsTransportFn = () =>
+const inboxMentionsTransportFn = (signal?: AbortSignal) =>
apiFetchProfiles<MentionsResponse & { stale?: boolean }>(
"/api/community/users/me/inbox/mentions",
(data) => messageProfilePatches(data.mentions.map((mention) => mention.m)),
+ signal ? { signal } : undefined,
)
export const inboxMentionsQueryFn = async () => (
@@ -365,121 +344,114 @@ function inboxMentionSources(data: MentionsResponse): AccountUnreadSource[] {
export const inboxMentionsProjectedQueryFn = (
projection: AccountUnreadProjection,
-) => async () => {
+ queryClient?: QueryClient,
+) => async ({ signal }: { signal?: AbortSignal } = {}) => {
const token = projection.beginSnapshot("inbox-mentions", "mentions")
+ const publicationToken = queryClient
+ ? captureCommunityLiveSnapshotToken(queryClient)
+ : null
try {
- const data = await inboxMentionsTransportFn()
+ const data = throwIfStale(await inboxMentionsTransportFn(signal))
+ if (queryClient && publicationToken) {
+ publishCommunityEmbeddedMessages(queryClient, {
+ entries: data.mentions.flatMap((mention) => mention.channelId
+ ? [{ channelId: mention.channelId, message: mention.m }]
+ : []),
+ proof: { token: publicationToken, signal },
+ })
+ }
projection.absorbSnapshot(token, inboxMentionSources(data), {
truncated: data.truncated ?? true,
stale: data.stale,
})
- return throwIfStale(data)
+ return data
} catch (error) {
projection.cancelSnapshot(token)
throw error
}
}
-export function useInboxMentions(): UseQueryResult<MentionsResponse> & {
- mentions: Mention[]
- pendingChannelIds: string[]
- hasProjectedMention: boolean
-} {
- const queryClient = useQueryClient()
- const unreadProjection = useMemo(
- () => getActiveAccountUnreadProjection(queryClient),
- [queryClient],
- )
- const unreadVersion = useSyncExternalStore(
- unreadProjection.subscribe,
- unreadProjection.getSnapshot,
- unreadProjection.getSnapshot,
- )
- const reservationTarget = useInboxProjectionTarget(queryClient)
- const mentionExclusion = useMemo(
- () => reservedUnreadExclusion(reservationTarget, "channels"),
- [reservationTarget],
- )
- const queryFn = useMemo(
- () => inboxMentionsProjectedQueryFn(unreadProjection),
- [unreadProjection],
- )
- const query = useQuery({
- queryKey: communityKeys.inboxMentions(),
- queryFn,
- placeholderData: keepPreviousData,
- staleTime: Infinity,
- refetchOnReconnect: true,
- })
- useEffect(() => {
- if (!query.data) return
- unreadProjection.mergeSources(
- "inbox-mentions",
- inboxMentionSources(query.data),
- "mentions",
- )
- unreadProjection.recordLegacySnapshot(
- query.data,
- query.data.mentions.flatMap((mention) => (
- mention.channelId && !mention.m.seq
- ? [{
- family: "inbox-mentions" as const,
- channelId: mention.channelId,
- serverId: mention.serverId,
- isMention: true,
- }]
- : []
- )),
- )
- }, [query.data, unreadProjection])
- const mentions = useMemo(() => {
- void unreadVersion
- const raw = query.data?.mentions ?? (EMPTY_MENTIONS as Mention[])
- const projected = raw.filter((mention) => (
- !mention.channelId
- || selectUnreadPresentation({
- accountUnread: unreadProjection.projectUnread(
- "inbox-mentions",
- mention.channelId,
- true,
- mention.m.seq,
- "mentions",
- mentionExclusion,
- true,
- mention.id,
- ),
- reserved: isInboxTargetReserved(
- reservationTarget,
- inboxMentionRowTarget(mention),
- ),
- }).effectiveUnread
- ))
- return projected.length === raw.length ? raw : projected
- }, [mentionExclusion, query.data, reservationTarget, unreadProjection, unreadVersion])
+export function useInboxMentions() {
+ const canonicalMessages = useCanonicalMessagesById()
+ const channelsById = useCanonicalChannelsById()
+ const serversById = useCanonicalServersById()
+ const query = useAccountAttentionProjection()
+ const projected = useMemo(() => {
+ const pendingChannelIds: string[] = []
+ const scopesById = new Map(query.scopes.map((scope) => [scope.scopeId, scope]))
+ const mentions = query.items.flatMap((item): Mention[] => {
+ if (item.kind === "friend_request" || !item.scopeId || !item.messageId) return []
+ if (item.kind === "pending") {
+ pendingChannelIds.push(item.scopeId)
+ return []
+ }
+ const scope = scopesById.get(item.scopeId)
+ const message = canonicalMessages?.get(item.messageId)
+ const channel = scope ? channelsById.get(scope.channelId) : undefined
+ if (!scope || !message || !channel) {
+ pendingChannelIds.push(scope?.channelId ?? item.scopeId)
+ return [{
+ id: item.sourceId,
+ kind: item.kind,
+ server: "",
+ ...(scope?.serverId ? { serverId: scope.serverId } : {}),
+ channel: "",
+ channelId: scope?.channelId ?? item.scopeId,
+ pending: true,
+ m: {
+ id: item.messageId,
+ type: "chat",
+ authorId: item.actorUserId,
+ },
+ }]
+ }
+ return [{
+ id: item.sourceId,
+ kind: item.kind,
+ server: scope.serverId
+ ? serversById.get(scope.serverId)?.name ?? "Server unavailable"
+ : "Conversation unavailable",
+ ...(scope.serverId ? { serverId: scope.serverId } : {}),
+ channel: channel.name || "Conversation unavailable",
+ channelId: channel.id,
+ m: message,
+ }]
+ })
+ return { mentions, pendingChannelIds }
+ }, [canonicalMessages, channelsById, query.items, query.scopes, serversById])
return {
...query,
- mentions,
- pendingChannelIds: unreadProjection.pendingChannelIds("inbox-mentions", "mentions", mentionExclusion),
- hasProjectedMention:
- mentions.length > 0
- || unreadProjection.hasPending(
- "inbox-mentions",
- "mentions",
- mentionExclusion,
- ),
+ mentions: projected.mentions,
+ pendingChannelIds: projected.pendingChannelIds,
+ isProjectionPending: projected.pendingChannelIds.length > 0,
+ hasProjectedMention: projected.mentions.length > 0 || projected.pendingChannelIds.length > 0,
}
}
export type MarkedResponse = { marked: Marked[] }
-const inboxMarkedQueryFn = () =>
- apiFetchProfiles<MarkedResponse & { stale?: boolean }>(
- "/api/community/users/me/marks",
- (data) => {
- throwIfStale(data)
- return messageProfilePatches(data.marked.map((marked) => marked.m))
- },
- )
+const inboxMarkedQueryFn = (queryClient: QueryClient) =>
+ async ({ signal }: { signal?: AbortSignal } = {}) => {
+ const publicationToken = captureCommunityLiveSnapshotToken(queryClient)
+ const data = await apiFetchProfiles<MarkedResponse & { stale?: boolean }>(
+ "/api/community/users/me/marks",
+ (response) => {
+ throwIfStale(response)
+ return messageProfilePatches(response.marked.map((marked) => marked.m))
+ },
+ signal ? { signal } : undefined,
+ )
+ if (publicationToken) {
+ publishCommunityEmbeddedMessages(queryClient, {
+ entries: data.marked.map((marked) => ({
+ channelId: marked.channelId,
+ message: marked.m,
+ })),
+ proof: { token: publicationToken, signal },
+ })
+ }
+ return throwIfStale(data)
+ }
/**
* The Marked feed is lazy — unlike unreads/mentions (which the shell reads
@@ -491,15 +463,38 @@ const inboxMarkedQueryFn = () =>
export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedResponse> & {
marked: Marked[]
} {
+ const canonicalMessages = useCanonicalMessagesById()
+ const queryClient = useQueryClient()
+ const unreadProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
const query = useQuery({
queryKey: communityKeys.inboxMarked(),
- queryFn: inboxMarkedQueryFn,
+ queryFn: inboxMarkedQueryFn(queryClient),
placeholderData: keepPreviousData,
enabled,
})
+ const marked = useMemo(() => {
+ void unreadVersion
+ const source = query.data?.marked ?? (EMPTY_MARKED as Marked[])
+ return source.flatMap((marked) => {
+ if (!unreadProjection.allowsAccess({
+ channelId: marked.channelId,
+ serverId: marked.serverId,
+ })) return []
+ const message = materializeCanonicalMessage(marked.m, canonicalMessages)
+ return message ? [{ ...marked, m: message }] : []
+ })
+ }, [canonicalMessages, query.data?.marked, unreadProjection, unreadVersion])
return {
...query,
- marked: query.data?.marked ?? (EMPTY_MARKED as Marked[]),
+ marked,
}
}
diff --git a/src/web/src/hooks/community/use-invitable-friends.test.ts b/src/web/src/hooks/community/use-invitable-friends.test.ts
index e71842083..85c973a8a 100644
--- a/src/web/src/hooks/community/use-invitable-friends.test.ts
+++ b/src/web/src/hooks/community/use-invitable-friends.test.ts
@@ -1,5 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { useCommunityWsStore } from "@/stores/community/ws"
const apiFetchMock = vi.fn()
const fetchAllServerMembersMock = vi.fn()
@@ -13,8 +12,6 @@ vi.mock("./fetch-all-server-members", () => ({
beforeEach(() => {
apiFetchMock.mockReset()
fetchAllServerMembersMock.mockReset()
- useCommunityWsStore.getState().reset()
- useCommunityWsStore.getState().activateProfileAccount("viewer")
})
describe("invitableFriendsQueryFn", () => {
@@ -45,9 +42,5 @@ describe("invitableFriendsQueryFn", () => {
const result = await invitableFriendsQueryFn("server_1")
expect(result.friends).toEqual([identified, legacy])
- expect(useCommunityWsStore.getState().profilesByUserId.get("friend_1")).toMatchObject({
- name: "Alice",
- avatarVersion: 2,
- })
})
})
diff --git a/src/web/src/hooks/community/use-message.dom.test.ts b/src/web/src/hooks/community/use-message.dom.test.ts
new file mode 100644
index 000000000..30e69d173
--- /dev/null
+++ b/src/web/src/hooks/community/use-message.dom.test.ts
@@ -0,0 +1,215 @@
+import { createElement, type PropsWithChildren } from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { act, renderHook } from "@/test/react-dom-harness"
+import { communityKeys } from "@/lib/query-keys"
+import { useMessage } from "./use-message"
+import type { Msg } from "@/lib/community/models/message"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
+import { takeMessageIdsForAccessScope } from "@/lib/community-db/message-access-scope"
+
+const apiFetchMock = vi.fn(() => new Promise(() => {}))
+const canonicalMessagesMock = vi.hoisted(() => vi.fn<() => ReadonlyMap<string, Msg> | undefined>(
+ () => undefined,
+))
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useCanonicalMessagesById: () => canonicalMessagesMock(),
+ useOptionalCommunityDbRegistry: () => canonicalMessagesMock() === undefined ? null : {},
+}))
+
+beforeEach(() => {
+ apiFetchMock.mockClear()
+ canonicalMessagesMock.mockReset()
+ canonicalMessagesMock.mockReturnValue(undefined)
+})
+
+function wrapperFor(queryClient: QueryClient) {
+ return function QueryWrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client: queryClient }, children)
+ }
+}
+
+describe("useMessage cache-first placeholder", () => {
+ it("returns a cached list message while the canonical message query is pending", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.channelMessages("channel-1"), {
+ pages: [{
+ messages: [{
+ id: "m_1",
+ type: "chat",
+ authorId: "u_1",
+ authorName: "Alice",
+ content: "cached opener",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ }],
+ hasMore: false,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+
+ const rendered = renderHook(() => useMessage("m_1", {
+ channelId: "channel-1",
+ serverId: "server-1",
+ }), {
+ wrapper: wrapperFor(queryClient),
+ })
+
+ expect(rendered.result.current.message).toMatchObject({
+ id: "m_1",
+ authorId: "u_1",
+ content: "cached opener",
+ })
+ expect(rendered.result.current.isPlaceholderData).toBe(true)
+ })
+
+ it("keeps a missing id disabled and returns no message", () => {
+ const queryClient = new QueryClient()
+ const rendered = renderHook(() => useMessage(null), {
+ wrapper: wrapperFor(queryClient),
+ })
+
+ expect(rendered.result.current.message).toBeNull()
+ expect(rendered.result.current.fetchStatus).toBe("idle")
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+
+ it("uses canonical identity exclusively when the DB provider is active", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.message("m_1"), {
+ id: "m_1",
+ type: "chat",
+ authorId: "raw",
+ authorName: "Raw",
+ authorAvatar: "R",
+ authorAvatarVersion: 0,
+ content: "raw query",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ })
+ canonicalMessagesMock.mockReturnValue(new Map([[
+ "m_1",
+ {
+ id: "m_1",
+ type: "chat",
+ authorId: "canonical",
+ authorName: "Canonical",
+ authorAvatar: "C",
+ authorAvatarVersion: 0,
+ content: "canonical row",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ },
+ ]]))
+ const rendered = renderHook(() => useMessage("m_1", {
+ channelId: "channel-1",
+ serverId: "server-1",
+ }), {
+ wrapper: wrapperFor(queryClient),
+ })
+
+ expect(rendered.result.current.message).toMatchObject({
+ authorId: "canonical",
+ content: "canonical row",
+ })
+ })
+
+ it("does not fall back to a raw single-message response in an active partial registry", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.message("m_1"), {
+ id: "m_1",
+ type: "chat",
+ authorId: "raw",
+ authorName: "Raw",
+ authorAvatar: "R",
+ authorAvatarVersion: 0,
+ content: "raw query",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ attachments: [{
+ kind: "file",
+ name: "raw.txt",
+ url: "/raw.txt",
+ size: "1 KB",
+ }],
+ })
+ canonicalMessagesMock.mockReturnValue(new Map())
+ const rendered = renderHook(() => useMessage("m_1", {
+ channelId: "channel-1",
+ serverId: "server-1",
+ }), {
+ wrapper: wrapperFor(queryClient),
+ })
+
+ expect(rendered.result.current.message).toBeNull()
+ })
+
+ it("keeps the access index empty while fenced and restores it after rollback or grant", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.message("m_1"), {
+ id: "m_1",
+ type: "chat",
+ authorId: "raw",
+ authorName: "Raw",
+ authorAvatar: "R",
+ authorAvatarVersion: 0,
+ content: "must not revive",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ })
+ canonicalMessagesMock.mockReturnValue(new Map())
+ const rendered = renderHook(() => useMessage("m_1", {
+ channelId: "channel-1",
+ serverId: "server-1",
+ }), {
+ wrapper: wrapperFor(queryClient),
+ })
+ expect(rendered.result.current.message).toBeNull()
+ expect(takeMessageIdsForAccessScope(
+ queryClient,
+ new Set(["channel-1"]),
+ null,
+ )).toEqual(["m_1"])
+
+ const projection = getActiveAccountUnreadProjection(queryClient)
+ let retirement!: ReturnType<typeof projection.beginScopeRetirement>
+ act(() => {
+ retirement = projection.beginScopeRetirement({ kind: "channel", channelId: "channel-1" })
+ })
+ expect(rendered.result.current.message).toBeNull()
+ expect(rendered.result.current.fetchStatus).toBe("idle")
+ expect(takeMessageIdsForAccessScope(
+ queryClient,
+ new Set(["channel-1"]),
+ null,
+ )).toEqual([])
+
+ act(() => projection.rollbackScopeRetirement(retirement))
+ expect(rendered.result.current.message).toBeNull()
+ expect(takeMessageIdsForAccessScope(
+ queryClient,
+ new Set(["channel-1"]),
+ null,
+ )).toEqual(["m_1"])
+
+ act(() => projection.retireAccessScope({ kind: "channel", channelId: "channel-1" }))
+ expect(rendered.result.current.message).toBeNull()
+ expect(takeMessageIdsForAccessScope(
+ queryClient,
+ new Set(["channel-1"]),
+ null,
+ )).toEqual([])
+
+ act(() => {
+ projection.grantAccessScope({ kind: "channel", channelId: "channel-1" })
+ projection.confirmAccessScopes(
+ [{ kind: "channel", channelId: "channel-1" }],
+ projection.beginAccessConfirmation(),
+ )
+ })
+ expect(rendered.result.current.message).toBeNull()
+ expect(takeMessageIdsForAccessScope(
+ queryClient,
+ new Set(["channel-1"]),
+ null,
+ )).toEqual(["m_1"])
+ })
+})
diff --git a/src/web/src/hooks/community/use-message.test.ts b/src/web/src/hooks/community/use-message.test.ts
index 624be3dae..0084f7988 100644
--- a/src/web/src/hooks/community/use-message.test.ts
+++ b/src/web/src/hooks/community/use-message.test.ts
@@ -3,12 +3,32 @@ import { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
const apiFetchMock = vi.fn()
+const {
+ liveSnapshotToken,
+ captureCommunityLiveSnapshotTokenMock,
+ publishCommunityMessagesMock,
+} = vi.hoisted(() => {
+ const token = { canonicalRevision: 0 }
+ return {
+ liveSnapshotToken: token,
+ captureCommunityLiveSnapshotTokenMock: vi.fn(() => token),
+ publishCommunityMessagesMock: vi.fn(),
+ }
+})
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
+vi.mock("@/lib/community-db/sync", () => ({
+ captureCommunityLiveSnapshotToken: (...args: unknown[]) => (
+ captureCommunityLiveSnapshotTokenMock(...args)
+ ),
+ publishCommunityMessages: (...args: unknown[]) => publishCommunityMessagesMock(...args),
+}))
beforeEach(() => {
apiFetchMock.mockReset()
+ captureCommunityLiveSnapshotTokenMock.mockClear()
+ publishCommunityMessagesMock.mockReset()
})
describe("useMessage / messageQueryFn", () => {
@@ -44,6 +64,71 @@ describe("useMessage / messageQueryFn", () => {
expect(qc.getQueryData(key)).toBeDefined()
})
+ it("publishes an exact opener through the channel id carried by its response", async () => {
+ const payload = {
+ id: "m_1",
+ channelId: "archived-post-1",
+ type: "chat" as const,
+ authorId: "u_1",
+ authorName: "Alice",
+ authorAvatar: "",
+ authorAvatarVersion: 0,
+ content: "archived opener",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ }
+ apiFetchMock.mockResolvedValueOnce(payload)
+ const { messageQueryFn } = await import("./use-message")
+ const queryClient = new QueryClient()
+
+ await messageQueryFn("m_1", queryClient)()
+
+ expect(publishCommunityMessagesMock).toHaveBeenCalledWith(queryClient, {
+ channelId: "archived-post-1",
+ messages: [payload],
+ proof: { token: liveSnapshotToken, signal: undefined },
+ })
+ })
+
+ it("derives an opener placeholder from a persisted message window", async () => {
+ const qc = new QueryClient()
+ qc.setQueryData(communityKeys.members("server-1"), {
+ pages: [{ members: [{ id: "u_1" }] }],
+ pageParams: [null],
+ })
+ qc.setQueryData(communityKeys.channelMessages("channel-1"), {
+ pages: [{
+ messages: [{
+ id: "m_1",
+ type: "chat",
+ authorId: "u_1",
+ authorName: "Alice",
+ content: "cached opener",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ replyTo: { id: "m_0", authorName: "Bob", text: "parent" },
+ attachments: [{ kind: "file", name: "notes.txt", url: "/notes.txt", size: "1 KB" }],
+ embeds: [{ title: "Reference" }],
+ reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_1"] }],
+ }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+ const { findCachedMessage } = await import("./use-message")
+
+ expect(findCachedMessage(qc, "m_1")).toMatchObject({
+ id: "m_1",
+ authorId: "u_1",
+ authorName: "Alice",
+ content: "cached opener",
+ replyTo: { id: "m_0", authorName: "Bob", text: "parent" },
+ attachments: [{ kind: "file", name: "notes.txt", url: "/notes.txt", size: "1 KB" }],
+ embeds: [{ title: "Reference" }],
+ reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_1"] }],
+ })
+ expect(findCachedMessage(qc, "missing")).toBeUndefined()
+ })
+
// ── Invalidation contract guard ──────────────────────────────────────────
// The whole point of moving ThreadOpener onto useQuery: an edit/reaction on
// the parent message can invalidate `communityKeys.message(id)` and the
diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.ts
index 9b29509ff..8e738d363 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -1,9 +1,29 @@
"use client"
-import { useQuery, type UseQueryResult } from "@tanstack/react-query"
+import { useEffect, useMemo, useSyncExternalStore } from "react"
+import {
+ useQuery,
+ useQueryClient,
+ type QueryClient,
+ type QueryFunctionContext,
+ type UseQueryResult,
+} from "@tanstack/react-query"
import { apiFetchProfiles, messageProfilePatches } from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
-import type { Msg } from "@/lib/community/models/message"
+import type { MessagesPage, Msg } from "@/lib/community/models/message"
+import {
+ useCanonicalMessagesById,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
+import {
+ rememberMessageAccessScope,
+ type MessageAccessScope,
+} from "@/lib/community-db/message-access-scope"
+import { getActiveAccountUnreadProjection } from "./account-unread-projection"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityMessages,
+} from "@/lib/community-db/sync"
/**
* Fetches a single hydrated message by id — the payload shape returned by
@@ -20,6 +40,10 @@ import type { Msg } from "@/lib/community/models/message"
*/
export type OpenerPayload = {
id: string
+ // Exact-message responses carry their owning surface so a hard-refresh can
+ // publish an archived opener even when the route model has no parent hint.
+ // Persisted list-window placeholders predate that response field.
+ channelId?: string
authorId: string
authorName: string
authorAvatar: string
@@ -35,28 +59,104 @@ export type OpenerPayload = {
reactions?: Msg["reactions"]
}
-export const messageQueryFn = (messageId: string) => () =>
- apiFetchProfiles<OpenerPayload>(
+export const messageQueryFn = (
+ messageId: string,
+ queryClient?: QueryClient,
+ channelId?: string,
+) => async (context: QueryFunctionContext = {} as QueryFunctionContext) => {
+ const token = queryClient ? captureCommunityLiveSnapshotToken(queryClient) : null
+ const message = await apiFetchProfiles<OpenerPayload>(
`/api/community/messages/${messageId}`,
(message) => messageProfilePatches([message]),
+ context.signal ? { signal: context.signal } : undefined,
)
+ const publishChannelId = message.channelId ?? channelId
+ if (queryClient && publishChannelId && token) {
+ publishCommunityMessages(queryClient, {
+ channelId: publishChannelId,
+ messages: [message],
+ proof: { token, signal: context.signal },
+ })
+ }
+ return message
+}
+
+export function findCachedMessage(
+ queryClient: QueryClient,
+ messageId: string,
+): OpenerPayload | undefined {
+ for (const [, data] of queryClient.getQueriesData<{ pages?: MessagesPage[] }>({
+ queryKey: communityKeys.all,
+ })) {
+ if (!Array.isArray(data?.pages)) continue
+ for (const page of data.pages) {
+ if (!Array.isArray(page.messages)) continue
+ const message = page.messages.find((candidate) => candidate.id === messageId)
+ if (!message?.authorId || !message.createdAt) continue
+ return {
+ id: message.id,
+ authorId: message.authorId,
+ authorName: message.authorName ?? "Deleted user",
+ authorAvatar: message.authorAvatar ?? "",
+ authorAvatarVersion: message.authorAvatarVersion ?? 0,
+ content: message.content ?? "",
+ type: message.type,
+ createdAt: message.createdAt,
+ ...(message.replyTo ? { replyTo: message.replyTo } : {}),
+ ...(message.attachments ? { attachments: message.attachments } : {}),
+ ...(message.embeds ? { embeds: message.embeds } : {}),
+ ...(message.reactions ? { reactions: message.reactions } : {}),
+ }
+ }
+ }
+ return undefined
+}
export function useMessage(
messageId: string | null | undefined,
+ accessScope?: MessageAccessScope,
): UseQueryResult<OpenerPayload> & { message: OpenerPayload | null } {
- const enabled = !!messageId
+ const registry = useOptionalCommunityDbRegistry()
+ const canonicalMessages = useCanonicalMessagesById()
+ const queryClient = useQueryClient()
+ const accessProjection = useMemo(
+ () => getActiveAccountUnreadProjection(queryClient),
+ [queryClient],
+ )
+ const accessVersion = useSyncExternalStore(
+ accessProjection.subscribe,
+ accessProjection.getSnapshot,
+ accessProjection.getSnapshot,
+ )
+ void accessVersion
+ const accessAllowed = !accessScope || accessProjection.allowsAccess(accessScope)
+ const enabled = !!messageId && accessAllowed
+ useEffect(() => {
+ if (!messageId || !accessScope || !accessAllowed) return
+ rememberMessageAccessScope(queryClient, messageId, accessScope)
+ }, [accessAllowed, accessScope, messageId, queryClient])
+ const placeholderData = useMemo(
+ () => messageId && accessAllowed ? findCachedMessage(queryClient, messageId) : undefined,
+ [accessAllowed, messageId, queryClient],
+ )
const query = useQuery({
queryKey: enabled ? communityKeys.message(messageId!) : communityKeys.message("__none__"),
queryFn: enabled
- ? messageQueryFn(messageId!)
+ ? messageQueryFn(messageId!, queryClient, accessScope?.channelId)
: (() => Promise.reject(new Error("disabled"))),
enabled,
+ placeholderData,
// Quick tab-switches shouldn't hammer the endpoint; 30s window is plenty
// for the "opener stays live via mutation invalidation" contract.
staleTime: 30_000,
})
+ const canonical = messageId ? canonicalMessages?.get(messageId) : undefined
return {
...query,
- message: query.data ?? null,
+ message: accessAllowed
+ ? registry
+ ? (canonical as OpenerPayload | undefined) ?? null
+ : query.data ?? null
+ : null,
}
}
diff --git a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.ts b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.ts
index 7e1c8b760..b6b1aff35 100644
--- a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.ts
@@ -229,6 +229,29 @@ function SwitchingLayoutPaginationCapture({ channelId, queueOlder, onRender }: {
return null
}
+function ConfigurableChannelCapture({
+ channelId,
+ revalidateOnMount,
+ onRender,
+}: {
+ channelId: string
+ revalidateOnMount: boolean
+ onRender: (snapshot: Snapshot, fetchOlder: () => void) => void
+}) {
+ const result = useMessages(channelId, {
+ serverId: "server_1",
+ lastReadMessageId: `m_anchor_${channelId}`,
+ revalidateOnMount,
+ })
+ onRender({
+ anchorReconciled: result.anchorReconciled,
+ hasMoreNewer: result.hasMoreNewer,
+ ids: result.messages.map((message) => message.id),
+ isFetching: result.isFetching,
+ }, result.fetchOlder)
+ return null
+}
+
function IndependentChannelCapture({ lastReadMessageId, onRender }: {
lastReadMessageId: string | null | undefined
onRender: (snapshot: Snapshot) => void
@@ -292,6 +315,47 @@ beforeEach(() => {
})
describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
+ it("reuses one cold initial anchor request across a StrictMode-style remount", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const transport = deferred<MessagesPage>()
+ apiFetchMock.mockImplementation((_url: string, init?: { signal?: AbortSignal }) => (
+ new Promise<MessagesPage>((resolve, reject) => {
+ const abort = () => reject(new DOMException("Aborted", "AbortError"))
+ if (init?.signal?.aborted) abort()
+ else init?.signal?.addEventListener("abort", abort, { once: true })
+ void transport.promise.then(resolve, reject)
+ })
+ ))
+ const snapshots: Snapshot[] = []
+
+ const capture = React.createElement(ChannelCapture, {
+ lastReadMessageId: "m_anchor",
+ onRender: (snapshot) => { snapshots.push(snapshot) },
+ })
+ const firstMount = renderCapture(
+ queryClient,
+ capture,
+ )
+
+ await waitFor(() => apiFetchMock.mock.calls.length > 0)
+ firstMount.unmount()
+ const remount = renderCapture(queryClient, capture)
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)) })
+ expect(apiFetchMock.mock.calls.filter(([url]) => url.includes("/messages")))
+ .toHaveLength(1)
+
+ transport.resolve({
+ messages: [{ id: "m_anchor", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 1,
+ })
+ await waitFor(() => snapshots.some((snapshot) => snapshot.ids.includes("m_anchor")))
+ expect(queryClient.getQueryData(communityKeys.channelMessages("ch_activation")))
+ .toMatchObject({ pages: [{ messages: [expect.objectContaining({ id: "m_anchor" })] }] })
+ remount.unmount()
+ })
+
it("keeps the real transport installed while the anchor gate is disabled", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
apiFetchMock.mockResolvedValue({
@@ -515,6 +579,232 @@ describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
renderer.unmount()
})
+ it("retries an aborted first activation refresh until a network success receipt", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const queryKey = communityKeys.dmMessages("dm_activation")
+ const cachedPage = {
+ messages: [{ id: "m_anchor", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 1,
+ } satisfies MessagesPage
+ queryClient.setQueryData(queryKey, {
+ pages: [cachedPage],
+ pageParams: [{ mode: "anchor", anchor: "m_anchor" }],
+ })
+ let messageAttempts = 0
+ apiFetchMock.mockImplementation((_url: string, init?: { signal?: AbortSignal }) => {
+ messageAttempts += 1
+ if (messageAttempts > 1) return Promise.resolve(cachedPage)
+ return new Promise<MessagesPage>((_resolve, reject) => {
+ const signal = init?.signal
+ const abort = () => reject(new DOMException("Aborted", "AbortError"))
+ if (signal?.aborted) abort()
+ else signal?.addEventListener("abort", abort, { once: true })
+ })
+ })
+ const snapshots: Snapshot[] = []
+ const renderer = renderCapture(
+ queryClient,
+ React.createElement(RevalidatingDmCapture, {
+ lastReadMessageId: "m_anchor",
+ onRender: (snapshot) => { snapshots.push(snapshot) },
+ }),
+ )
+
+ await waitFor(() => messageAttempts === 1)
+ await act(async () => {
+ await queryClient.cancelQueries({ queryKey, exact: true })
+ })
+ await waitFor(() => messageAttempts === 2)
+
+ expect(apiFetchMock.mock.calls.filter(([url]) => url.includes("/messages")))
+ .toHaveLength(2)
+ expect(snapshots.every((snapshot) => snapshot.ids.includes("m_anchor")))
+ .toBe(true)
+ renderer.unmount()
+ })
+
+ it("does not let a previous view's late success satisfy the current activation", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ for (const channelId of ["ch_a", "ch_b"]) {
+ queryClient.setQueryData(communityKeys.channelMessages(channelId), {
+ pages: [{
+ messages: [{
+ id: `m_anchor_${channelId}`,
+ seq: 1,
+ createdAt: "2026-08-09T00:00:00.000Z",
+ }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 1,
+ }],
+ pageParams: [{ mode: "anchor", anchor: `m_anchor_${channelId}` }],
+ })
+ }
+ const lateA = deferred<MessagesPage>()
+ let bAttempts = 0
+ apiFetchMock.mockImplementation((url: string, init?: { signal?: AbortSignal }) => {
+ if (url.includes("/ch_a/messages")) return lateA.promise
+ bAttempts += 1
+ if (bAttempts > 1) {
+ return Promise.resolve({
+ messages: [{ id: "m_anchor_ch_b", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 1,
+ } satisfies MessagesPage)
+ }
+ return new Promise<MessagesPage>((_resolve, reject) => {
+ const abort = () => reject(new DOMException("Aborted", "AbortError"))
+ if (init?.signal?.aborted) abort()
+ else init?.signal?.addEventListener("abort", abort, { once: true })
+ })
+ })
+ const view = (channelId: string) => React.createElement(ConfigurableChannelCapture, {
+ key: channelId,
+ channelId,
+ revalidateOnMount: true,
+ onRender: () => {},
+ })
+ const renderer = renderCapture(queryClient, view("ch_a"))
+
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ updateCapture(renderer, queryClient, view("ch_b"))
+ await waitFor(() => bAttempts === 1)
+ lateA.resolve({
+ messages: [{ id: "m_anchor_ch_a", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 1,
+ })
+ await act(async () => { await lateA.promise })
+ await act(async () => {
+ await queryClient.cancelQueries({
+ queryKey: communityKeys.channelMessages("ch_b"),
+ exact: true,
+ })
+ })
+ await waitFor(() => bAttempts === 2)
+
+ renderer.unmount()
+ })
+
+ it("does not treat older pagination success as an initial-window receipt", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const queryKey = communityKeys.channelMessages("ch_activation")
+ queryClient.setQueryData(queryKey, {
+ pages: [{
+ messages: [{ id: "m_anchor_ch_activation", seq: 2, createdAt: "2026-08-09T00:00:01.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ olderCursor: "older-cursor",
+ latestSeq: 2,
+ }],
+ pageParams: [{ mode: "anchor", anchor: "m_anchor_ch_activation" }],
+ })
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url.endsWith("?cursor=older-cursor")) {
+ return Promise.resolve({
+ messages: [{ id: "m_old", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 2,
+ } satisfies MessagesPage)
+ }
+ if (url.endsWith("?anchor=m_anchor_ch_activation")) {
+ return Promise.resolve({
+ messages: [{ id: "m_anchor_ch_activation", seq: 2, createdAt: "2026-08-09T00:00:01.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 2,
+ } satisfies MessagesPage)
+ }
+ throw new Error(`unexpected messages URL: ${url}`)
+ })
+ let fetchOlder = () => {}
+ const view = (revalidateOnMount: boolean) => React.createElement(
+ ConfigurableChannelCapture,
+ {
+ channelId: "ch_activation",
+ revalidateOnMount,
+ onRender: (_snapshot: Snapshot, nextFetchOlder: () => void) => {
+ fetchOlder = nextFetchOlder
+ },
+ },
+ )
+ const renderer = renderCapture(queryClient, view(false))
+
+ act(() => fetchOlder())
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ expect(apiFetchMock.mock.calls[0]?.[0]).toContain("cursor=older-cursor")
+ updateCapture(renderer, queryClient, view(true))
+ await waitFor(() => apiFetchMock.mock.calls.length === 2)
+ expect(apiFetchMock.mock.calls[1]?.[0]).toContain(
+ "anchor=m_anchor_ch_activation",
+ )
+
+ renderer.unmount()
+ })
+
+ it("retries when a later page in the activation refetch is aborted", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const queryKey = communityKeys.dmMessages("dm_activation")
+ const anchorPage = {
+ messages: [{ id: "m_anchor", seq: 2, createdAt: "2026-08-09T00:00:01.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ olderCursor: "older-cursor",
+ latestSeq: 2,
+ } satisfies MessagesPage
+ const olderPage = {
+ messages: [{ id: "m_old", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 2,
+ } satisfies MessagesPage
+ queryClient.setQueryData(queryKey, {
+ pages: [anchorPage, olderPage],
+ pageParams: [
+ { mode: "anchor", anchor: "m_anchor" },
+ { mode: "older", cursor: "older-cursor" },
+ ],
+ })
+ let anchorAttempts = 0
+ let olderAttempts = 0
+ apiFetchMock.mockImplementation((url: string, init?: { signal?: AbortSignal }) => {
+ if (url.endsWith("?anchor=m_anchor")) {
+ anchorAttempts += 1
+ return Promise.resolve(anchorPage)
+ }
+ if (url.endsWith("?cursor=older-cursor")) {
+ olderAttempts += 1
+ if (olderAttempts > 1) return Promise.resolve(olderPage)
+ return new Promise<MessagesPage>((_resolve, reject) => {
+ const abort = () => reject(new DOMException("Aborted", "AbortError"))
+ if (init?.signal?.aborted) abort()
+ else init?.signal?.addEventListener("abort", abort, { once: true })
+ })
+ }
+ throw new Error(`unexpected messages URL: ${url}`)
+ })
+ const renderer = renderCapture(
+ queryClient,
+ React.createElement(RevalidatingDmCapture, {
+ lastReadMessageId: "m_anchor",
+ onRender: () => {},
+ }),
+ )
+
+ await waitFor(() => anchorAttempts === 1 && olderAttempts === 1)
+ await act(async () => {
+ await queryClient.cancelQueries({ queryKey, exact: true })
+ })
+ await waitFor(() => anchorAttempts === 2 && olderAttempts === 2)
+
+ renderer.unmount()
+ })
+
it("does not fabricate cache data if normalization observes a vanished entry", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const cachedPage = {
@@ -828,7 +1118,6 @@ describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
await waitFor(() => apiFetchMock.mock.calls.length === 1)
expect(apiFetchMock).toHaveBeenCalledWith(
"/api/community/channels/ch_activation/messages",
- { signal: expect.any(AbortSignal) },
)
newest.resolve({
diff --git a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts
index 850b3d4a5..efafc46d5 100644
--- a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts
@@ -66,7 +66,7 @@ describe("anchor repair retains the message window", () => {
.mockResolvedValue(page)
const { rendered } = mount(kind)
await advance(900)
- expect(renders.at(-1)?.phase).toBe("aurora")
+ expect(renders.at(-1)?.phase).toBe("positioning")
await act(async () => { fail(new Error("offline")) })
await advance()
expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["cached"])
@@ -138,7 +138,7 @@ describe("anchor repair retains the message window", () => {
}
})
await advance(10_000)
- expect(apiFetchMock).toHaveBeenCalledTimes(change === "evict" ? 2 : 1)
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
if (change === "evict") {
expect(client.getQueryData(key)).toBeUndefined()
rendered.unmount()
diff --git a/src/web/src/hooks/community/use-messages.dom.test.ts b/src/web/src/hooks/community/use-messages.dom.test.ts
index d313012d4..dd25bf81f 100644
--- a/src/web/src/hooks/community/use-messages.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.dom.test.ts
@@ -4,6 +4,7 @@ import { QueryClient, QueryClientProvider, type InfiniteData } from "@tanstack/r
import { renderHook, waitFor } from "@/test/react-dom-harness"
import { communityKeys } from "@/lib/query-keys"
import type { Msg } from "@/lib/community/models/message"
+import { useCommunityWsStore } from "@/stores/community/ws"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -12,6 +13,7 @@ vi.mock("@/lib/api/client", () => ({
beforeEach(() => {
apiFetchMock.mockReset()
+ useCommunityWsStore.getState().reset()
})
// Load *after* the mock is set up so the queryFn resolves the mocked import.
@@ -77,6 +79,30 @@ describe("channelMessagesQueryFn — url per mode", () => {
})
describe("channelMessagesQueryFn — queryClient integration", () => {
+ it.each(["account", "access"] as const)(
+ "rejects a signal-free cold result after the active %s epoch changes",
+ async (epoch) => {
+ const { channelMessagesQueryFn } = await loadHook()
+ const queryClient = new QueryClient()
+ useCommunityWsStore.getState().activateProfileAccount("viewer-a")
+ let resolveTransport!: (value: { messages: Msg[]; hasMore: boolean }) => void
+ apiFetchMock.mockReturnValue(new Promise((resolve) => { resolveTransport = resolve }))
+ const request = channelMessagesQueryFn("ch_1", null, { queryClient })({
+ pageParam: { mode: "newest" },
+ signal: undefined,
+ })
+
+ if (epoch === "account") {
+ useCommunityWsStore.getState().activateProfileAccount("viewer-b")
+ } else {
+ useCommunityWsStore.getState().revokeChannelAccess("server-1", "ch_1")
+ }
+ resolveTransport({ messages: [], hasMore: false })
+
+ await expect(request).rejects.toMatchObject({ name: "AbortError" })
+ },
+ )
+
it("validates the transport receipt before returning a cache-safe page", async () => {
const { channelMessagesQueryFn } = await loadHook()
const onSurfaceReceipt = vi.fn()
diff --git a/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.ts b/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.ts
index 7ea14a56c..ce6ed20f7 100644
--- a/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.jump-to-present.dom.test.ts
@@ -5,6 +5,12 @@ import { act, render as renderDom } from "@/test/react-dom-harness"
import { communityKeys } from "@/lib/query-keys"
import { useDmMessages, useMessages, type MessagesPage } from "./use-messages"
import { useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import { ingestMessages } from "@/lib/community-db/sync"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -12,6 +18,7 @@ vi.mock("@/lib/api/client", () => ({
}))
type Snapshot = {
+ fetchOlder: () => void
hasMoreNewer: boolean
ids: string[]
isFetchingNewer: boolean
@@ -23,18 +30,22 @@ function ChannelCapture({
channelId,
lastReadMessageId,
onRender,
+ revalidateOnMount,
}: {
anchorMessageId?: string | null
channelId: string
lastReadMessageId: string | null
onRender: (snapshot: Snapshot) => void
+ revalidateOnMount?: boolean
}) {
const result = useMessages(channelId, {
anchorMessageId,
lastReadMessageId,
+ revalidateOnMount,
serverId: "server_1",
})
onRender({
+ fetchOlder: result.fetchOlder,
hasMoreNewer: result.hasMoreNewer,
ids: result.messages.map((message) => message.id),
isFetchingNewer: result.isFetchingNewer,
@@ -54,6 +65,7 @@ function DmCapture({
}) {
const result = useDmMessages(dmId, { lastReadMessageId })
onRender({
+ fetchOlder: result.fetchOlder,
hasMoreNewer: result.hasMoreNewer,
ids: result.messages.map((message) => message.id),
isFetchingNewer: result.isFetchingNewer,
@@ -62,6 +74,49 @@ function DmCapture({
return null
}
+function ChannelWindowCommitCapture({
+ blocker,
+ channelId,
+ onCommit,
+ suspend,
+}: {
+ blocker: Promise<never>
+ channelId: string
+ onCommit: (ids: string[]) => void
+ suspend: boolean
+}) {
+ const result = useMessages(channelId, {
+ lastReadMessageId: undefined,
+ serverId: "server_1",
+ })
+ const signature = result.messages.map((message) => message.id).join(",")
+ React.useLayoutEffect(() => {
+ onCommit(signature ? signature.split(",") : [])
+ }, [onCommit, signature])
+ if (suspend) throw blocker
+ return null
+}
+
+function DmWindowCommitCapture({
+ blocker,
+ dmId,
+ onCommit,
+ suspend,
+}: {
+ blocker: Promise<never>
+ dmId: string
+ onCommit: (ids: string[]) => void
+ suspend: boolean
+}) {
+ const result = useDmMessages(dmId, { lastReadMessageId: undefined })
+ const signature = result.messages.map((message) => message.id).join(",")
+ React.useLayoutEffect(() => {
+ onCommit(signature ? signature.split(",") : [])
+ }, [onCommit, signature])
+ if (suspend) throw blocker
+ return null
+}
+
function createClient(): QueryClient {
return new QueryClient({
defaultOptions: {
@@ -139,6 +194,161 @@ beforeEach(() => {
})
describe("useMessages jumpToPresent", () => {
+ it("uses canonical content only for the active transport window", async () => {
+ const queryClient = createClient()
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ const disposeRegistry = registry.cleanup.bind(registry)
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const message = (id: string, seq: number) => ({
+ id,
+ type: "chat" as const,
+ seq,
+ createdAt: new Date(Date.UTC(2026, 7, 9, 0, 0, seq)).toISOString(),
+ })
+ ingestMessages(registry, "channel_window", [
+ message("m40", 40),
+ message("m60", 60),
+ message("m80", 80),
+ message("m90", 90),
+ message("m100", 100),
+ ])
+ queryClient.setQueryData(communityKeys.channelMessages("channel_window"), {
+ pages: [{
+ messages: [message("m40", 40), message("m60", 60)],
+ hasMoreOlder: false,
+ hasMoreNewer: true,
+ newerCursor: "m60",
+ latestSeq: 100,
+ }],
+ pageParams: [{ mode: "anchor", anchor: "m40" }],
+ })
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url === "/api/community/channels/channel_window/messages") {
+ return Promise.resolve({
+ messages: [message("m90", 90), message("m100", 100)],
+ hasMore: true,
+ cursor: "older-present",
+ latestSeq: 100,
+ } satisfies MessagesPage)
+ }
+ if (url === "/api/community/channels/channel_window/messages?cursor=older-present") {
+ return Promise.resolve({
+ messages: [message("m80", 80)],
+ hasMore: false,
+ latestSeq: 100,
+ } satisfies MessagesPage)
+ }
+ throw new Error(`unexpected URL: ${url}`)
+ })
+ let latest!: Snapshot
+ const renderer = renderDom(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(
+ CommunityDbProvider,
+ { registry },
+ React.createElement(ChannelCapture, {
+ channelId: "channel_window",
+ lastReadMessageId: "m40",
+ onRender: (snapshot) => { latest = snapshot },
+ }),
+ ),
+ ),
+ )
+
+ await waitFor(() => latest?.ids.join(",") === "m40,m60")
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids.join(",") === "m90,m100")
+ act(() => latest.fetchOlder())
+ await waitFor(() => latest.ids.join(",") === "m80,m90,m100")
+
+ expect(latest.ids).not.toContain("m40")
+ expect(latest.ids).not.toContain("m60")
+ renderer.unmount()
+ unregister()
+ await disposeRegistry()
+ })
+
+ it.each(["channel", "dm"] as const)(
+ "does not let an aborted %s key switch rewrite committed transport-window ownership",
+ async (kind) => {
+ const queryClient = createClient()
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ const disposeRegistry = registry.cleanup.bind(registry)
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ const scopeA = `${kind}_committed_a`
+ const scopeB = `${kind}_aborted_b`
+ const message = (id: string, seq: number) => ({
+ id,
+ type: "chat" as const,
+ seq,
+ createdAt: new Date(Date.UTC(2026, 7, 9, 0, 0, seq)).toISOString(),
+ })
+ const visible = message(`${kind}_visible`, 1)
+ const outsideWindow = message(`${kind}_outside`, 2)
+ ingestMessages(registry, scopeA, [visible, outsideWindow])
+ const queryKey = kind === "channel"
+ ? communityKeys.channelMessages(scopeA)
+ : communityKeys.dmMessages(scopeA)
+ queryClient.setQueryData(queryKey, {
+ pages: [{
+ messages: [visible],
+ hasMoreOlder: false,
+ hasMoreNewer: false,
+ latestSeq: 2,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+ const blocker = new Promise<never>(() => {})
+ let committedIds: string[] = []
+ const onCommit = (ids: string[]) => { committedIds = ids }
+ const tree = (scopeId: string, suspend: boolean) => React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(
+ CommunityDbProvider,
+ { registry },
+ React.createElement(
+ React.Suspense,
+ { fallback: null },
+ kind === "channel"
+ ? React.createElement(ChannelWindowCommitCapture, {
+ blocker,
+ channelId: scopeId,
+ onCommit,
+ suspend,
+ })
+ : React.createElement(DmWindowCommitCapture, {
+ blocker,
+ dmId: scopeId,
+ onCommit,
+ suspend,
+ }),
+ ),
+ ),
+ )
+ const renderer = renderDom(tree(scopeA, false))
+ await waitFor(() => committedIds.join(",") === visible.id)
+
+ act(() => {
+ React.startTransition(() => renderer.rerender(tree(scopeB, true)))
+ })
+ act(() => {
+ queryClient.removeQueries({ queryKey, exact: true })
+ renderer.rerender(tree(scopeA, false))
+ })
+ await waitFor(() => committedIds.length === 0)
+
+ expect(committedIds).not.toContain(outsideWindow.id)
+ renderer.unmount()
+ unregister()
+ await disposeRegistry()
+ },
+ )
+
it("resets once, fetches newest once, and keeps the old last-read anchor suppressed", async () => {
const queryClient = createClient()
const queryKey = communityKeys.channelMessages("channel_1")
@@ -187,6 +397,51 @@ describe("useMessages jumpToPresent", () => {
renderer.unmount()
})
+ it("gives resetQueries sole request ownership after a revalidated mount jumps to present", async () => {
+ const queryClient = createClient()
+ const queryKey = communityKeys.channelMessages("channel_revalidated")
+ seedAnchor(queryClient, queryKey, "anchor_revalidated")
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url.endsWith("?anchor=anchor_revalidated")) {
+ return Promise.resolve({
+ messages: [{
+ id: "anchor_revalidated",
+ seq: 1,
+ createdAt: "2026-08-09T00:00:00.000Z",
+ }],
+ hasMoreOlder: false,
+ hasMoreNewer: true,
+ newerCursor: "anchor_revalidated",
+ latestSeq: 36,
+ } satisfies MessagesPage)
+ }
+ return Promise.resolve(newestPage("latest_revalidated"))
+ })
+ let latest!: Snapshot
+ const renderer = render(
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_revalidated",
+ lastReadMessageId: "anchor_revalidated",
+ onRender: (snapshot) => { latest = snapshot },
+ revalidateOnMount: true,
+ }),
+ )
+
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ await waitFor(() => !queryClient.isFetching({ queryKey }))
+ apiFetchMock.mockClear()
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids[0] === "latest_revalidated" && !latest.isFetchingNewer)
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/channel_revalidated/messages",
+ { signal: expect.any(AbortSignal) },
+ )
+ renderer.unmount()
+ })
+
it("treats repeated clicks during one pending attempt as idempotent", async () => {
const queryClient = createClient()
const queryKey = communityKeys.channelMessages("channel_pending")
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index b1ac34675..f5733cd78 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -32,6 +32,15 @@ import {
useConversationNavigationGate,
} from "@/lib/community/conversation-navigation-proof"
import type { MessageSurfaceReceipt } from "@/lib/community/conversation-navigation-proof"
+import {
+ useCanonicalMessagesById,
+ useMessageProjection,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityMessages,
+} from "@/lib/community-db/sync"
/**
* Fetches paginated messages for a community channel.
@@ -55,12 +64,47 @@ export type { MessagesPage, MessagesPageParam } from "@/lib/community/models/mes
export type { MessageSurfaceReceipt } from "@/lib/community/conversation-navigation-proof"
+type CommittedTransportWindow = {
+ key: string
+ observed: boolean
+}
+
+function useCommittedTransportWindow(
+ queryKey: readonly unknown[],
+ hasData: boolean,
+): boolean {
+ const key = useMemo(() => JSON.stringify(queryKey), [queryKey])
+ const [committed, setCommitted] = useState<CommittedTransportWindow>(() => ({
+ key,
+ observed: hasData,
+ }))
+ const observed = committed.key === key
+ ? committed.observed || hasData
+ : hasData
+
+ // A suspended render may inspect another query key, but it must not advance
+ // window ownership. Commit the sticky "observed" bit only after React has
+ // accepted this render, and reset it semantically when the key commits.
+ useLayoutEffect(() => {
+ setCommitted((current) => {
+ const nextObserved = current.key === key
+ ? current.observed || hasData
+ : hasData
+ if (current.key === key && current.observed === nextObserved) return current
+ return { key, observed: nextObserved }
+ })
+ }, [hasData, key])
+
+ return observed
+}
+
type MessagesTransportPage = MessagesPage & {
surfaceReceipt?: MessageSurfaceReceipt
}
type MessagesTransportOptions = {
onSurfaceReceipt?: (receipt: MessageSurfaceReceipt) => void
+ queryClient?: QueryClient
}
function isMessageSurfaceReceipt(value: unknown): value is MessageSurfaceReceipt {
@@ -123,12 +167,23 @@ export const channelMessagesQueryFn =
pageParam: MessagesPageParam
signal?: AbortSignal
}): Promise<MessagesPage> => {
+ const publicationToken = options?.queryClient
+ ? captureCommunityLiveSnapshotToken(options.queryClient)
+ : null
const url = buildMessagesUrl(
`/api/community/channels/${channelId}/messages`,
pageParam,
tag,
)
- return fetchMessagesTransport(url, signal, options)
+ const page = await fetchMessagesTransport(url, signal, options)
+ if (options?.queryClient && publicationToken) {
+ publishCommunityMessages(options.queryClient, {
+ channelId,
+ messages: page.messages,
+ proof: { token: publicationToken, signal },
+ })
+ }
+ return page
}
export const dmMessagesQueryFn =
@@ -140,11 +195,22 @@ export const dmMessagesQueryFn =
pageParam: MessagesPageParam
signal?: AbortSignal
}): Promise<MessagesPage> => {
+ const publicationToken = options?.queryClient
+ ? captureCommunityLiveSnapshotToken(options.queryClient)
+ : null
const url = buildMessagesUrl(
`/api/community/channels/${dmId}/messages`,
pageParam,
)
- return fetchMessagesTransport(url, signal, options)
+ const page = await fetchMessagesTransport(url, signal, options)
+ if (options?.queryClient && publicationToken) {
+ publishCommunityMessages(options.queryClient, {
+ channelId: dmId,
+ messages: page.messages,
+ proof: { token: publicationToken, signal },
+ })
+ }
+ return page
}
export function messageMatchesTag(message: Msg, tag?: string | null): boolean {
@@ -334,11 +400,37 @@ type PresentOverride = {
}
type ActivationRevalidationState = {
+ abortedAttemptId: number | null
+ activeAttemptId: number | null
+ attemptId: number
pending: Promise<unknown> | null
- requested: boolean
+ completed: boolean
+ activationKey: string
+}
+
+type InitialWindowReceipt = {
+ pageParam: MessagesPageParam
viewKey: string
}
+type InitialMessagesPageParam = Extract<
+ MessagesPageParam,
+ { mode: "newest" | "anchor" }
+>
+
+function sameMessagesPageParam(
+ left: MessagesPageParam | undefined,
+ right: InitialMessagesPageParam,
+): boolean {
+ if (!left || left.mode !== right.mode) return false
+ switch (right.mode) {
+ case "newest":
+ return true
+ case "anchor":
+ return left.mode === "anchor" && left.anchor === right.anchor
+ }
+}
+
// Shared pagination + reducer used by both channel and DM hooks. Kept inline
// as a hook because both variants need the same TanStack setup — factoring
// out a plain function would leak query internals; a hook stays clean.
@@ -371,27 +463,35 @@ function useMessagesInner(
() => JSON.stringify([queryKey, opts?.anchorMessageId ?? null]),
[queryKey, opts?.anchorMessageId],
)
- const activationRevalidationRef = useRef<ActivationRevalidationState>({
- pending: null,
- requested: false,
- viewKey,
- })
const attemptIdRef = useRef(0)
const snapshotRef = useRef<{
attemptId: number
data: PageCache | undefined
viewKey: string
} | null>(null)
- const networkFetchObservedRef = useRef(false)
+ const [activationRetryEpoch, setActivationRetryEpoch] = useState(0)
const [presentOverride, setPresentOverride] = useState<PresentOverride | null>(null)
const forceNewest = presentOverride?.viewKey === viewKey
const jumpPending = forceNewest && presentOverride?.phase === "requested"
- const initialPageParam = useMemo<MessagesPageParam>(() => {
+ const initialPageParam = useMemo<InitialMessagesPageParam>(() => {
if (forceNewest) return { mode: "newest" }
if (anchorId) return { mode: "anchor", anchor: anchorId }
return { mode: "newest" }
}, [forceNewest, anchorId])
+ const activationKey = useMemo(
+ () => JSON.stringify([viewKey, initialPageParam]),
+ [initialPageParam, viewKey],
+ )
+ const activationRevalidationRef = useRef<ActivationRevalidationState>({
+ abortedAttemptId: null,
+ activeAttemptId: null,
+ attemptId: 0,
+ pending: null,
+ completed: false,
+ activationKey,
+ })
+ const initialWindowReceiptRef = useRef<InitialWindowReceipt | null>(null)
const query = useInfiniteQuery<
MessagesPage,
@@ -402,12 +502,38 @@ function useMessagesInner(
>({
queryKey,
// `enabled` is the execution gate. Keep the real transport installed even
- // while the read-state anchor is resolving: a persisted observer can be
+ // while the read-state anchor is resolving: a retained observer can be
// explicitly refetched during the disabled→enabled commit before
// TanStack's passive option update runs. Installing a rejecting sentinel
// here made that one-shot revalidation fail locally without issuing the
// required `/messages` request.
- queryFn,
+ queryFn: async (context) => {
+ const stateAtStart = activationRevalidationRef.current
+ const attemptId = stateAtStart.activationKey === activationKey
+ ? stateAtStart.activeAttemptId
+ : null
+ const coldInitialRequest = !forceNewest
+ && attemptId === null
+ && queryClient.getQueryData(queryKey) === undefined
+ && sameMessagesPageParam(context.pageParam, initialPageParam)
+ const transportSignal = coldInitialRequest ? undefined : context.signal
+ const markAborted = () => {
+ if (
+ attemptId !== null
+ && activationRevalidationRef.current === stateAtStart
+ && stateAtStart.activationKey === activationKey
+ && stateAtStart.activeAttemptId === attemptId
+ ) {
+ stateAtStart.abortedAttemptId = attemptId
+ }
+ }
+ transportSignal?.addEventListener("abort", markAborted, { once: true })
+ try {
+ return await queryFn({ pageParam: context.pageParam, signal: transportSignal })
+ } finally {
+ transportSignal?.removeEventListener("abort", markAborted)
+ }
+ },
initialPageParam,
// "next" = older side. `fetchNextPage` appends to `data.pages`, so the
// LAST entry in `pages` is the oldest window we've loaded — that's the
@@ -434,8 +560,8 @@ function useMessagesInner(
// mount refetch for both so it cannot replay a pre-resolution pageParam.
...(opts?.revalidateOnMount !== undefined ? { refetchOnMount: false } : {}),
refetchOnReconnect: false,
- // Message bases are persisted, while accepted/session rows live in an
- // in-memory overlay. Ordinary observers stay stale; opt-in cached mounts
+ // Canonical message rows are persisted, while transport page ownership
+ // and accepted/session rows stay in memory. Ordinary observers stay stale; opt-in cached mounts
// are held fresh only until the anchor-normalized revalidation below owns
// their request. Once this mounted observer has seen a real request, hold
// it fresh so a later disabled→enabled transition cannot duplicate that
@@ -447,9 +573,8 @@ function useMessagesInner(
// Opt-in cached mounts are revalidated explicitly below so the request
// can first normalize its semantic page identity. Mark them fresh here
// to prevent TanStack's enabled-transition fetch from racing that owner
- // with a persisted cursor/newest pageParam.
+ // with an older cursor/newest pageParam.
(opts?.revalidateOnMount === true && cachedQuery.state.data !== undefined)
- || networkFetchObservedRef.current
|| cachedWindowNeedsAnchorReconcile(
cachedQuery.state.data as PageCache | undefined,
forceNewest ? null : anchorId,
@@ -464,7 +589,6 @@ function useMessagesInner(
reconcileLateAnchor,
)
useLayoutEffect(() => {
- networkFetchObservedRef.current = false
const mountedQuery = queryClient.getQueryCache().find({ queryKey, exact: true })
if (!mountedQuery) return
return queryClient.getQueryCache().subscribe((event) => {
@@ -473,21 +597,54 @@ function useMessagesInner(
&& event.query.queryHash === mountedQuery.queryHash
&& event.action.type === "success"
&& !event.action.manual
+ && event.query.state.fetchMeta === null
) {
- networkFetchObservedRef.current = true
+ const receiptPageParam = (event.query.state.data as PageCache | undefined)
+ ?.pageParams[0]
+ if (!receiptPageParam) return
+ initialWindowReceiptRef.current = {
+ pageParam: receiptPageParam,
+ viewKey,
+ }
+ const state = activationRevalidationRef.current
+ if (
+ state.activationKey === activationKey
+ && sameMessagesPageParam(receiptPageParam, initialPageParam)
+ ) {
+ state.completed = true
+ state.activeAttemptId = null
+ state.abortedAttemptId = null
+ state.pending = null
+ }
}
})
- }, [queryClient, queryKey, viewKey])
+ }, [activationKey, initialPageParam, queryClient, queryKey, viewKey])
useLayoutEffect(() => {
let state = activationRevalidationRef.current
- if (state.viewKey !== viewKey) {
- state = { pending: null, requested: false, viewKey }
+ if (state.activationKey !== activationKey) {
+ state = {
+ abortedAttemptId: null,
+ activeAttemptId: null,
+ attemptId: 0,
+ pending: null,
+ completed: false,
+ activationKey,
+ }
activationRevalidationRef.current = state
}
- if (isRestoring || state.requested) return
+ if (isRestoring || forceNewest || state.completed || state.pending) return
if (!enabled || query.data === undefined || opts?.revalidateOnMount !== true) return
+ const receipt = initialWindowReceiptRef.current
+ if (
+ receipt?.viewKey === viewKey
+ && sameMessagesPageParam(receipt.pageParam, initialPageParam)
+ ) {
+ state.completed = true
+ return
+ }
+
// Guarantee one actual post-mount fetch for cached conversation observers.
// A retained observer can mount after restore and read-state have already
// settled, so neither lifecycle is a reliable prerequisite. Retained cache
@@ -496,29 +653,44 @@ function useMessagesInner(
// request. Refetch through this observer rather than asking the cache for
// "active" queries: while PersistQueryClientProvider hands hydration back
// to React, the mounted observer can briefly fail that cache-level filter.
- // An infinite-query refetch replays its first persisted pageParam. Normalize
+ // An infinite-query refetch replays its first retained pageParam. Normalize
// that identity to this mount's resolved anchor/newest target first: after
// older pagination or hydration the stored first param can be a cursor,
// which must never outrun the read-state anchor on a retained mount.
// Running in layout also starts the semantic revalidation before the
// message-list's passive IntersectionObserver can request another page.
- state.requested = true
- if (networkFetchObservedRef.current) return
queryClient.setQueryData<PageCache>(queryKey, (current) => current
? {
...current,
pageParams: [initialPageParam, ...current.pageParams.slice(1)],
}
: current)
+ state.attemptId += 1
+ const attemptId = state.attemptId
+ state.activeAttemptId = attemptId
+ state.abortedAttemptId = null
const request = refetchMountedObserver({ cancelRefetch: false })
state.pending = request
- const clearPending = () => {
+ const settleAttempt = () => {
if (state.pending === request) state.pending = null
+ if (state.completed) return
+ if (
+ state.abortedAttemptId === attemptId
+ && state.activeAttemptId === attemptId
+ && activationRevalidationRef.current === state
+ && state.activationKey === activationKey
+ ) {
+ state.activeAttemptId = null
+ setActivationRetryEpoch((epoch) => epoch + 1)
+ }
}
- void request.then(clearPending, clearPending)
+ void request.then(settleAttempt, settleAttempt)
}, [
+ activationRetryEpoch,
+ activationKey,
anchorRepairNeeded,
enabled,
+ forceNewest,
initialPageParam,
isRestoring,
opts?.revalidateOnMount,
@@ -712,11 +884,11 @@ function useMessagesInner(
if (!query.hasNextPage) return
if (query.isFetchingNextPage) return
const activationState = activationRevalidationRef.current
- if (activationState.viewKey !== viewKey) return
+ if (activationState.activationKey !== activationKey) return
const activationRequest = activationState.pending
if (activationRequest) {
void activationRequest.then(() => {
- if (activationRevalidationRef.current.viewKey !== viewKey) return
+ if (activationRevalidationRef.current.activationKey !== activationKey) return
void query.fetchNextPage({ cancelRefetch: false })
})
return
@@ -734,7 +906,7 @@ function useMessagesInner(
return
}
void query.fetchNextPage()
- }, [enabled, query, viewKey])
+ }, [activationKey, enabled, query])
const fetchNewer = useCallback(() => {
if (!query.hasPreviousPage) return
@@ -755,7 +927,7 @@ function useMessagesInner(
return {
...query,
// Instant channel switch: a warm channel already has its newest-tail
- // hydrated into `messages` (from the persisted `channelMessages` cache)
+ // restored in canonical message rows
// before the read anchor resolves. Those rows must paint immediately rather
// than wait on the read-snapshot round-trip — switching must not
// happen on a network timescale. So only report loading when there is
@@ -766,7 +938,7 @@ function useMessagesInner(
// forces `isFetching` false in that state, so native
// `isLoading = isPending && isFetching` computes to `false` even with no
// data — leaving callers a frame of "ready but empty". We still guard that
- // empty case, but a non-empty hydrated cache is the warm tail and renders
+ // empty case, but a non-empty canonical tail is warm and renders
// now. The scroll-to-bottom / NEW-divider / unread count stay gated in the
// page + `useScrollAnchor` (which now scrolls a warm tail to the bottom on
// first paint and converges the divider once the snapshot lands), so early
@@ -803,6 +975,9 @@ export function useMessages(
channelId: string | null,
opts: ChannelMessagesOpts,
): MessagesReturn {
+ const registry = useOptionalCommunityDbRegistry()
+ const dbMessages = useMessageProjection(channelId)
+ const canonicalMessagesById = useCanonicalMessagesById()
const queryClient = useQueryClient()
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const queryKey = useMemo(() => {
@@ -811,6 +986,7 @@ export function useMessages(
}, [channelId, opts.tag])
const queryFn = useMemo(
() => channelMessagesQueryFn(channelId ?? "__none__", opts.tag, {
+ queryClient,
onSurfaceReceipt: (receipt) => {
recordConversationNavigationReceipt(
queryClient,
@@ -827,6 +1003,10 @@ export function useMessages(
queryFn,
opts,
)
+ const transportWindowObserved = useCommittedTransportWindow(
+ queryKey,
+ base.data !== undefined,
+ )
const scope = useMemo<MessageScope>(() => ({
kind: "channel",
id: channelId ?? "__none__",
@@ -834,10 +1014,20 @@ export function useMessages(
}), [channelId, opts.serverId])
const overlay = useMessageOverlay(scope)
const canonicalBase = useMemo(
- () => base.messages.filter(
- (message): message is CanonicalMessage => typeof message.seq === "number",
- ),
- [base.messages],
+ () => {
+ const messages = !registry
+ ? base.messages
+ : !transportWindowObserved
+ ? dbMessages ?? []
+ : base.messages.flatMap((message) => {
+ const canonical = canonicalMessagesById?.get(message.id)
+ return canonical ? [canonical] : []
+ })
+ return messages.filter(
+ (message): message is CanonicalMessage => typeof message.seq === "number",
+ )
+ },
+ [base.messages, canonicalMessagesById, dbMessages, registry, transportWindowObserved],
)
useEffect(() => {
if (!channelId) return
@@ -865,7 +1055,7 @@ export function useMessages(
return {
...base,
messages: gated ? [] : messages,
- isLoading: base.isLoading || gated,
+ isLoading: (base.isLoading && canonicalBase.length === 0) || gated,
navigationBlocked: gated,
}
}
@@ -877,6 +1067,9 @@ export function useDmMessages(
dmId: string | null,
opts?: MessagesOpts,
): MessagesReturn {
+ const registry = useOptionalCommunityDbRegistry()
+ const dbMessages = useMessageProjection(dmId)
+ const canonicalMessagesById = useCanonicalMessagesById()
const queryClient = useQueryClient()
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const queryKey = useMemo(
@@ -885,6 +1078,7 @@ export function useDmMessages(
)
const queryFn = useMemo(
() => dmMessagesQueryFn(dmId ?? "__none__", {
+ queryClient,
onSurfaceReceipt: (receipt) => {
recordConversationNavigationReceipt(
queryClient,
@@ -901,16 +1095,30 @@ export function useDmMessages(
queryFn,
opts,
)
+ const transportWindowObserved = useCommittedTransportWindow(
+ queryKey,
+ base.data !== undefined,
+ )
const scope = useMemo<MessageScope>(() => ({
kind: "dm",
id: dmId ?? "__none__",
}), [dmId])
const overlay = useMessageOverlay(scope)
const canonicalBase = useMemo(
- () => base.messages.filter(
- (message): message is CanonicalMessage => typeof message.seq === "number",
- ),
- [base.messages],
+ () => {
+ const messages = !registry
+ ? base.messages
+ : !transportWindowObserved
+ ? dbMessages ?? []
+ : base.messages.flatMap((message) => {
+ const canonical = canonicalMessagesById?.get(message.id)
+ return canonical ? [canonical] : []
+ })
+ return messages.filter(
+ (message): message is CanonicalMessage => typeof message.seq === "number",
+ )
+ },
+ [base.messages, canonicalMessagesById, dbMessages, registry, transportWindowObserved],
)
useEffect(() => {
if (!dmId) return
@@ -937,7 +1145,7 @@ export function useDmMessages(
return {
...base,
messages: gated ? [] : messages,
- isLoading: base.isLoading || gated,
+ isLoading: (base.isLoading && canonicalBase.length === 0) || gated,
navigationBlocked: gated,
}
}
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 bec0da5d8..6df8352b2 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
@@ -3,6 +3,15 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { renderHook, waitFor } from "@/test/react-dom-harness"
import { communityKeys } from "@/lib/query-keys"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityLiveSnapshot,
+} from "@/lib/community-db/sync"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -40,6 +49,10 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {
const queryClient = new QueryClient()
const key = communityKeys.notificationSettings()
await queryClient.fetchQuery({ queryKey: key, queryFn: notificationSettingsQueryFn })
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/users/me/notifications",
+ { signal: expect.any(AbortSignal) },
+ )
expect(queryClient.getQueryData(key)).toBeDefined()
})
@@ -69,4 +82,52 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {
rendered.unmount()
disposeAccountUnreadProjection(queryClient)
})
+
+ it("projects warm canonical policy while the transport request is stalled", async () => {
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
+ const { useNotificationSettings } = await import("./use-notification-settings")
+ const {
+ disposeAccountUnreadProjection,
+ getAccountUnreadProjection,
+ } = await import("./account-unread-projection")
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const registry = createCommunityDbRegistry(queryClient, "viewer_1")
+ const disposeRegistry = registry.cleanup.bind(registry)
+ await registry.preload()
+ const unregister = registerCommunityDbRegistry(registry)
+ publishCommunityLiveSnapshot(queryClient, {
+ snapshot: {
+ kind: "notification-settings",
+ data: {
+ raw: [{ serverId: "srv_1", channelId: null, level: "nothing" }],
+ server: { srv_1: "Nothing" },
+ channel: {},
+ },
+ },
+ proof: {
+ kind: "structural",
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
+ })
+ const projection = getAccountUnreadProjection(queryClient, "viewer_1")
+ projection.recordArrival({ channelId: "channel_1", serverId: "srv_1", seq: 1 })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(CommunityDbProvider, { registry }, children),
+ )
+ const rendered = renderHook(() => useNotificationSettings(), { wrapper })
+
+ await waitFor(() => expect(rendered.result.current.server).toEqual({ srv_1: "Nothing" }))
+ await waitFor(() => expect(
+ projection.projectUnread("servers", "channel_1", false),
+ ).toBe(false))
+ expect(rendered.result.current.fetchStatus).toBe("fetching")
+
+ rendered.unmount()
+ unregister()
+ await disposeRegistry()
+ disposeAccountUnreadProjection(queryClient)
+ })
})
diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.ts
index 8e077b6ed..335dca28e 100644
--- a/src/web/src/hooks/community/use-notification-settings.ts
+++ b/src/web/src/hooks/community/use-notification-settings.ts
@@ -16,6 +16,14 @@ import {
getActiveAccountUnreadProjection,
type AccountUnreadProjection,
} from "./account-unread-projection"
+import {
+ useNotificationSettingsProjection,
+ useOptionalCommunityDbRegistry,
+} from "@/lib/community-db/projections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityLiveSnapshot,
+} from "@/lib/community-db/sync"
/**
* Fetches the user's notification-setting rows and materialises them into
@@ -55,6 +63,9 @@ export function resolveServerNotificationDisplayLevel(level?: string): string {
export const notificationSettingsQueryFn = async (
context: QueryFunctionContext = {} as QueryFunctionContext,
): Promise<NotificationSettings> => {
+ const publicationToken = context.client
+ ? captureCommunityLiveSnapshotToken(context.client)
+ : null
const rows = context.signal
? await apiFetch<NotificationSettingRow[]>(
"/api/community/users/me/notifications",
@@ -70,7 +81,14 @@ export const notificationSettingsQueryFn = async (
if (s.channelId) channel[s.channelId] = level
else if (s.serverId) server[s.serverId] = level
}
- return { raw: rows, server, channel }
+ const data = { raw: rows, server, channel }
+ if (context.client && publicationToken) {
+ publishCommunityLiveSnapshot(context.client, {
+ snapshot: { kind: "notification-settings", data },
+ proof: { kind: "structural", token: publicationToken, signal: context.signal },
+ })
+ }
+ return data
}
function projectNotificationSettings(
@@ -102,6 +120,8 @@ export function useNotificationSettings(): UseQueryResult<NotificationSettings>
server: Record<string, string>
channel: Record<string, string>
} {
+ const registry = useOptionalCommunityDbRegistry()
+ const dbSettings = useNotificationSettingsProjection()
const queryClient = useQueryClient()
const projection = useMemo(
() => getActiveAccountUnreadProjection(queryClient),
@@ -111,13 +131,18 @@ export function useNotificationSettings(): UseQueryResult<NotificationSettings>
queryKey: communityKeys.notificationSettings(),
queryFn: notificationSettingsQueryFn,
})
+ const projectedSettings = registry ? dbSettings : query.data
useEffect(() => {
- if (query.data) projectNotificationSettings(projection, query.data)
- }, [projection, query.data])
+ if (projectedSettings) projectNotificationSettings(projection, projectedSettings)
+ }, [projectedSettings, projection])
return {
...query,
- server: query.data?.server ?? (EMPTY_NOTIF_SERVER as Record<string, string>),
- channel: query.data?.channel ?? (EMPTY_NOTIF_CHANNEL as Record<string, string>),
+ server: registry
+ ? dbSettings?.server ?? (EMPTY_NOTIF_SERVER as Record<string, string>)
+ : query.data?.server ?? (EMPTY_NOTIF_SERVER as Record<string, string>),
+ channel: registry
+ ? dbSettings?.channel ?? (EMPTY_NOTIF_CHANNEL as Record<string, string>)
+ : query.data?.channel ?? (EMPTY_NOTIF_CHANNEL as Record<string, string>),
}
}
diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
index a83f1d3d2..c022afd23 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.test.ts
@@ -206,10 +206,11 @@ function messageItem(id: string, authorId?: string): FlatItem {
}
}
-function growingRow(requestFrame: (callback: FrameRequestCallback) => void) {
+function growingRow(requestFrame: (callback: FrameRequestCallback) => void, index = 0) {
let height = 400
return {
element: {
+ dataset: { index: String(index) },
getBoundingClientRect: () => ({ height }),
get scrollHeight() {
return height
@@ -300,6 +301,66 @@ describe("useScrollAnchor delayed row-growth re-pin", () => {
expect(scrollWrites).toEqual([1_600, 1_600])
})
+ it("settles a pinned tail after an appended row's first real measurement", async () => {
+ const settleFrames: FrameRequestCallback[] = []
+ vi.stubGlobal("window", {
+ requestAnimationFrame: (callback: FrameRequestCallback) => {
+ settleFrames.push(callback)
+ return settleFrames.length
+ },
+ cancelAnimationFrame: vi.fn(),
+ })
+ const mounted = await mountHook({
+ items: [messageItem("m1")],
+ initialScrollReady: true,
+ heroMeasured: true,
+ })
+ expect(settleFrames).toHaveLength(1)
+ settleFrames[0](0)
+ mounted.rerender({ items: [messageItem("m1"), messageItem("m2")] })
+
+ let frame: FrameRequestCallback | undefined
+ const row = growingRow((callback) => { frame = callback }, 1)
+ const measure = virtualizerOptions?.measureElement
+
+ expect(measure!(row.element, undefined, virtualizer as never)).toBe(400)
+ expect(mounted.scrollWrites).toEqual([])
+
+ await Promise.resolve()
+ expect(mounted.scrollWrites).toEqual([1_600])
+ expect(frame).toBeTypeOf("function")
+
+ frame!(0)
+ expect(mounted.scrollWrites).toEqual([1_600, 1_600])
+ })
+
+ it("does not treat an anchored mount row as an append before initial positioning settles", async () => {
+ const settleFrames: FrameRequestCallback[] = []
+ vi.stubGlobal("window", {
+ requestAnimationFrame: (callback: FrameRequestCallback) => {
+ settleFrames.push(callback)
+ return settleFrames.length
+ },
+ cancelAnimationFrame: vi.fn(),
+ })
+ const mounted = await mountHook({
+ items: [messageItem("anchor"), messageItem("newer")],
+ initialScrollReady: true,
+ heroMeasured: true,
+ newDividerBefore: "anchor",
+ })
+ let frame: FrameRequestCallback | undefined
+ const row = growingRow((callback) => { frame = callback }, 1)
+ const measure = virtualizerOptions?.measureElement
+
+ expect(settleFrames).toHaveLength(1)
+ expect(measure!(row.element, undefined, virtualizer as never)).toBe(400)
+ await Promise.resolve()
+
+ expect(mounted.scrollWrites).toEqual([])
+ expect(frame).toBeUndefined()
+ })
+
it("does not schedule a re-pin after upward user intent", async () => {
const { listeners, scrollWrites } = await mountHook()
let frame: FrameRequestCallback | undefined
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 57c0341d9..2957f96ef 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -524,6 +524,16 @@ export function useScrollAnchor({
const [paginationDirection, setPaginationDirection] = useState<"older" | "newer" | null>(null)
const isOlderPageAnchorSettling = paginationDirection === "older"
const isNewerPageAnchorSettling = paginationDirection === "newer"
+ const previousTailId = stateRef.current.lastTailId
+ const previousTailIndex = previousTailId === null
+ ? -1
+ : messages.findIndex((message) => message.id === previousTailId)
+ const firstMeasureAppendIds = initialPositionSettledRef.current
+ && !isNewerPageAnchorSettling
+ && previousTailIndex >= 0
+ && previousTailIndex < messages.length - 1
+ ? new Set(messages.slice(previousTailIndex + 1).map((message) => message.id))
+ : null
const liveResizeAnchor = !isNewerPageAnchorSettling
&& wasExactlyPinnedRef.current
&& !userScrolledAwayRef.current
@@ -555,6 +565,11 @@ export function useScrollAnchor({
const size = measureMessageRow(element)
const previousSize = measuredRowHeightsRef.current.get(element)
measuredRowHeightsRef.current.set(element, size)
+ const index = Number((element as HTMLElement).dataset.index)
+ const measuredItem = Number.isInteger(index) ? items[index] : undefined
+ const isFirstMeasureOfSettledAppend = previousSize === undefined
+ && measuredItem?.kind === "message"
+ && firstMeasureAppendIds?.has(measuredItem.m.id) === true
// `resizeItem` grows the direct-DOM sizer only after this callback
// returns. Its immediate scroll adjustment can therefore be clamped by
@@ -562,8 +577,13 @@ export function useScrollAnchor({
// viewer who was already pinned remains pinned; never move somebody who
// deliberately scrolled away.
if (
- previousSize !== undefined
- && previousSize !== size
+ previousSize !== size
+ // Ref callbacks run before the first layout effect. Do not let those
+ // initial measurements inherit the optimistic `true` latch. Even
+ // after that effect, anchored mount can still be positioning and
+ // measuring its initial rows; only a message identity appended after
+ // initial settlement may give a first measurement re-pin ownership.
+ && (previousSize !== undefined || isFirstMeasureOfSettledAppend)
// Read the last real scroll sample, not `instance.isAtEnd()` here.
// By the time ResizeObserver calls us, an overflowing child can have
// already increased the browser scrollHeight without emitting a
@@ -574,7 +594,11 @@ export function useScrollAnchor({
) {
bottomRepinQueuedRef.current = true
queueMicrotask(() => {
- if (element.isConnected && !userScrolledAwayRef.current) {
+ if (
+ element.isConnected
+ && wasExactlyPinnedRef.current
+ && !userScrolledAwayRef.current
+ ) {
const scrollElement = scrollRef.current
if (scrollElement) scrollElement.scrollTop = scrollElement.scrollHeight
}
@@ -587,7 +611,11 @@ export function useScrollAnchor({
// exactly that hero height after a row-only resize.
element.ownerDocument.defaultView?.requestAnimationFrame(() => {
bottomRepinQueuedRef.current = false
- if (element.isConnected && !userScrolledAwayRef.current) {
+ if (
+ element.isConnected
+ && wasExactlyPinnedRef.current
+ && !userScrolledAwayRef.current
+ ) {
const scrollElement = scrollRef.current
if (scrollElement) scrollElement.scrollTop = scrollElement.scrollHeight
}
diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.ts
index 4d4e01ad1..256153a11 100644
--- a/src/web/src/hooks/community/use-server-members.ts
+++ b/src/web/src/hooks/community/use-server-members.ts
@@ -27,8 +27,7 @@ export const SEARCH_DEBOUNCE_MS = 200
// ── Pure reducers (exported for direct unit tests) ────────────────────────────
//
-// These implement the WS-event insertion strategy documented in
-// `plans/09-members-infinite-scroll.md` §Milestone (b):
+// WS-event insertion rules for paginated member lists:
// - MEMBER_JOIN appends at the *tail* only when the last page is loaded
// (`!hasMore`); otherwise the event is dropped — the joiner will show up
// once the intervening pages load.
diff --git a/src/web/src/hooks/community/use-server-panels.ts b/src/web/src/hooks/community/use-server-panels.ts
index 65ebc5bcb..32beba305 100644
--- a/src/web/src/hooks/community/use-server-panels.ts
+++ b/src/web/src/hooks/community/use-server-panels.ts
@@ -44,7 +44,7 @@ export const invitesQueryFn = (serverId: string) => async (): Promise<InvitesRes
uses: i.uses,
maxUses: i.maxUses,
expiresAt: i.expiresAt,
- by: i.creatorName ?? "Unknown",
+ by: i.creatorName ?? "Deleted user",
creatorId: i.creatorId,
}))
return { invites }
diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.ts
index d4054b891..2537a19e5 100644
--- a/src/web/src/hooks/community/use-servers.test.ts
+++ b/src/web/src/hooks/community/use-servers.test.ts
@@ -15,9 +15,22 @@ vi.mock("react", async (importOriginal) => {
})
const apiFetchMock = vi.fn()
+const dbProjection = vi.hoisted(() => ({
+ registry: null as object | null,
+ rail: undefined as { servers: Array<Record<string, unknown>>; folders: unknown[] } | undefined,
+ attentionScopes: [] as Array<Record<string, unknown>>,
+ attentionItems: [] as Array<Record<string, unknown>>,
+}))
vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useOptionalCommunityDbRegistry: () => dbProjection.registry,
+ useAttentionScopes: () => dbProjection.attentionScopes,
+ useAttentionItems: () => dbProjection.attentionItems,
+ useServerRailProjection: () => dbProjection.rail,
+ useServerTreeProjection: () => undefined,
+}))
type CapturedQueryConfig = {
enabled?: boolean
@@ -45,6 +58,10 @@ beforeEach(() => {
capturedHookQueryClient = new QueryClient()
capturedHookQueryData = undefined
capturedHookQueryError = null
+ dbProjection.registry = null
+ dbProjection.rail = undefined
+ dbProjection.attentionScopes = []
+ dbProjection.attentionItems = []
useCommunityWsStore.getState().reset()
})
@@ -127,7 +144,7 @@ describe("useServers / serversQueryFn", () => {
projection.setNotificationPolicy({})
projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
- await serversProjectedQueryFn(projection)()
+ await serversProjectedQueryFn(projection, new QueryClient())()
expect(projection.projectUnread("servers", "c1", false)).toBe(false)
})
@@ -138,7 +155,7 @@ describe("useServers / serversQueryFn", () => {
const { AccountUnreadProjection } = await import("./account-unread-projection")
const projection = new AccountUnreadProjection("u1")
- await expect(serversProjectedQueryFn(projection)()).rejects.toThrow("offline")
+ await expect(serversProjectedQueryFn(projection, new QueryClient())()).rejects.toThrow("offline")
expect(projection.inspectForTests().pendingSnapshots).toBe(0)
})
@@ -151,7 +168,7 @@ describe("useServers / serversQueryFn", () => {
const { AccountUnreadProjection } = await import("./account-unread-projection")
const projection = new AccountUnreadProjection("u1")
- const pending = serversProjectedQueryFn(projection)()
+ const pending = serversProjectedQueryFn(projection, new QueryClient())()
useCommunityWsStore.getState().activateProfileAccount("u2")
release({ servers: [] })
@@ -159,6 +176,88 @@ describe("useServers / serversQueryFn", () => {
expect(projection.inspectForTests().pendingSnapshots).toBe(0)
})
+ it("confirms live list authority only for the current QueryClient and auth generation", async () => {
+ useCommunityWsStore.getState().activateProfileAccount("u1")
+ apiFetchMock.mockResolvedValueOnce({ servers: [] })
+ const { useServers } = await import("./use-servers")
+
+ expect(useServers().isLiveAuthoritative).toBe(false)
+ await capturedQueryConfig?.queryFn?.()
+ expect(useServers().isLiveAuthoritative).toBe(true)
+
+ useCommunityWsStore.getState().activateProfileAccount("u2")
+ expect(useServers().isLiveAuthoritative).toBe(false)
+
+ capturedHookQueryClient = new QueryClient()
+ expect(useServers().isLiveAuthoritative).toBe(false)
+ })
+
+ it("invalidates live list authority when the access epoch changes", async () => {
+ useCommunityWsStore.getState().activateProfileAccount("u1")
+ apiFetchMock.mockResolvedValueOnce({ servers: [] })
+ const { useServers } = await import("./use-servers")
+
+ useServers()
+ await capturedQueryConfig?.queryFn?.()
+ expect(useServers().isLiveAuthoritative).toBe(true)
+
+ useCommunityWsStore.getState().revokeChannelAccess("s1", "c1")
+
+ expect(useServers().isLiveAuthoritative).toBe(false)
+ })
+
+ it("binds live authority to the projected unordered server membership", async () => {
+ useCommunityWsStore.getState().activateProfileAccount("u1")
+ const liveServers = Array.from({ length: 7 }, (_, index) => ({
+ id: `s${index + 1}`,
+ name: `Server ${index + 1}`,
+ discriminator: `000${index + 1}`,
+ icon: null,
+ ownerId: "u1",
+ unread: false,
+ mentions: 0,
+ }))
+ const liveResponse = { servers: liveServers }
+ capturedHookQueryData = { servers: liveServers.slice(0, 6) }
+ apiFetchMock.mockResolvedValueOnce(liveResponse)
+ const { useServers } = await import("./use-servers")
+
+ useServers()
+ const committedLiveResponse = await capturedQueryConfig?.queryFn?.() as typeof liveResponse
+
+ expect(useServers().servers.map((server) => server.id)).toEqual([
+ "s1", "s2", "s3", "s4", "s5", "s6",
+ ])
+ expect(useServers().isLiveAuthoritative).toBe(false)
+
+ capturedHookQueryData = committedLiveResponse
+ expect(useServers().isLiveAuthoritative).toBe(true)
+
+ capturedHookQueryData = { servers: [...committedLiveResponse.servers].reverse() }
+ expect(useServers().isLiveAuthoritative).toBe(true)
+
+ capturedHookQueryData = { servers: [...committedLiveResponse.servers, {
+ id: "s8",
+ name: "Server 8",
+ discriminator: "0008",
+ icon: null,
+ ownerId: "u1",
+ unread: false,
+ mentions: 0,
+ }] }
+ expect(useServers().isLiveAuthoritative).toBe(false)
+ })
+
+ it("does not confirm live list authority after a transport failure", async () => {
+ useCommunityWsStore.getState().activateProfileAccount("u1")
+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))
+ const { useServers } = await import("./use-servers")
+
+ useServers()
+ await expect(capturedQueryConfig?.queryFn?.()).rejects.toThrow("offline")
+ expect(useServers().isLiveAuthoritative).toBe(false)
+ })
+
it("correlates cold rail unread sources with their attention facets", async () => {
apiFetchMock.mockResolvedValueOnce({ servers: [{
id: "s1",
@@ -180,7 +279,7 @@ describe("useServers / serversQueryFn", () => {
const projection = new AccountUnreadProjection("u1")
projection.setNotificationPolicy({ server: { s1: "mentions" } })
- await serversProjectedQueryFn(projection)()
+ await serversProjectedQueryFn(projection, new QueryClient())()
expect(projection.projectUnread("servers", "attention", false)).toBe(true)
expect(projection.projectUnread("servers", "ordinary", false)).toBe(false)
@@ -189,7 +288,7 @@ describe("useServers / serversQueryFn", () => {
expect(projection.projectUnread("servers", "attention", false)).toBe(false)
})
- it("projects a live unread arrival and preserves unchanged server identity", async () => {
+ it("does not let the legacy unread ledger override canonical attention", async () => {
const changed = {
id: "s1",
unread: false,
@@ -218,10 +317,44 @@ describe("useServers / serversQueryFn", () => {
const result = useServers()
expect(result.servers).not.toBe(raw)
- expect(result.servers[0]).not.toBe(changed)
- expect(result.servers[0]?.unread).toBe(true)
- expect(result.servers[1]).toBe(unchanged)
- expect(result.servers[2]).toBe(legacy)
+ expect(result.servers[0]).toBe(changed)
+ expect(result.servers[0]?.unread).toBe(false)
+ expect(result.servers[1]).not.toBe(unchanged)
+ expect(result.servers[1]).toMatchObject({ unread: false, mentions: 0 })
+ expect(result.servers[2]).not.toBe(legacy)
+ expect(result.servers[2]).toMatchObject({ unread: false, mentions: 0 })
+ })
+
+ it("projects live mention-source evidence onto canonical rail rows", async () => {
+ dbProjection.registry = {}
+ dbProjection.rail = {
+ servers: [{ id: "s1", unread: false, mentions: 1 }],
+ folders: [],
+ }
+ dbProjection.attentionScopes = [{
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ ordinaryUnread: true,
+ attentionCount: 1,
+ }]
+ dbProjection.attentionItems = [{ id: "mention:m1", kind: "mention", scopeId: "c1" }]
+ capturedHookQueryData = {
+ servers: [{
+ id: "s1",
+ unread: true,
+ mentions: 1,
+ unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }],
+ mentionSources: [{ channelId: "c1", count: 1, lastSeq: 4 }],
+ }],
+ }
+ const { useServers } = await import("./use-servers")
+
+ expect(useServers().servers[0]).toMatchObject({
+ id: "s1",
+ unread: true,
+ mentions: 1,
+ })
})
it("returns the frozen empty server list before query data arrives", async () => {
@@ -232,25 +365,25 @@ describe("useServers / serversQueryFn", () => {
expect(first).toEqual([])
})
- it("retains a rolling-deploy rail unread without a source vector", async () => {
+ it("does not retain a legacy rail unread without canonical attention", async () => {
capturedHookQueryData = {
servers: [{ id: "s1", unread: true, mentions: 0 }],
}
const { useServers } = await import("./use-servers")
- expect(useServers().servers[0]?.unread).toBe(true)
+ expect(useServers().servers[0]?.unread).toBe(false)
capturedHookQueryData = {
servers: [{ id: "s1", unread: false, mentions: 0 }],
}
- expect(useServers().servers[0]?.unread).toBe(true)
+ expect(useServers().servers[0]?.unread).toBe(false)
})
- it("hands a rolling-deploy rail unread to exact sources once they arrive", async () => {
+ it("keeps legacy rail source transitions subordinate to canonical attention", async () => {
capturedHookQueryData = {
servers: [{ id: "s1", unread: true, mentions: 0 }],
}
const { useServers } = await import("./use-servers")
- expect(useServers().servers[0]?.unread).toBe(true)
+ expect(useServers().servers[0]?.unread).toBe(false)
capturedHookQueryData = {
servers: [{
@@ -260,7 +393,7 @@ describe("useServers / serversQueryFn", () => {
unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }],
}],
}
- expect(useServers().servers[0]?.unread).toBe(true)
+ expect(useServers().servers[0]?.unread).toBe(false)
const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")
getActiveAccountUnreadProjection(capturedHookQueryClient).acceptPrimarySnapshot({
@@ -375,7 +508,7 @@ describe("useServer / serverQueryFn", () => {
it.each([
["offline", new Error("offline")],
["5xx", new ApiError("unavailable", 503)],
- ])("keeps the structural hint on a transient %s failure", async (_label, error) => {
+ ])("keeps the cached server list on a transient %s failure", async (_label, error) => {
apiFetchMock.mockRejectedValue(error)
const qc = new QueryClient()
qc.setQueryData(communityKeys.servers(), { servers: [{
@@ -386,28 +519,12 @@ describe("useServer / serverQueryFn", () => {
icon: null,
ownerId: "u_1",
}] })
- const hint = {
- schemaVersion: 1 as const,
- accountId: "u_1",
- capturedAt: Date.now(),
- serverOrder: ["srv_1"],
- folders: [],
- servers: [{
- id: "srv_1",
- name: "Alook",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [],
- childRouteHints: [],
- }],
- }
- qc.setQueryData(communityKeys.structuralSnapshot(), hint)
const { serverProjectedQueryFn } = await import("./use-servers")
await expect(serverProjectedQueryFn(qc, "srv_1")()).rejects.toBe(error)
- expect(qc.getQueryData(communityKeys.structuralSnapshot())).toEqual(hint)
+ expect(qc.getQueryData<{ servers: Array<{ id: string }> }>(communityKeys.servers())?.servers)
+ .toEqual([expect.objectContaining({ id: "srv_1" })])
})
it.each([403, 404])("evicts live and persisted server state on definitive %s", async (status) => {
@@ -426,32 +543,15 @@ describe("useServer / serverQueryFn", () => {
name: "Alook",
categories: [],
})
- qc.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "u_1",
- capturedAt: Date.now(),
- serverOrder: ["srv_1"],
- folders: [],
- servers: [{
- id: "srv_1",
- name: "Alook",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [],
- childRouteHints: [],
- }],
- })
const { serverProjectedQueryFn } = await import("./use-servers")
await expect(serverProjectedQueryFn(qc, "srv_1")()).rejects.toMatchObject({ status })
expect(qc.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()
expect(qc.getQueryData<{ servers: unknown[] }>(communityKeys.servers())?.servers).toEqual([])
- expect(qc.getQueryData<{ servers: unknown[] }>(communityKeys.structuralSnapshot())?.servers).toEqual([])
})
- it("merges stale server-detail positives before rejecting the cache write", async () => {
+ it("does not merge stale positives from the retired server unread endpoint", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
if (url.endsWith("/categories")) return { categories: [] }
if (url.endsWith("/channels")) return { channels: [] }
@@ -475,9 +575,10 @@ describe("useServer / serverQueryFn", () => {
const projection = getAccountUnreadProjection(qc, "u1")
const { serverProjectedQueryFn } = await import("./use-servers")
- await expect(serverProjectedQueryFn(qc, "srv_1")()).rejects.toThrow("stale D1 read")
+ await expect(serverProjectedQueryFn(qc, "srv_1")()).resolves.toMatchObject({ id: "srv_1" })
- expect(projection.projectUnread("server-detail:srv_1", "c1", false)).toBe(true)
+ expect(projection.projectUnread("server-detail:srv_1", "c1", false)).toBe(false)
+ expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
it("projects child scope metadata and confirms every loaded channel", async () => {
@@ -538,6 +639,7 @@ describe("useServer / serverQueryFn", () => {
forumUnreadState: {},
}
capturedHookQueryData = detail
+ dbProjection.attentionScopes = [{ scopeId: "c1", channelId: "c1", serverId: "s1", ordinaryUnread: true }]
const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")
getActiveAccountUnreadProjection(capturedHookQueryClient).recordArrival({
channelId: "c1",
@@ -556,7 +658,7 @@ describe("useServer / serverQueryFn", () => {
expect(result.server?.categories[1]?.channels[0]?.unread).toBe(false)
})
- it("retains rolling-deploy server-detail unread rows without source vectors", async () => {
+ it("does not retain rolling-deploy server-detail unread without canonical attention", async () => {
const channel = { id: "c1", unread: true }
const baseUnreadForum = { id: "forum-base", unread: false }
const childUnreadForum = { id: "forum-child", unread: false }
@@ -574,9 +676,9 @@ describe("useServer / serverQueryFn", () => {
capturedHookQueryData = detail
const { useServer } = await import("./use-servers")
const first = useServer("s1")
- expect(first.server?.categories[0]?.channels[0]?.unread).toBe(true)
- expect(first.server?.categories[0]?.channels[1]?.unread).toBe(true)
- expect(first.server?.categories[0]?.channels[2]?.unread).toBe(true)
+ expect(first.server?.categories[0]?.channels[0]?.unread).toBe(false)
+ expect(first.server?.categories[0]?.channels[1]?.unread).toBe(false)
+ expect(first.server?.categories[0]?.channels[2]?.unread).toBe(false)
capturedHookQueryData = {
...detail,
@@ -590,7 +692,7 @@ describe("useServer / serverQueryFn", () => {
}],
}
const second = useServer("s1")
- expect(second.server?.categories[0]?.channels[0]?.unread).toBe(true)
+ expect(second.server?.categories[0]?.channels[0]?.unread).toBe(false)
})
it("composes a single server detail from canonical resources", async () => {
@@ -602,7 +704,6 @@ describe("useServer / serverQueryFn", () => {
{ id: "ch_1", name: "general", categoryId: "cat_1" },
{ id: "ch_2", name: "loose", categoryId: null },
] }
- if (url.endsWith("/unreads")) return { channelIds: ["ch_1"] }
throw new Error(`unexpected ${url}`)
})
const { serverQueryFn } = await import("./use-servers")
@@ -610,11 +711,11 @@ describe("useServer / serverQueryFn", () => {
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.any(Object))
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/categories")
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/channels")
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers/srv_1/unreads")
+ expect(apiFetchMock).not.toHaveBeenCalledWith("/api/community/servers/srv_1/unreads")
expect(data).toEqual({ ...detail, discriminator: "0001", categories: [
- { id: "cat_1", name: "Main", private: 0, channels: [{ id: "ch_1", name: "general", categoryId: "cat_1", active: false, unread: true }] },
+ { id: "cat_1", name: "Main", private: 0, channels: [{ id: "ch_1", name: "general", categoryId: "cat_1", active: false, unread: false }] },
{ id: "__uncategorized__", name: "", private: 0, channels: [{ id: "ch_2", name: "loose", categoryId: null, active: false, unread: false }] },
- ], forumUnreadState: {} })
+ ] })
})
it("passes the navigation AbortSignal to every server-detail resource", async () => {
@@ -630,14 +731,13 @@ describe("useServer / serverQueryFn", () => {
if (url === "/api/community/servers") return { servers: [identity] }
if (url.endsWith("/categories")) return { categories: [] }
if (url.endsWith("/channels")) return { channels: [] }
- if (url.endsWith("/unreads")) return { channelIds: [] }
throw new Error(`unexpected ${url}`)
})
const controller = new AbortController()
const { serverQueryFn } = await import("./use-servers")
await serverQueryFn(new QueryClient(), "srv_signal", controller.signal)()
- for (const path of ["categories", "channels", "unreads"]) {
+ for (const path of ["categories", "channels"]) {
expect(apiFetchMock).toHaveBeenCalledWith(
`/api/community/servers/srv_signal/${path}`,
{ signal: controller.signal },
@@ -671,7 +771,6 @@ describe("useServer / serverQueryFn", () => {
if (url === "/api/community/servers") return { servers: [identity] }
if (url.endsWith("/categories")) return { categories: [] }
if (url.endsWith("/channels")) return { channels: [] }
- if (url.endsWith("/unreads")) return { channelIds: [] }
throw new Error(`unexpected ${url}`)
})
const { serverQueryFn } = await import("./use-servers")
@@ -714,7 +813,6 @@ describe("useServer / serverQueryFn", () => {
apiFetchMock.mockImplementation(async (url: string) => {
if (url.endsWith("/categories")) return { categories: [] }
if (url.endsWith("/channels")) return { channels: [] }
- if (url.endsWith("/unreads")) return { channelIds: [] }
throw new Error(`unexpected ${url}`)
})
const { serverQueryFn } = await import("./use-servers")
@@ -724,10 +822,10 @@ describe("useServer / serverQueryFn", () => {
await expect(serverQueryFn(qc, "srv_1")()).resolves.toMatchObject(identity)
expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/servers")).toHaveLength(0)
- expect(apiFetchMock).toHaveBeenCalledTimes(3)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
})
- it("cold-boots a forum fallback from a canonical unread child outside the sidebar projection", async () => {
+ it("does not cold-boot forum unread from the retired server unread endpoint", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
if (url === "/api/community/servers") return { servers: [{
id: "srv_1", name: "Alook", discriminator: "0001", icon: null, ownerId: "u_1",
@@ -736,20 +834,15 @@ describe("useServer / serverQueryFn", () => {
if (url.endsWith("/channels")) return { channels: [{
id: "forum_1", name: "Forum", type: "forum", categoryId: "cat_1",
}] }
- if (url.endsWith("/unreads")) return {
- channelIds: ["post_hidden"],
- childChannels: [{ id: "post_hidden", parentChannelId: "forum_1" }],
- }
throw new Error(`unexpected ${url}`)
})
const { serverQueryFn } = await import("./use-servers")
const data = await serverQueryFn(new QueryClient(), "srv_1")()
- expect(data.categories[0]?.channels[0]?.unread).toBe(true)
- expect(data.forumUnreadState).toEqual({
- forum_1: { baseUnread: false, childIds: ["post_hidden"] },
- })
+ expect(data.categories[0]?.channels[0]?.unread).toBe(false)
+ expect(data.forumUnreadState).toBeUndefined()
+ expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
it("nests the server(id) key under servers() so prefix invalidation cascades", async () => {
@@ -758,7 +851,6 @@ describe("useServer / serverQueryFn", () => {
if (url === "/api/community/servers") return { servers: [{ ...detail, discriminator: "0001" }] }
if (url.endsWith("/categories")) return { categories: [] }
if (url.endsWith("/channels")) return { channels: [] }
- if (url.endsWith("/unreads")) return { channelIds: [] }
throw new Error(`unexpected ${url}`)
})
const { serverQueryFn } = await import("./use-servers")
@@ -777,19 +869,19 @@ describe("useServer / serverQueryFn", () => {
staleTime: Infinity,
})
expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/servers")).toHaveLength(1)
- expect(apiFetchMock).toHaveBeenCalledTimes(4)
+ expect(apiFetchMock).toHaveBeenCalledTimes(3)
})
- it("rejects a stale raw unread read instead of caching false read badges", async () => {
+ it("does not issue a raw server unread read", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
if (url === "/api/community/servers") return { servers: [{ id: "srv_1", name: "Alook", discriminator: "0001", icon: null, ownerId: "u_1" }] }
if (url.endsWith("/categories")) return { categories: [] }
if (url.endsWith("/channels")) return { channels: [{ id: "ch_1", name: "general", categoryId: null }] }
- if (url.endsWith("/unreads")) return { channelIds: [], stale: true }
throw new Error(`unexpected ${url}`)
})
const { serverQueryFn } = await import("./use-servers")
- await expect(serverQueryFn(new QueryClient(), "srv_1")()).rejects.toThrow("stale D1 read")
+ await expect(serverQueryFn(new QueryClient(), "srv_1")()).resolves.toMatchObject({ id: "srv_1" })
+ expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
})
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 0759238eb..4cc113750 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -19,30 +19,35 @@ import {
type AccountUnreadScope,
type AccountUnreadSource,
} from "./account-unread-projection"
-import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"
-import { reservedUnreadExclusion } from "./unread-presentation"
import { useCommunityWsStore } from "@/stores/community/ws"
import { ApiError } from "@/lib/errors"
import { evictServerChannelScopes } from "./community-ws/scope-eviction"
+import {
+ useAttentionScopes,
+ useOptionalCommunityDbRegistry,
+ useServerRailProjection,
+ useServerTreeProjection,
+} from "@/lib/community-db/projections"
+import {
+ assertCommunityLiveSnapshotTokenCurrent,
+ captureCommunityLiveSnapshotToken,
+ publishCommunityLiveSnapshot,
+ type CommunityLiveSnapshotToken,
+} from "@/lib/community-db/sync"
-function captureStructuralQueryToken() {
- const state = useCommunityWsStore.getState()
- return {
- viewerId: state.profileViewerId,
- accountEpoch: state.profileAccountEpoch,
- accessEpoch: state.accessEpoch,
- }
+type LiveServerListAuthority = CommunityLiveSnapshotToken & {
+ serverIdsSignature: string
+}
+
+const liveServerListAuthority = new WeakMap<QueryClient, LiveServerListAuthority>()
+
+function canonicalServerIdsSignature(servers: readonly Pick<Server, "id">[]) {
+ return JSON.stringify([...new Set(servers.map((server) => server.id))].sort())
}
-function assertStructuralQueryTokenCurrent(
- token: ReturnType<typeof captureStructuralQueryToken>,
-) {
+function currentStructuralQueryGeneration() {
const state = useCommunityWsStore.getState()
- if (
- state.profileViewerId !== token.viewerId
- || state.profileAccountEpoch !== token.accountEpoch
- || state.accessEpoch !== token.accessEpoch
- ) throw new DOMException("Stale structural query", "AbortError")
+ return `${state.profileViewerId ?? ""}:${state.profileAccountEpoch}:${state.accessEpoch}`
}
/**
@@ -124,18 +129,25 @@ function serverListUnreadSources(data: ServersResponse): AccountUnreadSource[] {
export const serversProjectedQueryFn = (
projection: AccountUnreadProjection,
+ queryClient: QueryClient,
+ onLiveSuccess?: (
+ token: CommunityLiveSnapshotToken,
+ data: ServersResponse,
+ signal: AbortSignal | undefined,
+ ) => void,
) => async (context?: QueryFunctionContext) => {
- const structuralToken = captureStructuralQueryToken()
+ const structuralToken = captureCommunityLiveSnapshotToken(queryClient)
const token = projection.beginSnapshot("servers", "channels")
try {
const data = await serversQueryFn(context)
- assertStructuralQueryTokenCurrent(structuralToken)
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, context?.signal)
projection.absorbSnapshot(token, serverListUnreadSources(data), {
confirmedAccessScopes: data.servers.map((server) => ({
kind: "server" as const,
serverId: server.id,
})),
})
+ onLiveSuccess?.(structuralToken, data, context?.signal)
return data
} catch (error) {
projection.cancelSnapshot(token)
@@ -153,15 +165,38 @@ function serversQueryOptions() {
export function useServers(): UseQueryResult<ServersResponse> & {
servers: Server[]
+ isLiveAuthoritative: boolean
} {
+ const registry = useOptionalCommunityDbRegistry()
+ const attentionScopes = useAttentionScopes()
+ const dbRail = useServerRailProjection()
const queryClient = useQueryClient()
+ const structuralGeneration = useSyncExternalStore(
+ useCommunityWsStore.subscribe,
+ currentStructuralQueryGeneration,
+ currentStructuralQueryGeneration,
+ )
const unreadProjection = useMemo(
() => getActiveAccountUnreadProjection(queryClient),
[queryClient],
)
+ const unreadVersion = useSyncExternalStore(
+ unreadProjection.subscribe,
+ unreadProjection.getSnapshot,
+ unreadProjection.getSnapshot,
+ )
const queryFn = useMemo(
- () => serversProjectedQueryFn(unreadProjection),
- [unreadProjection],
+ () => serversProjectedQueryFn(unreadProjection, queryClient, (token, data, signal) => {
+ publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "servers", data },
+ proof: { kind: "structural", token, signal },
+ })
+ liveServerListAuthority.set(queryClient, {
+ ...token,
+ serverIdsSignature: canonicalServerIdsSignature(data.servers),
+ })
+ }),
+ [queryClient, unreadProjection],
)
const query = useQuery({
...serversQueryOptions(),
@@ -178,16 +213,6 @@ export function useServers(): UseQueryResult<ServersResponse> & {
staleTime: Infinity,
refetchOnReconnect: true,
})
- const unreadVersion = useSyncExternalStore(
- unreadProjection.subscribe,
- unreadProjection.getSnapshot,
- unreadProjection.getSnapshot,
- )
- const reservationTarget = useInboxProjectionTarget(queryClient)
- const unreadExclusion = useMemo(
- () => reservedUnreadExclusion(reservationTarget, "channels"),
- [reservationTarget],
- )
useEffect(() => {
if (query.data) {
unreadProjection.mergeSources(
@@ -217,31 +242,43 @@ export function useServers(): UseQueryResult<ServersResponse> & {
}, [query.data, unreadProjection])
const projectedServers = useMemo(() => {
void unreadVersion
- const raw = query.data?.servers
+ const raw = registry
+ ? dbRail?.servers.filter((server) => unreadProjection.allowsAccess({ serverId: server.id }))
+ : query.data?.servers.filter((server) => unreadProjection.allowsAccess({ serverId: server.id }))
if (!raw) return undefined
+ // Canonical rail rows intentionally contain renderable aggregates only.
+ // Keep using the fresh list response as exact source evidence so the
+ // unread projection can reconcile numeric mention badges by channel.
+ const liveEvidenceByServer = new Map(
+ query.data?.servers.map((server) => [server.id, server]) ?? [],
+ )
let changed = false
const projected = raw.map((server) => {
- const unread = unreadProjection.projectServerUnread(
- server.id,
- server.unreadSources ?? [],
- server.unread,
- unreadExclusion,
- )
- const mentions = unreadProjection.projectServerMentionCount(
- server.id,
- server.mentionSources ?? [],
- server.mentions,
- unreadExclusion,
- )
+ const liveEvidence = liveEvidenceByServer.get(server.id)
+ void liveEvidence
+ const serverScopes = attentionScopes.filter((scope) => scope.serverId === server.id)
+ const unread = serverScopes.some((scope) => scope.ordinaryUnread)
+ const mentions = serverScopes.reduce((total, scope) => total + (scope.attentionCount ?? 0), 0)
if (unread === server.unread && mentions === server.mentions) return server
changed = true
return { ...server, unread, mentions }
})
return changed ? projected : raw
- }, [query.data, unreadExclusion, unreadProjection, unreadVersion])
+ }, [attentionScopes, dbRail?.servers, query.data, registry, unreadProjection, unreadVersion])
return {
...query,
servers: projectedServers ?? (EMPTY_SERVERS as Server[]),
+ isLiveAuthoritative: (() => {
+ void structuralGeneration
+ const authority = liveServerListAuthority.get(queryClient)
+ const state = useCommunityWsStore.getState()
+ return authority?.viewerId === state.profileViewerId
+ && authority.accountEpoch === state.profileAccountEpoch
+ && authority.accessEpoch === state.accessEpoch
+ && authority.serverIdsSignature === canonicalServerIdsSignature(
+ projectedServers ?? EMPTY_SERVERS,
+ )
+ })(),
}
}
@@ -273,22 +310,6 @@ type ForumUnreadState = Record<string, {
}>
type RawChannel = Channel & { categoryId: string | null }
-type UnreadResponse = {
- stale?: boolean
- channelIds: string[]
- sources?: Array<{
- channelId: string
- lastUnreadSeq: number
- lastAttentionSeq: number | null
- }>
- childChannels?: Array<{
- id: string
- parentChannelId: string
- lastUnreadSeq?: number
- lastAttentionSeq?: number | null
- }>
-}
-
async function resolveServerIdentity(
queryClient: QueryClient,
serverId: string,
@@ -301,78 +322,37 @@ async function resolveServerIdentity(
const fetched = await serversProjectedQueryFn(
getActiveAccountUnreadProjection(queryClient),
+ queryClient,
+ (_token, data) => {
+ publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "servers", data },
+ proof: { kind: "structural", token: _token, signal },
+ })
+ },
)({ signal } as QueryFunctionContext)
return fetched.servers.find((server) => server.id === serverId)
}
-function serverDetailUnreadSources(
- serverId: string,
- unreadData: UnreadResponse,
-): AccountUnreadSource[] {
- const parentByChild = new Map(
- (unreadData.childChannels ?? []).map((child) => [child.id, child.parentChannelId]),
- )
- return (unreadData.sources ?? []).flatMap((source) => [
- {
- channelId: source.channelId,
- lastUnreadSeq: source.lastUnreadSeq,
- serverId,
- railChannelId: parentByChild.get(source.channelId),
- },
- ...(source.lastAttentionSeq == null ? [] : [{
- channelId: source.channelId,
- lastUnreadSeq: source.lastAttentionSeq,
- lastMentionSeq: source.lastAttentionSeq,
- serverId,
- railChannelId: parentByChild.get(source.channelId),
- isMention: true,
- }]),
- ])
-}
-
export const serverQueryFn = (
queryClient: QueryClient,
serverId: string,
signal?: AbortSignal,
- options: { onUnreadResponse?: (data: UnreadResponse) => void } = {},
) => async (): Promise<ServerDetail> => {
const fetchResource = <T,>(path: string) => signal
? apiFetch<T>(path, { signal })
: apiFetch<T>(path)
- const [server, categoryData, channelData, unreadData] = await Promise.all([
+ const [server, categoryData, channelData] = await Promise.all([
resolveServerIdentity(queryClient, serverId, signal),
fetchResource<{ categories: Array<Omit<Category, "channels"> & { serverId?: string }> }>(`/api/community/servers/${serverId}/categories`),
fetchResource<{ channels: RawChannel[] }>(`/api/community/servers/${serverId}/channels`),
- fetchResource<UnreadResponse>(`/api/community/servers/${serverId}/unreads`),
])
- options.onUnreadResponse?.(unreadData)
- if (unreadData.stale) throw new Error("stale D1 read")
if (!server) throw new Error("server not found")
- const unreadIds = new Set(unreadData.channelIds)
- const forumParentIds = new Set(
- channelData.channels.filter((channel) => channel.type === "forum").map((channel) => channel.id),
- )
- const forumUnreadState: ForumUnreadState = Object.fromEntries(
- [...forumParentIds].map((parentChannelId) => [parentChannelId, {
- baseUnread: unreadIds.has(parentChannelId),
- childIds: (unreadData.childChannels ?? [])
- .filter((child) => child.parentChannelId === parentChannelId)
- .map((child) => child.id),
- }]),
- )
- const channels = channelData.channels.map((channel) => {
- const forumUnread = forumUnreadState[channel.id]
- return {
- ...channel,
- active: false,
- // Until the sidebar projection arrives, every canonical unread child is
- // necessarily hidden. Its parent owns the cold-boot fallback dot; the
- // sidebar hook migrates loaded children to their own rows immediately.
- unread: forumUnread
- ? forumUnread.baseUnread || forumUnread.childIds.length > 0
- : unreadIds.has(channel.id),
- }
- })
+ const channels = channelData.channels.map((channel) => ({
+ ...channel,
+ active: false,
+ // Visible unread state is projected exclusively from account attention.
+ unread: false,
+ }))
const categories: Category[] = categoryData.categories.map((category) => ({
...category,
channels: channels.filter((channel) => channel.categoryId === category.id),
@@ -390,8 +370,6 @@ export const serverQueryFn = (
official: server.official === true,
ownerId: server.ownerId ?? "",
categories,
- forumUnreadState,
- ...(unreadData.sources ? { unreadSources: unreadData.sources } : {}),
}
}
@@ -400,19 +378,13 @@ export const serverProjectedQueryFn = (
serverId: string,
signal?: AbortSignal,
) => async () => {
- const structuralToken = captureStructuralQueryToken()
+ const structuralToken = captureCommunityLiveSnapshotToken(queryClient)
const projection = getActiveAccountUnreadProjection(queryClient)
const family = `server-detail:${serverId}` as const
const token = projection.beginSnapshot(family, "channels")
- let unreadData: UnreadResponse | undefined
try {
- const data = await serverQueryFn(queryClient, serverId, signal, {
- onUnreadResponse: (response) => {
- unreadData = response
- },
- })()
- assertStructuralQueryTokenCurrent(structuralToken)
- if (!unreadData) throw new Error("server unread response missing")
+ const data = await serverQueryFn(queryClient, serverId, signal)()
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, signal)
const confirmedAccessScopes: AccountUnreadScope[] = [
{ kind: "server", serverId },
...data.categories.flatMap((category) => category.channels.map((channel) => ({
@@ -422,20 +394,16 @@ export const serverProjectedQueryFn = (
]
projection.absorbSnapshot(
token,
- serverDetailUnreadSources(serverId, unreadData),
- { stale: unreadData.stale, confirmedAccessScopes },
+ [],
+ { confirmedAccessScopes },
)
+ publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "server-detail", data },
+ proof: { kind: "structural", token: structuralToken, signal },
+ })
return data
} catch (error) {
- if (unreadData) {
- projection.absorbSnapshot(
- token,
- serverDetailUnreadSources(serverId, unreadData),
- { stale: true },
- )
- } else {
- projection.cancelSnapshot(token)
- }
+ projection.cancelSnapshot(token)
if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {
evictServerChannelScopes(queryClient, serverId)
}
@@ -451,21 +419,14 @@ export const serverProjectedQueryFn = (
export function useServer(
serverId: string | null,
): UseQueryResult<ServerDetail> & { server: ServerDetail | null } {
+ const registry = useOptionalCommunityDbRegistry()
+ const attentionScopes = useAttentionScopes()
+ const dbServer = useServerTreeProjection(serverId)
const queryClient = useQueryClient()
const unreadProjection = useMemo(
() => getActiveAccountUnreadProjection(queryClient),
[queryClient],
)
- const unreadVersion = useSyncExternalStore(
- unreadProjection.subscribe,
- unreadProjection.getSnapshot,
- unreadProjection.getSnapshot,
- )
- const reservationTarget = useInboxProjectionTarget(queryClient)
- const unreadExclusion = useMemo(
- () => reservedUnreadExclusion(reservationTarget, "channels"),
- [reservationTarget],
- )
const enabled = !!serverId
const queryFn = useMemo(() => {
if (!serverId) return () => Promise.reject(new Error("disabled"))
@@ -520,30 +481,17 @@ export function useServer(
)
}, [query.data, serverId, unreadProjection])
const projectedServer = useMemo(() => {
- void unreadVersion
- if (!query.data || !serverId) return null
- const sourceByChannel = new Map(
- (query.data.unreadSources ?? []).map((source) => [source.channelId, source]),
- )
+ const source = registry ? dbServer : query.data
+ if (!source || !serverId) return null
let changed = false
- const categories = query.data.categories.map((category) => {
+ const categories = source.categories.map((category) => {
let categoryChanged = false
const channels = category.channels.map((channel) => {
- const forum = query.data?.forumUnreadState?.[channel.id]
- const sourceIds = forum
- ? [channel.id, ...forum.childIds]
- : [channel.id]
- const sources = sourceIds.flatMap((id) => {
- const source = sourceByChannel.get(id)
- return source ? [source] : []
- })
- const unread = unreadProjection.projectServerChannelUnread(
- serverId,
- channel.id,
- sources,
- channel.unread,
- unreadExclusion,
- )
+ const unread = attentionScopes.some((scope) => (
+ scope.serverId === serverId
+ && (scope.channelId === channel.id || scope.parentChannelId === channel.id)
+ && scope.ordinaryUnread
+ ))
if (unread === channel.unread) return channel
categoryChanged = true
return { ...channel, unread }
@@ -552,8 +500,8 @@ export function useServer(
changed = true
return { ...category, channels }
})
- return changed ? { ...query.data, categories } : query.data
- }, [query.data, unreadExclusion, serverId, unreadProjection, unreadVersion])
+ return changed ? { ...source, categories } : source
+ }, [attentionScopes, dbServer, query.data, registry, serverId])
return {
...query,
server: query.error instanceof ApiError
diff --git a/src/web/src/hooks/community/use-structural-snapshot.test.ts b/src/web/src/hooks/community/use-structural-snapshot.test.ts
deleted file mode 100644
index 0d5ea05e6..000000000
--- a/src/web/src/hooks/community/use-structural-snapshot.test.ts
+++ /dev/null
@@ -1,373 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest"
-import { QueryClient } from "@tanstack/react-query"
-import { communityKeys } from "@/lib/query-keys"
-import type { ServerDetail, ServersResponse } from "./use-servers"
-import type { FoldersResponse } from "./use-folders"
-import { useCommunityWsStore } from "@/stores/community/ws"
-import {
- hasStructuralServerTree,
- installStructuralSnapshotProjection,
- structuralHintServer,
-} from "./use-structural-snapshot"
-
-function servers(name = "Alpha"): ServersResponse {
- return {
- servers: [{
- id: "server-1",
- name,
- discriminator: "0001",
- icon: null,
- initial: "A",
- active: false,
- unread: true,
- mentions: 4,
- ownerId: "owner-1",
- isOwner: true,
- }],
- }
-}
-
-describe("installStructuralSnapshotProjection", () => {
- let queryClient: QueryClient
- let dispose: () => void
-
- beforeEach(() => {
- useCommunityWsStore.getState().reset()
- useCommunityWsStore.getState().activateProfileAccount("account-a")
- queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- dispose = installStructuralSnapshotProjection(queryClient, "account-a")
- })
-
- afterEach(() => {
- dispose()
- queryClient.clear()
- useCommunityWsStore.getState().reset()
- })
-
- it("projects authoritative server, folder, tree, and child query success", async () => {
- await queryClient.fetchQuery({
- queryKey: communityKeys.servers(),
- queryFn: () => Promise.resolve(servers()),
- })
- const folders: FoldersResponse = {
- folders: [{
- id: "folder-1",
- name: "Work",
- position: 0,
- servers: [{ id: "server-1", name: "Alpha", initial: "A", icon: null }],
- }],
- }
- await queryClient.fetchQuery({
- queryKey: communityKeys.folders(),
- queryFn: () => Promise.resolve(folders),
- })
- const detail = {
- id: "server-1",
- name: "Alpha",
- discriminator: "0001",
- description: "not persisted",
- icon: null,
- ownerId: "owner-1",
- categories: [{
- id: "category-1",
- name: "General",
- private: 1,
- creatorId: "creator-1",
- channels: [{
- id: "channel-1",
- name: "chat",
- type: "text",
- active: false,
- unread: true,
- creatorId: "creator-1",
- }],
- }],
- } satisfies ServerDetail
- await queryClient.fetchQuery({
- queryKey: communityKeys.server("server-1"),
- queryFn: () => Promise.resolve(detail),
- })
- await queryClient.fetchQuery({
- queryKey: communityKeys.channelMeta("server-1", "child-1"),
- queryFn: () => Promise.resolve({
- id: "child-1",
- serverId: "server-1",
- name: "Thread",
- type: "thread",
- parentChannelId: "channel-1",
- parentMessageId: "message-1",
- creatorId: "creator-1",
- archived: false,
- lastMessageAt: null,
- createdAt: "2026-09-08T00:00:00.000Z",
- verifiedEpoch: 0,
- }),
- })
-
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toMatchObject({
- accountId: "account-a",
- serverOrder: ["server-1"],
- folders: [{ id: "folder-1", name: "Work", serverIds: ["server-1"] }],
- servers: [{
- id: "server-1",
- categories: [{ id: "category-1", name: "General", private: true }],
- channels: [{ id: "channel-1", name: "chat", type: "text", categoryId: "category-1" }],
- childRouteHints: [{
- id: "child-1",
- name: "Thread",
- type: "thread",
- parentChannelId: "channel-1",
- parentMessageId: "message-1",
- }],
- }],
- })
- })
-
- it("replays cached folder, tree, and child successes when the server list arrives last", async () => {
- await queryClient.fetchQuery({
- queryKey: communityKeys.folders(),
- queryFn: () => Promise.resolve({
- folders: [{
- id: "folder-1",
- name: "Work",
- position: 0,
- servers: [{ id: "server-1", name: "Alpha", initial: "A", icon: null }],
- }],
- } satisfies FoldersResponse),
- })
- await queryClient.fetchQuery({
- queryKey: communityKeys.server("server-1"),
- queryFn: () => Promise.resolve({
- id: "server-1",
- name: "Alpha",
- discriminator: "0001",
- description: "private live description",
- icon: null,
- ownerId: "owner-1",
- categories: [{
- id: "category-1",
- name: "General",
- private: 0,
- channels: [{
- id: "channel-1",
- name: "chat",
- type: "text",
- active: false,
- unread: false,
- }],
- }],
- } satisfies ServerDetail),
- })
- await queryClient.fetchQuery({
- queryKey: communityKeys.channelMeta("server-1", "child-1"),
- queryFn: () => Promise.resolve({
- id: "child-1",
- serverId: "server-1",
- name: "Thread",
- type: "thread",
- parentChannelId: "channel-1",
- parentMessageId: "message-1",
- creatorId: "creator-1",
- archived: false,
- lastMessageAt: null,
- createdAt: "2026-09-08T00:00:00.000Z",
- verifiedEpoch: 0,
- }),
- })
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()
-
- await queryClient.fetchQuery({
- queryKey: communityKeys.servers(),
- queryFn: () => Promise.resolve(servers()),
- })
-
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toMatchObject({
- folders: [{ id: "folder-1", serverIds: ["server-1"] }],
- servers: [{
- id: "server-1",
- categories: [{ id: "category-1" }],
- channels: [{ id: "channel-1" }],
- childRouteHints: [{ id: "child-1" }],
- }],
- })
- })
-
- it("ignores manual optimistic cache writes", async () => {
- await queryClient.fetchQuery({
- queryKey: communityKeys.servers(),
- queryFn: () => Promise.resolve(servers()),
- })
- queryClient.setQueryData(communityKeys.servers(), servers("Optimistic"))
- expect(queryClient.getQueryData<{ servers: Array<{ name: string }> }>(
- communityKeys.structuralSnapshot(),
- )?.servers[0]?.name).toBe("Alpha")
- })
-
- it("rejects projection after the active account changes", async () => {
- useCommunityWsStore.getState().activateProfileAccount("account-b")
- await queryClient.fetchQuery({
- queryKey: communityKeys.servers(),
- queryFn: () => Promise.resolve(servers()),
- })
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()
- })
-
- it("removes a malformed restored snapshot", () => {
- dispose()
- queryClient.setQueryData(communityKeys.structuralSnapshot(), {
- schemaVersion: 1,
- accountId: "account-a",
- capturedAt: Date.now(),
- serverOrder: [],
- folders: [],
- servers: [],
- role: "owner",
- })
- dispose = installStructuralSnapshotProjection(queryClient, "account-a")
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()
- })
-
- it("removes structural state for an anonymous account", () => {
- queryClient.setQueryData(communityKeys.structuralSnapshot(), { unsafe: true })
- dispose()
- dispose = installStructuralSnapshotProjection(queryClient, null)
-
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()
- })
-
- it("rejects malformed data that is already present when a query is added", () => {
- queryClient.getQueryCache().build(
- queryClient,
- { queryKey: communityKeys.structuralSnapshot() },
- { data: { unsafe: true } } as never,
- )
-
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()
- })
-
- it("projects successful cache entries that predate projection installation", () => {
- dispose()
- queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- queryClient.setQueryData(communityKeys.servers(), servers("Cached"))
-
- dispose = installStructuralSnapshotProjection(queryClient, "account-a")
-
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toMatchObject({
- accountId: "account-a",
- servers: [{ id: "server-1", name: "Cached" }],
- })
- })
-
- it("does not project reserved server query keys as server trees", async () => {
- await queryClient.fetchQuery({
- queryKey: communityKeys.servers(),
- queryFn: () => Promise.resolve(servers()),
- })
- const snapshot = queryClient.getQueryData(communityKeys.structuralSnapshot())
-
- await queryClient.fetchQuery({
- queryKey: communityKeys.channelRefDirectory(),
- queryFn: () => Promise.resolve({ servers: [] }),
- })
- await queryClient.fetchQuery({
- queryKey: communityKeys.server("__none__"),
- queryFn: () => Promise.resolve({ sentinel: true }),
- })
-
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toEqual(snapshot)
- })
-
- it("removes an archived child receipt from the structural snapshot", async () => {
- await queryClient.fetchQuery({
- queryKey: communityKeys.servers(),
- queryFn: () => Promise.resolve(servers()),
- })
- await queryClient.fetchQuery({
- queryKey: communityKeys.server("server-1"),
- queryFn: () => Promise.resolve({
- id: "server-1",
- name: "Alpha",
- discriminator: "0001",
- description: "",
- icon: null,
- ownerId: "owner-1",
- categories: [{
- id: "category-1",
- name: "General",
- private: 0,
- channels: [{
- id: "channel-1",
- name: "chat",
- type: "text",
- active: false,
- unread: false,
- }],
- }],
- } satisfies ServerDetail),
- })
- queryClient.setQueryData(communityKeys.structuralSnapshot(), (current: any) => ({
- ...current,
- servers: current.servers.map((server: any) => ({
- ...server,
- childRouteHints: [{
- id: "child-1",
- name: "Thread",
- type: "thread",
- parentChannelId: "channel-1",
- parentMessageId: "message-1",
- }],
- })),
- }))
- await queryClient.fetchQuery({
- queryKey: communityKeys.channelMeta("server-1", "child-1"),
- queryFn: () => Promise.resolve({
- id: "child-1",
- serverId: "server-1",
- name: "Thread",
- type: "thread",
- parentChannelId: "channel-1",
- parentMessageId: "message-1",
- archived: true,
- }),
- })
-
- expect(queryClient.getQueryData<any>(
- communityKeys.structuralSnapshot(),
- ).servers[0].childRouteHints).toEqual([])
- })
-
- it("projects and misses structural server hints explicitly", () => {
- const snapshot = {
- schemaVersion: 1 as const,
- accountId: "account-a",
- capturedAt: Date.now(),
- serverOrder: ["server-1"],
- folders: [],
- servers: [{
- id: "server-1",
- name: "Alpha",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [],
- childRouteHints: [],
- }],
- }
-
- expect(structuralHintServer(snapshot, "server-1")).toMatchObject({
- id: "server-1",
- categoriesView: [],
- })
- expect(hasStructuralServerTree(snapshot.servers[0])).toBe(false)
- expect(hasStructuralServerTree({
- ...snapshot.servers[0],
- categories: [{ id: "category-1", name: "General", private: false }],
- })).toBe(true)
- expect(hasStructuralServerTree({
- ...snapshot.servers[0],
- channels: [{ id: "channel-1", name: "chat", type: "text" as const, categoryId: null }],
- })).toBe(true)
- expect(structuralHintServer(snapshot, "missing")).toBeNull()
- expect(structuralHintServer(null, "server-1")).toBeNull()
- })
-})
diff --git a/src/web/src/hooks/community/use-structural-snapshot.ts b/src/web/src/hooks/community/use-structural-snapshot.ts
deleted file mode 100644
index 9275bf03d..000000000
--- a/src/web/src/hooks/community/use-structural-snapshot.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-"use client"
-
-import { useCallback, useMemo, useSyncExternalStore } from "react"
-import { useQueryClient, type QueryClient, type QueryKey } from "@tanstack/react-query"
-import {
- communityKeys,
- isCommunityServerDetailQueryKey,
-} from "@/lib/query-keys"
-import {
- parseStructuralSnapshot,
- projectServerDetailTree,
- structuralServerToCategories,
- type StructuralSnapshotV1,
- type StructuralServerV1,
- updateStructuralSnapshot,
-} from "@/lib/community/structural-snapshot"
-import { useCommunityWsStore } from "@/stores/community/ws"
-import type { ServersResponse, ServerDetail } from "./use-servers"
-import type { FoldersResponse } from "./use-folders"
-import type { ChannelMetadata } from "./channel-metadata"
-
-function sameKey(left: QueryKey, right: QueryKey): boolean {
- return left.length === right.length
- && left.every((value, index) => value === right[index])
-}
-
-function projectLiveStructuralQuery(
- queryClient: QueryClient,
- accountId: string,
- key: QueryKey,
- data: unknown,
-): void {
- if (useCommunityWsStore.getState().profileViewerId !== accountId) return
- if (sameKey(key, communityKeys.servers())) {
- const response = data as ServersResponse
- updateStructuralSnapshot(queryClient, {
- type: "replaceServers",
- accountId,
- servers: response.servers.map((server) => ({
- id: server.id,
- name: server.name,
- discriminator: server.discriminator ?? "",
- icon: server.icon ?? null,
- })),
- })
- const folders = queryClient.getQueryData<FoldersResponse>(communityKeys.folders())
- if (folders) {
- projectLiveStructuralQuery(
- queryClient,
- accountId,
- communityKeys.folders(),
- folders,
- )
- }
- for (const server of response.servers) {
- const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(server.id))
- if (detail) {
- projectLiveStructuralQuery(
- queryClient,
- accountId,
- communityKeys.server(server.id),
- detail,
- )
- }
- }
- return
- }
- if (sameKey(key, communityKeys.folders())) {
- const response = data as FoldersResponse
- updateStructuralSnapshot(queryClient, {
- type: "replaceFolders",
- folders: response.folders.map((folder) => ({
- id: folder.id,
- name: folder.name,
- serverIds: folder.servers.map((server) => server.id),
- })),
- })
- return
- }
- if (isCommunityServerDetailQueryKey(key)) {
- const serverId = key[2]
- const tree = projectServerDetailTree(data as ServerDetail)
- updateStructuralSnapshot(queryClient, {
- type: "replaceServerTree",
- serverId,
- ...tree,
- })
- for (const [metaKey, meta] of queryClient.getQueriesData<ChannelMetadata & { archived: boolean }>({
- queryKey: communityKeys.channelMetaRoot(serverId),
- })) {
- if (meta) projectLiveStructuralQuery(queryClient, accountId, metaKey, meta)
- }
- return
- }
- if (
- key.length === 5
- && key[0] === "community"
- && key[1] === "servers"
- && key[3] === "channel-meta"
- ) {
- const meta = data as ChannelMetadata & { archived: boolean }
- if (meta.type !== "thread" || !meta.parentChannelId || !meta.parentMessageId) return
- if (meta.archived) {
- updateStructuralSnapshot(queryClient, {
- type: "removeChildHint",
- serverId: meta.serverId,
- channelId: meta.id,
- })
- return
- }
- updateStructuralSnapshot(queryClient, {
- type: "upsertChildHint",
- serverId: meta.serverId,
- child: {
- id: meta.id,
- name: meta.name,
- type: "thread",
- parentChannelId: meta.parentChannelId,
- parentMessageId: meta.parentMessageId,
- },
- })
- }
-}
-
-export function installStructuralSnapshotProjection(
- queryClient: QueryClient,
- accountId: string | null,
-): () => void {
- if (!accountId) {
- queryClient.removeQueries({ queryKey: communityKeys.structuralSnapshot(), exact: true })
- return () => {}
- }
- const existing = queryClient.getQueryData(communityKeys.structuralSnapshot())
- if (existing !== undefined && !parseStructuralSnapshot(existing, accountId)) {
- queryClient.removeQueries({ queryKey: communityKeys.structuralSnapshot(), exact: true })
- }
- const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
- if (event.type === "added" && sameKey(event.query.queryKey, communityKeys.structuralSnapshot())) {
- if (
- event.query.state.data !== undefined
- && !parseStructuralSnapshot(event.query.state.data, accountId)
- ) {
- queryClient.removeQueries({ queryKey: communityKeys.structuralSnapshot(), exact: true })
- }
- return
- }
- if (event.type !== "updated") return
- if (event.action.type !== "success" || event.action.manual) return
- projectLiveStructuralQuery(
- queryClient,
- accountId,
- event.query.queryKey,
- event.query.state.data,
- )
- })
- for (const query of queryClient.getQueryCache().getAll()) {
- if (query.state.status === "success") {
- projectLiveStructuralQuery(queryClient, accountId, query.queryKey, query.state.data)
- }
- }
- return unsubscribe
-}
-
-export function useStructuralSnapshot(
- accountId: string | null,
- providedQueryClient?: QueryClient,
-): StructuralSnapshotV1 | null {
- const queryClient = useQueryClient(providedQueryClient)
- const getSnapshot = useCallback(
- () => queryClient.getQueryData<unknown>(communityKeys.structuralSnapshot()),
- [queryClient],
- )
- const subscribe = useCallback((notify: () => void) => {
- const cache = queryClient.getQueryCache?.()
- if (!cache) return () => {}
- return cache.subscribe((event) => {
- if (sameKey(event.query.queryKey, communityKeys.structuralSnapshot())) notify()
- })
- }, [queryClient])
- const data = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
- return useMemo(
- () => accountId ? parseStructuralSnapshot(data, accountId) : null,
- [accountId, data],
- )
-}
-
-export function structuralHintServer(
- snapshot: StructuralSnapshotV1 | null,
- serverId: string,
-): (StructuralServerV1 & { categoriesView: ReturnType<typeof structuralServerToCategories> }) | null {
- const server = snapshot?.servers.find((candidate) => candidate.id === serverId)
- return server ? { ...server, categoriesView: structuralServerToCategories(server) } : null
-}
-
-/** A rail-only Server identity is not enough to initialize a Channel Tree. */
-export function hasStructuralServerTree(
- server: Pick<StructuralServerV1, "categories" | "channels"> | null | undefined,
-): boolean {
- return Boolean(server && (server.categories.length > 0 || server.channels.length > 0))
-}
diff --git a/src/web/src/hooks/community/use-thread-participants.test.ts b/src/web/src/hooks/community/use-thread-participants.test.ts
index 4cc38c02c..35d9e8d3e 100644
--- a/src/web/src/hooks/community/use-thread-participants.test.ts
+++ b/src/web/src/hooks/community/use-thread-participants.test.ts
@@ -5,6 +5,16 @@ import {
disposeAccountUnreadProjection,
getAccountUnreadProjection,
} from "./account-unread-projection"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import {
+ captureCommunityLiveSnapshotToken,
+ publishCommunityForumSidebar,
+} from "@/lib/community-db/sync"
+import { getForumSidebarBase } from "./use-forum-sidebar-threads"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -18,6 +28,8 @@ type MutationConfig = {
let config: MutationConfig
let queryClient: QueryClient
+let registry: CommunityDbRegistry
+let unregister: () => void
vi.mock("@tanstack/react-query", async () => {
const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
return {
@@ -48,14 +60,19 @@ function sidebarData() {
}
}
-beforeEach(() => {
+beforeEach(async () => {
apiFetchMock.mockReset()
apiFetchMock.mockResolvedValue(undefined)
queryClient = new QueryClient()
+ registry = createCommunityDbRegistry(queryClient, "viewer_1")
+ await registry.preload()
+ unregister = registerCommunityDbRegistry(registry)
})
-afterEach(() => {
+afterEach(async () => {
disposeAccountUnreadProjection(queryClient)
+ unregister()
+ await registry.cleanup()
queryClient.clear()
})
@@ -64,6 +81,19 @@ describe("useRemoveThreadParticipant", () => {
const key = communityKeys.forumSidebarThreads("server_1")
const metaKey = communityKeys.channelMeta("server_1", "post_1")
queryClient.setQueryData(key, sidebarData())
+ publishCommunityForumSidebar(queryClient, {
+ serverId: "server_1",
+ channels: [{
+ id: "post_1", name: "Post", parentChannelId: "forum_1",
+ parentMessageId: "opener_1", activityAt: "2026-08-08T00:00:00.000Z",
+ unread: false, type: "thread",
+ }],
+ openers: [{ id: "opener_1", channelId: "forum_1", content: "Post", type: "chat" }],
+ proof: {
+ token: captureCommunityLiveSnapshotToken(queryClient),
+ signal: undefined,
+ },
+ })
queryClient.setQueryData(metaKey, { id: "post_1", parentChannelId: "forum_1" })
const unreadProjection = getAccountUnreadProjection(queryClient, "viewer_1")
unreadProjection.recordArrival({
@@ -81,7 +111,11 @@ describe("useRemoveThreadParticipant", () => {
"/api/community/channels/post_1/participants/viewer_1",
{ method: "DELETE" },
)
- expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toEqual([])
+ expect(getForumSidebarBase(queryClient, "server_1").threads).toHaveLength(0)
+ expect(registry.collections.channelMemberships.get("post_1:viewer_1:access"))
+ .toBeDefined()
+ expect(registry.collections.channelMemberships.get("post_1:viewer_1:notify"))
+ .toBeUndefined()
expect(queryClient.getQueryData(metaKey)).toEqual({ id: "post_1", parentChannelId: "forum_1" })
expect(unreadProjection.projectUnread("inbox-unreads", "post_1", false, 7)).toBe(false)
})
diff --git a/src/web/src/hooks/community/ws-live-query-config.test.ts b/src/web/src/hooks/community/ws-live-query-config.test.ts
index 709650f50..323f3e06e 100644
--- a/src/web/src/hooks/community/ws-live-query-config.test.ts
+++ b/src/web/src/hooks/community/ws-live-query-config.test.ts
@@ -57,6 +57,13 @@ vi.mock("@/lib/api/client", () => ({
apiFetch: vi.fn(() => Promise.resolve({})),
toastApiError: vi.fn(),
}))
+vi.mock("@/lib/community-db/projections", () => ({
+ useOptionalCommunityDbRegistry: () => null,
+ useAttentionScopes: () => [],
+ useAttentionItems: () => [],
+ useServerRailProjection: () => undefined,
+ useServerTreeProjection: () => undefined,
+}))
function configFor(keyIncludes: string) {
return queryConfigs.find((c) => JSON.stringify(c.queryKey).includes(keyIncludes))
diff --git a/src/web/src/instrumentation-client.test.ts b/src/web/src/instrumentation-client.test.ts
new file mode 100644
index 000000000..bbab377a2
--- /dev/null
+++ b/src/web/src/instrumentation-client.test.ts
@@ -0,0 +1,25 @@
+import { beforeEach, expect, it, vi } from "vitest"
+
+const installReactScanMock = vi.fn()
+
+vi.mock("@/lib/perf/react-scan-install", () => ({
+ installReactScan: installReactScanMock,
+}))
+
+beforeEach(() => {
+ vi.resetModules()
+ installReactScanMock.mockReset()
+})
+
+it("starts optional client diagnostics without making app boot await them", async () => {
+ let rejectInstall!: (error: Error) => void
+ installReactScanMock.mockReturnValue(new Promise<void>((_resolve, reject) => {
+ rejectInstall = reject
+ }))
+
+ await expect(import("./instrumentation-client")).resolves.toBeDefined()
+ expect(installReactScanMock).toHaveBeenCalledOnce()
+
+ rejectInstall(new Error("diagnostics unavailable"))
+ await Promise.resolve()
+})
diff --git a/src/web/src/instrumentation-client.ts b/src/web/src/instrumentation-client.ts
index 8dfb810e2..590e546b4 100644
--- a/src/web/src/instrumentation-client.ts
+++ b/src/web/src/instrumentation-client.ts
@@ -1,7 +1,7 @@
// Next.js client instrumentation entry — runs before the app hydrates, i.e.
// before react-dom installs its DevTools global hook. This is the ONLY place
// early enough to register react-scan's instrument() and capture the initial
-// mount (see plans/community-switch-perf-diagnosis.md).
+// mount.
//
// Distinct from the server-side `instrumentation.ts` `register()` hook — do not
// conflate them. This file is diagnosis-only and self-noops unless
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index 65c7a621b..46bf129ca 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -93,6 +93,11 @@ function makeEnvBase() {
function makeEnv(overrides: Partial<Record<string, unknown>> = {}) {
return {
...makeEnvBase(),
+ CF_VERSION_METADATA: {
+ id: "version-a",
+ tag: "",
+ timestamp: "2026-09-26T00:00:00.000Z",
+ },
DB: {},
EMAIL_BUCKET: {},
WS_DO_WORKER: {},
@@ -175,6 +180,72 @@ async function loadCreateAuth() {
return mod.createAuth
}
+async function loadAuthModule() {
+ vi.resetModules()
+ return import("./auth")
+}
+
+describe("getAuth lifecycle", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it("reuses one version instance across fresh DB and service binding wrappers", async () => {
+ const { getAuth } = await loadAuthModule()
+ const first = getAuth(makeEnv({
+ DB: { request: 1 },
+ EMAIL_WORKER: { fetch: vi.fn() },
+ }) as never)
+ const second = getAuth(makeEnv({
+ DB: { request: 2 },
+ EMAIL_WORKER: { fetch: vi.fn() },
+ }) as never)
+
+ expect(second).toBe(first)
+ })
+
+ it("rebuilds when the Worker version and binding generation changes", async () => {
+ const { getAuth } = await loadAuthModule()
+ const first = getAuth(makeEnv({
+ CF_VERSION_METADATA: { id: "version-a", tag: "", timestamp: "a" },
+ DB: { generation: "a" },
+ EMAIL_WORKER: { fetch: vi.fn() },
+ }) as never)
+ const second = getAuth(makeEnv({
+ CF_VERSION_METADATA: { id: "version-b", tag: "", timestamp: "b" },
+ DB: { generation: "b" },
+ EMAIL_WORKER: { fetch: vi.fn() },
+ }) as never)
+
+ expect(second).not.toBe(first)
+ })
+
+ it("does not reuse an instance in production without version metadata", async () => {
+ const { getAuth } = await loadAuthModule()
+ const env = makeEnv({ NODE_ENV: "production", CF_VERSION_METADATA: undefined })
+
+ expect(getAuth(env as never)).not.toBe(getAuth(env as never))
+ })
+
+ it("rebuilds when provider configuration changes", async () => {
+ const { getAuth } = await loadAuthModule()
+ const first = getAuth(makeEnv({ GITHUB_CLIENT_ID: "github-a" }) as never)
+ const second = getAuth(makeEnv({ GITHUB_CLIENT_ID: "github-b" }) as never)
+
+ expect(second).not.toBe(first)
+ })
+
+ it("starts a fresh lifecycle after a module reload", async () => {
+ const env = makeEnv()
+ const firstModule = await loadAuthModule()
+ const first = firstModule.getAuth(env as never)
+ const secondModule = await loadAuthModule()
+ const second = secondModule.getAuth(env as never)
+
+ expect(second).not.toBe(first)
+ })
+})
+
// Fetches the OTP-plugin `sendVerificationOTP` callback for a given env
// so tests can drive rate-limit + email-send behavior directly.
function getSendOtp(opts: AuthOptions) {
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index 0a07bbe39..1852a1881 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -394,3 +394,89 @@ export function createAuth(env: Env) {
],
})
}
+
+type AuthInstance = ReturnType<typeof createAuth>
+
+type AuthLifecycleEntry = {
+ configuration: readonly (string | undefined)[]
+ versionId: string
+ auth: AuthInstance
+}
+
+let authLifecycleEntry: AuthLifecycleEntry | undefined
+
+function authConfiguration(env: Env): readonly (string | undefined)[] {
+ return [
+ env.NODE_ENV ?? process.env.NODE_ENV,
+ env.BETTER_AUTH_URL,
+ env.BETTER_AUTH_SECRET,
+ env.GITHUB_CLIENT_ID,
+ env.GITHUB_CLIENT_SECRET,
+ env.GOOGLE_CLIENT_ID,
+ env.GOOGLE_CLIENT_SECRET,
+ env.APPLE_CLIENT_ID,
+ env.APPLE_TEAM_ID,
+ env.APPLE_KEY_ID,
+ env.APPLE_PRIVATE_KEY,
+ env.DEVICE_CLIENT_IDS,
+ env.APP_REVIEW_EMAIL,
+ env.APP_REVIEW_OTP,
+ env.AUTH_OTP_RATE_LIMIT_MAX,
+ env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,
+ ]
+}
+
+function sameAuthConfiguration(
+ left: readonly (string | undefined)[],
+ right: readonly (string | undefined)[],
+): boolean {
+ return left.length === right.length
+ && left.every((value, index) => value === right[index])
+}
+
+function authVersionId(env: Env): string | undefined {
+ const versionId = env.CF_VERSION_METADATA?.id
+ return typeof versionId === "string" && versionId.length > 0
+ ? versionId
+ : undefined
+}
+
+/**
+ * Worker-version-local Better Auth lifecycle.
+ *
+ * Cloudflare may materialize a fresh `env` wrapper for every request, so
+ * wrapper identity is not a valid cache key. A Worker version captures code,
+ * bindings, and compatibility configuration, so its version-metadata ID is
+ * the binding-generation boundary. Scalar auth/provider configuration is
+ * compared explicitly for local development and tests, where those values can
+ * change without a deployed version transition. A module/HMR reload naturally
+ * starts a fresh lifecycle as well.
+ *
+ * Production fails safe when version metadata is unavailable: construct a
+ * request-local instance instead of retaining binding-derived objects behind
+ * a scalar-only cache key.
+ *
+ * This caches only Better Auth's immutable instance/context. Request headers,
+ * session results, cookies, and responses always flow through each individual
+ * API call and are never retained here.
+ */
+export function getAuth(env: Env): AuthInstance {
+ const versionId = authVersionId(env)
+ const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })
+ if (!versionId && mode === "production") return createAuth(env)
+
+ const lifecycleVersion = versionId ?? "local-module"
+ const configuration = authConfiguration(env)
+ if (
+ !authLifecycleEntry
+ || authLifecycleEntry.versionId !== lifecycleVersion
+ || !sameAuthConfiguration(authLifecycleEntry.configuration, configuration)
+ ) {
+ authLifecycleEntry = {
+ configuration,
+ versionId: lifecycleVersion,
+ auth: createAuth(env),
+ }
+ }
+ return authLifecycleEntry.auth
+}
diff --git a/src/web/src/lib/community-db/collections.ts b/src/web/src/lib/community-db/collections.ts
new file mode 100644
index 000000000..e47aea193
--- /dev/null
+++ b/src/web/src/lib/community-db/collections.ts
@@ -0,0 +1,333 @@
+import {
+ DbClient,
+ collectionOptions,
+} from "@tanstack/react-db"
+import { queryCollectionOptions } from "@tanstack/query-db-collection"
+import type { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ categorySchema,
+ attentionItemSchema,
+ attentionScopeSchema,
+ channelMembershipSchema,
+ channelSchema,
+ folderItemSchema,
+ folderSchema,
+ messageSchema,
+ notificationSettingSchema,
+ profileSchema,
+ readStateClockSchema,
+ readStateSchema,
+ serverMembershipSchema,
+ serverSchema,
+ type CategoryRow,
+ type AttentionItemRow,
+ type AttentionScopeRow,
+ type ChannelMembershipRow,
+ type ChannelRow,
+ type FolderItemRow,
+ type FolderRow,
+ type MessageRow,
+ type NotificationSettingRow,
+ type ProfileRow,
+ type ReadStateClockRow,
+ type ReadStateRow,
+ type ServerMembershipRow,
+ type ServerRow,
+} from "./schema"
+
+const COLLECTION_GC_TIME = 24 * 60 * 60 * 1000
+
+function collectionQueryKey(accountId: string, name: string) {
+ return communityKeys.communityDbCollection(accountId, name)
+}
+
+function restoredRows<T extends object>(
+ queryClient: QueryClient,
+ accountId: string,
+ name: string,
+) {
+ return queryClient.getQueryData<T[]>(collectionQueryKey(accountId, name)) ?? []
+}
+
+function migrateLegacyServerPositions(queryClient: QueryClient, accountId: string) {
+ const key = collectionQueryKey(accountId, "servers")
+ const rows = queryClient.getQueryData<ServerRow[]>(key)
+ if (!rows?.some((row) => row.position === undefined)) return
+ queryClient.setQueryData(key, rows.map((row, position) => ({
+ ...row,
+ position: row.position ?? position,
+ })))
+}
+
+export function createCommunityDbRegistry(
+ queryClient: QueryClient,
+ accountId: string | null,
+ options: { waitForRestore?: Promise<void> } = {},
+) {
+ const scopeId = accountId ?? "anon"
+ const dbClient = new DbClient({ queryClient })
+ const waitForRestore = options.waitForRestore ?? Promise.resolve()
+ const queryFnFor = <T extends object>(name: string) => async () => {
+ await waitForRestore
+ return restoredRows<T>(queryClient, scopeId, name)
+ }
+
+ const servers = dbClient.collection(collectionOptions("community-db-servers", () => (
+ queryCollectionOptions({
+ id: "community-db-servers",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "servers"),
+ queryFn: queryFnFor<ServerRow>("servers"),
+ schema: serverSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const categories = dbClient.collection(collectionOptions("community-db-categories", () => (
+ queryCollectionOptions({
+ id: "community-db-categories",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "categories"),
+ queryFn: queryFnFor<CategoryRow>("categories"),
+ schema: categorySchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const channels = dbClient.collection(collectionOptions("community-db-channels", () => (
+ queryCollectionOptions({
+ id: "community-db-channels",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "channels"),
+ queryFn: queryFnFor<ChannelRow>("channels"),
+ schema: channelSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const serverMemberships = dbClient.collection(collectionOptions("community-db-server-memberships", () => (
+ queryCollectionOptions({
+ id: "community-db-server-memberships",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "serverMemberships"),
+ queryFn: queryFnFor<ServerMembershipRow>("serverMemberships"),
+ schema: serverMembershipSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const channelMemberships = dbClient.collection(collectionOptions("community-db-channel-memberships", () => (
+ queryCollectionOptions({
+ id: "community-db-channel-memberships",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "channelMemberships"),
+ queryFn: queryFnFor<ChannelMembershipRow>("channelMemberships"),
+ schema: channelMembershipSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const profiles = dbClient.collection(collectionOptions("community-db-profiles", () => (
+ queryCollectionOptions({
+ id: "community-db-profiles",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "profiles"),
+ queryFn: queryFnFor<ProfileRow>("profiles"),
+ schema: profileSchema,
+ getKey: (row) => row.userId,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const messages = dbClient.collection(collectionOptions("community-db-messages", () => (
+ queryCollectionOptions({
+ id: "community-db-messages",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "messages"),
+ queryFn: queryFnFor<MessageRow>("messages"),
+ schema: messageSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const readStates = dbClient.collection(collectionOptions("community-db-read-states", () => (
+ queryCollectionOptions({
+ id: "community-db-read-states",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "readStates"),
+ queryFn: queryFnFor<ReadStateRow>("readStates"),
+ schema: readStateSchema,
+ getKey: (row) => row.channelId,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const readStateClock = dbClient.collection(collectionOptions("community-db-read-state-clock", () => (
+ queryCollectionOptions({
+ id: "community-db-read-state-clock",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "readStateClock"),
+ queryFn: queryFnFor<ReadStateClockRow>("readStateClock"),
+ schema: readStateClockSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const attentionScopes = dbClient.collection(collectionOptions("community-db-attention-scopes", () => (
+ queryCollectionOptions({
+ id: "community-db-attention-scopes",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "attentionScopes"),
+ queryFn: queryFnFor<AttentionScopeRow>("attentionScopes"),
+ schema: attentionScopeSchema,
+ getKey: (row) => row.scopeId,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const attentionItems = dbClient.collection(collectionOptions("community-db-attention-items", () => (
+ queryCollectionOptions({
+ id: "community-db-attention-items",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "attentionItems"),
+ queryFn: queryFnFor<AttentionItemRow>("attentionItems"),
+ schema: attentionItemSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const folders = dbClient.collection(collectionOptions("community-db-folders", () => (
+ queryCollectionOptions({
+ id: "community-db-folders",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "folders"),
+ queryFn: queryFnFor<FolderRow>("folders"),
+ schema: folderSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const folderItems = dbClient.collection(collectionOptions("community-db-folder-items", () => (
+ queryCollectionOptions({
+ id: "community-db-folder-items",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "folderItems"),
+ queryFn: queryFnFor<FolderItemRow>("folderItems"),
+ schema: folderItemSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+ const notificationSettings = dbClient.collection(collectionOptions("community-db-notification-settings", () => (
+ queryCollectionOptions({
+ id: "community-db-notification-settings",
+ queryClient,
+ queryKey: collectionQueryKey(scopeId, "notificationSettings"),
+ queryFn: queryFnFor<NotificationSettingRow>("notificationSettings"),
+ schema: notificationSettingSchema,
+ getKey: (row) => row.id,
+ staleTime: Infinity,
+ gcTime: COLLECTION_GC_TIME,
+ persistedGcTime: COLLECTION_GC_TIME,
+ })
+ )))
+
+ const collections = {
+ servers,
+ categories,
+ channels,
+ serverMemberships,
+ channelMemberships,
+ profiles,
+ messages,
+ readStates,
+ readStateClock,
+ attentionScopes,
+ attentionItems,
+ folders,
+ folderItems,
+ notificationSettings,
+ } as const
+ type CollectionName = keyof typeof collections
+ const restoredCollectionNames = new Set<CollectionName>()
+ const restoredCollectionListeners = new Set<() => void>()
+ let restoredSnapshotCaptured = false
+ let restoredDataExists = false
+
+ return {
+ accountId,
+ scopeId,
+ queryClient,
+ dbClient,
+ collections,
+ captureRestoredCollections: () => {
+ if (restoredSnapshotCaptured) return
+ restoredSnapshotCaptured = true
+ migrateLegacyServerPositions(queryClient, scopeId)
+ for (const name of Object.keys(collections) as CollectionName[]) {
+ const data = queryClient.getQueryData(collectionQueryKey(scopeId, name))
+ if (data !== undefined) {
+ restoredCollectionNames.add(name)
+ if (Array.isArray(data) && data.length > 0) restoredDataExists = true
+ }
+ }
+ for (const listener of restoredCollectionListeners) listener()
+ },
+ hasRestoredCollection: (name: CollectionName) => restoredCollectionNames.has(name),
+ hasRestoredData: () => restoredDataExists,
+ subscribeRestoredCollections: (listener: () => void) => {
+ restoredCollectionListeners.add(listener)
+ return () => restoredCollectionListeners.delete(listener)
+ },
+ preload: () => Promise.all(Object.values(collections).map((collection) => collection.preload())),
+ cleanup: () => dbClient.cleanup(),
+ }
+}
+
+export type CommunityDbRegistry = ReturnType<typeof createCommunityDbRegistry>
+
+const registryByQueryClient = new WeakMap<QueryClient, CommunityDbRegistry>()
+let activeRegistry: CommunityDbRegistry | null = null
+
+export function registerCommunityDbRegistry(registry: CommunityDbRegistry) {
+ registryByQueryClient.set(registry.queryClient, registry)
+ activeRegistry = registry
+ return () => {
+ if (registryByQueryClient.get(registry.queryClient) === registry) {
+ registryByQueryClient.delete(registry.queryClient)
+ }
+ if (activeRegistry === registry) activeRegistry = null
+ }
+}
+
+export function getCommunityDbRegistry(queryClient: QueryClient) {
+ return registryByQueryClient.get(queryClient) ?? null
+}
+
+export function getActiveCommunityDbRegistry() {
+ return activeRegistry
+}
diff --git a/src/web/src/lib/community-db/message-access-scope.ts b/src/web/src/lib/community-db/message-access-scope.ts
new file mode 100644
index 000000000..00da757c6
--- /dev/null
+++ b/src/web/src/lib/community-db/message-access-scope.ts
@@ -0,0 +1,41 @@
+import type { QueryClient } from "@tanstack/react-query"
+
+export type MessageAccessScope = {
+ channelId?: string
+ serverId?: string | null
+}
+
+const messageAccessScopes = new WeakMap<QueryClient, Map<string, MessageAccessScope>>()
+
+export function rememberMessageAccessScope(
+ queryClient: QueryClient,
+ messageId: string,
+ scope: MessageAccessScope,
+) {
+ let scopes = messageAccessScopes.get(queryClient)
+ if (!scopes) {
+ scopes = new Map()
+ messageAccessScopes.set(queryClient, scopes)
+ }
+ scopes.set(messageId, scope)
+}
+
+export function takeMessageIdsForAccessScope(
+ queryClient: QueryClient,
+ channelIds: ReadonlySet<string>,
+ serverId: string | null,
+) {
+ const scopes = messageAccessScopes.get(queryClient)
+ if (!scopes) return []
+ const messageIds: string[] = []
+ for (const [messageId, scope] of scopes) {
+ if (
+ (scope.channelId !== undefined && channelIds.has(scope.channelId))
+ || (serverId !== null && scope.serverId === serverId)
+ ) {
+ messageIds.push(messageId)
+ scopes.delete(messageId)
+ }
+ }
+ return messageIds
+}
diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.ts
new file mode 100644
index 000000000..7622f0d4a
--- /dev/null
+++ b/src/web/src/lib/community-db/projections.dom.test.ts
@@ -0,0 +1,352 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import React, { type ReactNode } from "react"
+import { describe, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { communityKeys } from "@/lib/query-keys"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { CommunityPreviewProfileOwner } from "@/stores/community/profile-preview"
+import { createCommunityDbRegistry } from "./collections"
+import {
+ CommunityDbProvider,
+ useCanonicalCommunityProfile,
+ useCanonicalMessagesById,
+ useCanonicalProfilesByUserId,
+ useChannelRefDirectoryProjection,
+ useDmProjection,
+ useMessageProjection,
+ useNotificationSettingsProjection,
+ useReadStateProjection,
+ useRouteChannelProjection,
+ useServerRailProjection,
+ useServerTreeProjection,
+ useTrustedRestoredPrimary,
+} from "./projections"
+import { ingestServerDetail, ingestServers } from "./sync"
+
+describe("community DB projections", () => {
+ it("keeps every projection unresolved without a registry owner", () => {
+ const rendered = renderHook(() => ({
+ restored: useTrustedRestoredPrimary(),
+ rail: useServerRailProjection(),
+ tree: useServerTreeProjection("s1"),
+ dms: useDmProjection(),
+ route: useRouteChannelProjection("c1"),
+ messages: useMessageProjection("c1"),
+ messagesById: useCanonicalMessagesById(),
+ notifications: useNotificationSettingsProjection(),
+ readState: useReadStateProjection("c1"),
+ directory: useChannelRefDirectoryProjection(),
+ }))
+
+ expect(rendered.result.current).toEqual({
+ restored: false,
+ rail: undefined,
+ tree: undefined,
+ dms: undefined,
+ route: undefined,
+ messages: undefined,
+ messagesById: undefined,
+ notifications: undefined,
+ readState: undefined,
+ directory: undefined,
+ })
+ rendered.unmount()
+ })
+
+ it("uses an explicit preview profile map instead of canonical presence", () => {
+ const preview = new Map([[
+ "preview",
+ { id: "preview", name: "Preview", discriminator: "0001", avatar: "P", avatarVersion: 1 },
+ ]])
+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
+ CommunityPreviewProfileOwner,
+ { profiles: preview },
+ children,
+ )
+ const rendered = renderHook(useCanonicalProfilesByUserId, { wrapper })
+ expect(rendered.result.current).toBe(preview)
+ rendered.unmount()
+ })
+
+ it("requires completed detail before projecting a rail server tree", async () => {
+ const queryClient = new QueryClient()
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ ingestServers(registry, {
+ servers: [{
+ id: "s1",
+ name: "Server",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ }],
+ })
+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(CommunityDbProvider, { registry }, children),
+ )
+ const rendered = renderHook(() => useServerTreeProjection("s1"), { wrapper })
+
+ expect(rendered.result.current).toBeUndefined()
+ act(() => ingestServerDetail(registry, {
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [],
+ }))
+ await waitFor(() => expect(rendered.result.current).toMatchObject({
+ id: "s1",
+ categories: [],
+ }))
+
+ act(() => ingestServers(registry, {
+ servers: [{
+ id: "s1",
+ name: "Server renamed",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ }],
+ }))
+ await waitFor(() => expect(rendered.result.current?.name).toBe("Server renamed"))
+
+ rendered.unmount()
+ await registry["cleanup"]()
+ })
+
+ it("keeps the canonical rail in server-list order instead of collection-key order", async () => {
+ const queryClient = new QueryClient()
+ const legacyServers = [
+ {
+ id: "z-first",
+ name: "First",
+ discriminator: "0001",
+ description: "",
+ ownerId: "viewer",
+ icon: null,
+ official: false,
+ isOwner: true,
+ unread: false,
+ mentions: 0,
+ detailComplete: false,
+ },
+ {
+ id: "a-second",
+ name: "Second",
+ discriminator: "0001",
+ description: "",
+ ownerId: "viewer",
+ icon: null,
+ official: false,
+ isOwner: true,
+ unread: false,
+ mentions: 0,
+ detailComplete: false,
+ },
+ ]
+ queryClient.setQueryData(
+ communityKeys.communityDbCollection("viewer", "servers"),
+ legacyServers,
+ )
+ queryClient.setQueryData(
+ communityKeys.communityDbCollection("viewer", "serverMemberships"),
+ legacyServers.map((server) => ({
+ id: `${server.id}:viewer`,
+ serverId: server.id,
+ userId: "viewer",
+ role: "owner",
+ viewer: true,
+ })),
+ )
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ registry.captureRestoredCollections()
+ await registry.preload()
+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(CommunityDbProvider, { registry }, children),
+ )
+ const rendered = renderHook(useServerRailProjection, { wrapper })
+
+ await waitFor(() => expect(rendered.result.current?.servers.map((server) => server.id))
+ .toEqual(["z-first", "a-second"]))
+
+ act(() => ingestServers(registry, {
+ servers: [
+ {
+ id: "z-first",
+ name: "First",
+ initial: "F",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ },
+ {
+ id: "a-second",
+ name: "Second",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ },
+ ],
+ }))
+
+ await waitFor(() => expect(rendered.result.current?.servers.map((server) => server.id))
+ .toEqual(["z-first", "a-second"]))
+
+ rendered.unmount()
+ await registry["cleanup"]()
+ })
+
+ it("projects the complete canonical graph through every read model", async () => {
+ const queryClient = new QueryClient()
+ const collection = (name: string, rows: unknown[]) => queryClient.setQueryData(
+ communityKeys.communityDbCollection("viewer", name),
+ rows,
+ )
+ collection("servers", [{
+ id: "s1", position: 0, name: "Server", discriminator: "0001", description: "desc",
+ ownerId: "owner", icon: null, official: true, isOwner: false, unread: true,
+ mentions: 2, detailComplete: true,
+ }])
+ collection("serverMemberships", [{
+ id: "s1:viewer", serverId: "s1", userId: "viewer", role: "member", viewer: true,
+ }])
+ collection("categories", [
+ { id: "cat2", serverId: "s1", name: "Later", position: 2, private: false, pending: false },
+ { id: "cat1", serverId: "s1", name: "General", position: 1, private: false, pending: false },
+ ])
+ const channelBase = {
+ position: 1, archived: false, muted: false, unread: false, tags: [], pending: false,
+ }
+ collection("channels", [
+ { ...channelBase, id: "c2", serverId: "s1", categoryId: "cat1", name: "later", type: "text", position: 2 },
+ { ...channelBase, id: "c1", serverId: "s1", categoryId: "cat1", name: "chat", type: "text", position: 1 },
+ { ...channelBase, id: "forum2", serverId: "s1", categoryId: null, name: "later forum", type: "forum", position: 2 },
+ { ...channelBase, id: "forum1", serverId: "s1", categoryId: null, name: "forum", type: "forum", position: 1 },
+ { ...channelBase, id: "thread1", serverId: "s1", categoryId: null, name: "thread", type: "thread", parentChannelId: "forum1" },
+ { ...channelBase, id: "dm1", serverId: null, categoryId: null, name: "Peer", type: "dm", preview: "hello", lastUnreadSeq: 8 },
+ { ...channelBase, id: "dm-no-read-state", serverId: null, categoryId: null, name: "Quiet", type: "dm" },
+ { ...channelBase, id: "dm-no-member", serverId: null, categoryId: null, name: "Missing", type: "dm" },
+ { ...channelBase, id: "dm-no-profile", serverId: null, categoryId: null, name: "Missing profile", type: "dm" },
+ ])
+ collection("channelMemberships", [
+ { id: "dm1:viewer:access", channelId: "dm1", userId: "viewer", relation: "access" },
+ { id: "dm1:peer:access", channelId: "dm1", userId: "peer", relation: "access" },
+ { id: "dm-no-read-state:quiet:access", channelId: "dm-no-read-state", userId: "quiet", relation: "access" },
+ { id: "dm-no-profile:ghost:access", channelId: "dm-no-profile", userId: "ghost", relation: "access" },
+ ])
+ collection("profiles", [
+ { userId: "viewer", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 1 },
+ { userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 2 },
+ { userId: "quiet", name: "Quiet", discriminator: "0003", avatar: "Q", avatarVersion: 1 },
+ ])
+ collection("messages", [
+ { id: "m2", channelId: "c1", type: "chat", authorId: "peer", content: "second", seq: 2 },
+ { id: "m1", channelId: "c1", type: "chat", authorId: "peer", content: "first", seq: 1 },
+ ])
+ collection("readStates", [{
+ channelId: "dm1", lastReadMessageId: null, lastReadAt: "2026-09-25T00:00:00.000Z",
+ lastReadSeq: 7,
+ }, {
+ channelId: "c1", lastReadMessageId: "m1", lastReadAt: "2026-09-25T00:00:01.000Z",
+ lastReadSeq: 1,
+ }])
+ collection("readStateClock", [{ id: "account", revision: 1 }])
+ collection("folders", [
+ { id: "f2", name: "Later", position: 2 },
+ { id: "f1", name: "Folder", position: 1 },
+ ])
+ collection("folderItems", [
+ { id: "f1:missing", folderId: "f1", serverId: "missing", position: 2 },
+ { id: "f1:s1", folderId: "f1", serverId: "s1", position: 1 },
+ ])
+ collection("notificationSettings", [
+ { id: "server:s1", serverId: "s1", level: "all" },
+ { id: "channel:c1", channelId: "c1", level: "mentions" },
+ ])
+ const registry = createCommunityDbRegistry(queryClient, "viewer")
+ await registry.preload()
+ useCommunityWsStore.setState({ presenceByUserId: new Map([["peer", "online"]]) })
+ const restoredListener = vi.fn()
+ const unsubscribeRestored = registry.subscribeRestoredCollections(restoredListener)
+ registry.captureRestoredCollections()
+ registry.captureRestoredCollections()
+ expect(restoredListener).toHaveBeenCalledOnce()
+ unsubscribeRestored()
+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(CommunityDbProvider, { registry }, children),
+ )
+ const rendered = renderHook(() => ({
+ restored: useTrustedRestoredPrimary(),
+ rail: useServerRailProjection(),
+ tree: useServerTreeProjection("s1"),
+ dms: useDmProjection(),
+ route: useRouteChannelProjection("c1"),
+ messages: useMessageProjection("c1"),
+ messagesById: useCanonicalMessagesById(),
+ notifications: useNotificationSettingsProjection(),
+ readState: useReadStateProjection("c1"),
+ profiles: useCanonicalProfilesByUserId(),
+ profile: useCanonicalCommunityProfile("peer"),
+ directory: useChannelRefDirectoryProjection(),
+ }), { wrapper })
+
+ await waitFor(() => expect(rendered.result.current.restored).toBe(true))
+ expect(rendered.result.current.rail?.servers).toEqual([
+ expect.objectContaining({ id: "s1", name: "Server" }),
+ ])
+ expect(rendered.result.current.rail?.folders).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: "f1", servers: [expect.objectContaining({ id: "s1" })] }),
+ ]))
+ expect(rendered.result.current.tree?.categories).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: "cat1", channels: expect.arrayContaining([expect.objectContaining({ id: "c1" })]) }),
+ expect.objectContaining({ id: "__uncategorized__", channels: expect.arrayContaining([expect.objectContaining({ id: "forum1" })]) }),
+ ]))
+ expect(rendered.result.current.dms).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: "dm1", userId: "peer", lastUnreadSeq: 8 }),
+ expect.objectContaining({ id: "dm-no-read-state", userId: "quiet" }),
+ ]))
+ expect(rendered.result.current.dms?.find((dm) => dm.id === "dm-no-read-state"))
+ .not.toHaveProperty("lastUnreadSeq")
+ expect(rendered.result.current.route?.id).toBe("c1")
+ expect(rendered.result.current.messages?.map((message) => message.id)).toEqual(["m1", "m2"])
+ expect(rendered.result.current.messagesById?.get("m2")?.content).toBe("second")
+ expect(rendered.result.current.notifications).toMatchObject({
+ server: { s1: "All Messages" },
+ channel: { c1: "Only @mentions" },
+ })
+ expect(rendered.result.current.readState).toEqual({
+ lastReadMessageId: "m1",
+ lastReadAt: "2026-09-25T00:00:01.000Z",
+ lastReadSeq: 1,
+ })
+ expect(rendered.result.current.profiles.get("peer")?.id).toBe("peer")
+ expect(rendered.result.current.profiles.get("peer")?.presence).toBe("online")
+ expect(rendered.result.current.profile?.name).toBe("Peer")
+ expect(rendered.result.current.directory).toEqual([
+ expect.objectContaining({ id: "s1", channels: expect.arrayContaining([
+ expect.objectContaining({ id: "c1" }),
+ expect.objectContaining({ id: "forum1" }),
+ ]) }),
+ ])
+
+ rendered.unmount()
+ useCommunityWsStore.getState().reset()
+ expect(registry.hasRestoredCollection("channels")).toBe(true)
+ await registry["cleanup"]()
+ })
+})
diff --git a/src/web/src/lib/community-db/projections.ssr.test.ts b/src/web/src/lib/community-db/projections.ssr.test.ts
new file mode 100644
index 000000000..ffd7b0506
--- /dev/null
+++ b/src/web/src/lib/community-db/projections.ssr.test.ts
@@ -0,0 +1,14 @@
+import React from "react"
+import { renderToString } from "react-dom/server"
+import { describe, expect, it } from "vitest"
+import { useTrustedRestoredPrimary } from "./projections"
+
+describe("community DB projection server snapshot", () => {
+ it("is unresolved without a registry during server rendering", () => {
+ function Probe() {
+ return React.createElement("span", null, String(useTrustedRestoredPrimary()))
+ }
+
+ expect(renderToString(React.createElement(Probe))).toContain("false")
+ })
+})
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
new file mode 100644
index 000000000..0f58547f2
--- /dev/null
+++ b/src/web/src/lib/community-db/projections.ts
@@ -0,0 +1,632 @@
+"use client"
+
+import {
+ createContext,
+ createElement,
+ useContext,
+ useMemo,
+ useSyncExternalStore,
+ type Context,
+ type ReactNode,
+} from "react"
+import { DbProvider, useLiveQuery } from "@tanstack/react-db"
+import { notifLevelDisplay } from "@alook/shared"
+import { avatarInitial } from "@/lib/community/avatar"
+import type { DM } from "@/lib/community/models/people"
+import type { CommunityProfile } from "@/lib/community/models/people"
+import type { Category, CommunityFolder, Server } from "@/lib/community/models/navigation"
+import type { Msg } from "@/lib/community/models/message"
+import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
+import type { CommunityDbRegistry } from "./collections"
+import { useCommunityPreviewProfiles } from "@/stores/community/profile-preview"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import type {
+ AttentionItemRow,
+ AttentionScopeRow,
+ CategoryRow,
+ ChannelMembershipRow,
+ ChannelRow,
+ FolderItemRow,
+ FolderRow,
+ MessageRow,
+ NotificationSettingRow,
+ ProfileRow,
+ ReadStateRow,
+ ServerMembershipRow,
+ ServerRow,
+} from "./schema"
+
+let communityDbContext: Context<CommunityDbRegistry | null> | null = null
+
+function getCommunityDbContext() {
+ communityDbContext ??= createContext<CommunityDbRegistry | null>(null)
+ return communityDbContext
+}
+
+export function useOptionalCommunityDbRegistry() {
+ return useContext(getCommunityDbContext())
+}
+
+const subscribeToNoRestoredCollections = () => () => {}
+const noRestoredPrimary = () => false
+
+export function useTrustedRestoredPrimary() {
+ const registry = useOptionalCommunityDbRegistry()
+ return useSyncExternalStore(
+ registry?.subscribeRestoredCollections ?? subscribeToNoRestoredCollections,
+ () => Boolean(
+ registry?.hasRestoredCollection("categories")
+ && registry.hasRestoredCollection("channels"),
+ ),
+ noRestoredPrimary,
+ )
+}
+
+export function CommunityDbProvider({
+ registry,
+ children,
+}: {
+ registry: CommunityDbRegistry
+ children: ReactNode
+}) {
+ return createElement(
+ DbProvider,
+ { client: registry.dbClient },
+ createElement(getCommunityDbContext().Provider, { value: registry }, children),
+ )
+}
+
+function useCollectionRows() {
+ const registry = useOptionalCommunityDbRegistry()
+ const servers = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ server: registry.collections.servers })
+ : undefined,
+ }).data as ServerRow[] | undefined
+ const categories = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ category: registry.collections.categories })
+ : undefined,
+ }).data as CategoryRow[] | undefined
+ const channels = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ channel: registry.collections.channels })
+ : undefined,
+ }).data as ChannelRow[] | undefined
+ const serverMemberships = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ membership: registry.collections.serverMemberships })
+ : undefined,
+ }).data as ServerMembershipRow[] | undefined
+ const channelMemberships = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ membership: registry.collections.channelMemberships })
+ : undefined,
+ }).data as ChannelMembershipRow[] | undefined
+ const profiles = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ profile: registry.collections.profiles })
+ : undefined,
+ }).data as ProfileRow[] | undefined
+ const messages = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ message: registry.collections.messages })
+ : undefined,
+ }).data as MessageRow[] | undefined
+ const readStates = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ readState: registry.collections.readStates })
+ : undefined,
+ }).data as ReadStateRow[] | undefined
+ const folders = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ folder: registry.collections.folders })
+ : undefined,
+ }).data as FolderRow[] | undefined
+ const folderItems = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ item: registry.collections.folderItems })
+ : undefined,
+ }).data as FolderItemRow[] | undefined
+ const notificationSettings = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ setting: registry.collections.notificationSettings })
+ : undefined,
+ }).data as NotificationSettingRow[] | undefined
+ return {
+ registry,
+ servers,
+ categories,
+ channels,
+ serverMemberships,
+ channelMemberships,
+ profiles,
+ messages,
+ readStates,
+ folders,
+ folderItems,
+ notificationSettings,
+ }
+}
+
+export function useServerRailProjection() {
+ const rows = useCollectionRows()
+ return useMemo(() => {
+ if (!rows.registry || !rows.servers || !rows.serverMemberships) return undefined
+ const viewerId = rows.registry.accountId
+ const allowed = new Set(
+ rows.serverMemberships
+ .filter((membership) => membership.viewer && membership.userId === viewerId)
+ .map((membership) => membership.serverId),
+ )
+ const servers: Server[] = rows.servers
+ .map((server, fallbackPosition) => ({ server, fallbackPosition }))
+ .sort((left, right) => (
+ (left.server.position ?? left.fallbackPosition)
+ - (right.server.position ?? right.fallbackPosition)
+ ))
+ .filter(({ server }) => allowed.has(server.id))
+ .map(({ server }) => ({
+ id: server.id,
+ name: server.name,
+ discriminator: server.discriminator,
+ description: server.description,
+ ownerId: server.ownerId,
+ initial: avatarInitial(server.name),
+ active: false,
+ unread: server.unread,
+ mentions: server.mentions,
+ official: server.official,
+ isOwner: server.isOwner,
+ icon: server.icon,
+ }))
+ const byServer = new Map(servers.map((server) => [server.id, server]))
+ const itemsByFolder = new Map<string, FolderItemRow[]>()
+ for (const item of rows.folderItems ?? []) {
+ const items = itemsByFolder.get(item.folderId) ?? []
+ items.push(item)
+ itemsByFolder.set(item.folderId, items)
+ }
+ const folders: CommunityFolder[] = (rows.folders ?? [])
+ .slice()
+ .sort((a, b) => a.position - b.position)
+ .map((folder) => ({
+ id: folder.id,
+ name: folder.name,
+ position: folder.position,
+ servers: (itemsByFolder.get(folder.id) ?? [])
+ .slice()
+ .sort((a, b) => a.position - b.position)
+ .flatMap((item) => {
+ const server = byServer.get(item.serverId)
+ return server ? [{
+ id: server.id,
+ name: server.name,
+ initial: server.initial,
+ icon: server.icon,
+ }] : []
+ }),
+ }))
+ return { servers, folders }
+ }, [rows])
+}
+
+export function useServerTreeProjection(serverId: string | null) {
+ const rows = useCollectionRows()
+ return useMemo(() => {
+ if (!serverId || !rows.servers || !rows.categories || !rows.channels) return undefined
+ const server = rows.servers.find((candidate) => candidate.id === serverId)
+ if (!server?.detailComplete) return undefined
+ const channels = rows.channels.filter((channel) => (
+ channel.serverId === serverId && channel.type !== "thread"
+ ))
+ const categories: Category[] = rows.categories
+ .filter((category) => category.serverId === serverId)
+ .sort((a, b) => a.position - b.position)
+ .map((category) => ({
+ id: category.id,
+ name: category.name,
+ private: category.private,
+ creatorId: category.creatorId,
+ pending: category.pending,
+ channels: channels
+ .filter((channel) => channel.categoryId === category.id)
+ .sort((a, b) => a.position - b.position)
+ .map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ active: false,
+ unread: channel.unread,
+ muted: channel.muted,
+ type: channel.type === "forum" ? "forum" : "text",
+ tags: channel.tags,
+ creatorId: channel.creatorId,
+ pending: channel.pending,
+ })),
+ }))
+ const uncategorized = channels
+ .filter((channel) => !channel.categoryId)
+ .sort((a, b) => a.position - b.position)
+ .map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ active: false,
+ unread: channel.unread,
+ muted: channel.muted,
+ type: channel.type === "forum" ? "forum" as const : "text" as const,
+ tags: channel.tags,
+ creatorId: channel.creatorId,
+ pending: channel.pending,
+ }))
+ if (uncategorized.length > 0) {
+ categories.push({ id: "__uncategorized__", name: "", private: false, channels: uncategorized })
+ }
+ return {
+ id: server.id,
+ name: server.name,
+ discriminator: server.discriminator,
+ description: server.description,
+ icon: server.icon,
+ official: server.official,
+ ownerId: server.ownerId,
+ categories,
+ }
+ }, [rows, serverId])
+}
+
+export function useDmProjection() {
+ const rows = useCollectionRows()
+ return useMemo(() => {
+ const viewerId = rows.registry?.accountId
+ if (!viewerId || !rows.channels || !rows.channelMemberships || !rows.profiles) return undefined
+ const channelMemberships = rows.channelMemberships
+ const profileById = new Map(rows.profiles.map((profile) => [profile.userId, profile]))
+ const readStateByChannel = new Map((rows.readStates ?? []).map((state) => [state.channelId, state]))
+ return rows.channels
+ .filter((channel) => channel.type === "dm")
+ .flatMap((channel): DM[] => {
+ const peerMembership = channelMemberships.find((membership) => (
+ membership.channelId === channel.id
+ && membership.relation === "access"
+ && membership.userId !== viewerId
+ ))
+ if (!peerMembership) return []
+ const profile = profileById.get(peerMembership.userId)
+ if (!profile) return []
+ const readState = readStateByChannel.get(channel.id)
+ return [{
+ id: channel.id,
+ userId: profile.userId,
+ name: profile.name,
+ discriminator: profile.discriminator,
+ avatar: profile.avatar,
+ avatarVersion: profile.avatarVersion,
+ status: "offline",
+ preview: channel.preview ?? "",
+ unread: channel.unread,
+ ...(channel.lastUnreadSeq === undefined && !readState
+ ? {}
+ : { lastUnreadSeq: channel.lastUnreadSeq ?? readState?.lastReadSeq }),
+ }]
+ })
+ }, [rows])
+}
+
+export function useRouteChannelProjection(channelId: string | null) {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ channel: registry.collections.channels })
+ : undefined,
+ })
+ return useMemo(() => {
+ if (!channelId || !result.data) return undefined
+ return (result.data as ChannelRow[]).find((row) => row.id === channelId)
+ }, [channelId, result.data])
+}
+
+export function useReadStateProjection(channelId: string | null | undefined) {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ readState: registry.collections.readStates })
+ : undefined,
+ })
+ return useMemo(() => {
+ if (!channelId || !result.data) return undefined
+ const row = (result.data as ReadStateRow[])
+ .find((candidate) => candidate.channelId === channelId)
+ if (!row) return undefined
+ return {
+ lastReadMessageId: row.lastReadMessageId,
+ lastReadAt: row.lastReadAt,
+ lastReadSeq: row.lastReadSeq,
+ }
+ }, [channelId, result.data])
+}
+
+export function useMessageProjection(channelId: string | null) {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ message: registry.collections.messages })
+ : undefined,
+ })
+ return useMemo(() => {
+ if (!channelId || !result.data) return undefined
+ return (result.data as MessageRow[])
+ .filter((message) => message.channelId === channelId)
+ .sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
+ .map((message) => {
+ const { channelId: _channelId, replyToId: _replyToId, ...model } = message
+ return model as Msg
+ })
+ }, [channelId, result.data])
+}
+
+export function useCanonicalMessagesById(): ReadonlyMap<string, Msg> | undefined {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ message: registry.collections.messages })
+ : undefined,
+ })
+ return useMemo(() => !registry ? undefined : new Map(
+ ((result.data ?? []) as MessageRow[]).map((message) => {
+ const { channelId: _channelId, replyToId: _replyToId, ...model } = message
+ return [message.id, model as Msg]
+ }),
+ ), [registry, result.data])
+}
+
+export function useCanonicalChannelsById(): ReadonlyMap<string, ChannelRow> {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ channel: registry.collections.channels })
+ : undefined,
+ })
+ return useMemo(() => new Map(
+ ((result.data ?? []) as ChannelRow[]).map((channel) => [channel.id, channel]),
+ ), [result.data])
+}
+
+export function useCanonicalServersById(): ReadonlyMap<string, ServerRow> {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ server: registry.collections.servers })
+ : undefined,
+ })
+ return useMemo(() => new Map(
+ ((result.data ?? []) as ServerRow[]).map((server) => [server.id, server]),
+ ), [result.data])
+}
+
+export function materializeCanonicalMessage(
+ transport: Msg,
+ canonical: ReadonlyMap<string, Msg> | undefined,
+): Msg | undefined {
+ return canonical === undefined ? transport : canonical.get(transport.id)
+}
+
+export function materializeCanonicalMessages(
+ transport: readonly Msg[],
+ canonical: ReadonlyMap<string, Msg> | undefined,
+): Msg[] {
+ return canonical === undefined
+ ? [...transport]
+ : transport.flatMap((message) => {
+ const row = canonical.get(message.id)
+ return row ? [row] : []
+ })
+}
+
+export function useNotificationSettingsProjection() {
+ const rows = useCollectionRows()
+ return useMemo(() => {
+ if (!rows.notificationSettings) return undefined
+ const server: Record<string, string> = {}
+ const channel: Record<string, string> = {}
+ for (const setting of rows.notificationSettings) {
+ const display = notifLevelDisplay(setting.level)
+ if (setting.channelId) channel[setting.channelId] = display
+ else if (setting.serverId) server[setting.serverId] = display
+ }
+ return {
+ raw: rows.notificationSettings.map(({ serverId, channelId, level }) => ({
+ serverId,
+ channelId,
+ level,
+ })),
+ server,
+ channel,
+ }
+ }, [rows.notificationSettings])
+}
+
+function useProfileProjectionMap() {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ profile: registry.collections.profiles })
+ : undefined,
+ })
+ return useMemo(() => new Map(
+ ((result.data ?? []) as ProfileRow[]).map((profile) => [profile.userId, profile]),
+ ), [result.data])
+}
+
+export function useCanonicalProfilesByUserId(): ReadonlyMap<string, CommunityProfile> {
+ const previewProfiles = useCommunityPreviewProfiles()
+ const canonicalProfiles = useProfileProjectionMap()
+ const livePresence = useCommunityWsStore((state) => (
+ previewProfiles ? null : state.presenceByUserId
+ ))
+ return useMemo(() => {
+ if (previewProfiles) return previewProfiles
+ const merged = new Map<string, CommunityProfile>()
+ for (const [userId, profile] of canonicalProfiles) {
+ merged.set(userId, { ...profile, id: userId })
+ }
+ for (const [userId, presence] of livePresence ?? []) {
+ merged.set(userId, { ...merged.get(userId), id: userId, presence })
+ }
+ return merged
+ }, [canonicalProfiles, livePresence, previewProfiles])
+}
+
+export function useCanonicalCommunityProfile(userId: string | null | undefined) {
+ const profiles = useCanonicalProfilesByUserId()
+ return userId ? profiles.get(userId) : undefined
+}
+
+export function useAttentionScopes(): readonly AttentionScopeRow[] {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ scope: registry.collections.attentionScopes })
+ : undefined,
+ })
+ return (result.data ?? []) as AttentionScopeRow[]
+}
+
+export function useAttentionItems(): readonly AttentionItemRow[] {
+ const registry = useOptionalCommunityDbRegistry()
+ const result = useLiveQuery({
+ query: (q) => registry
+ ? q.from({ item: registry.collections.attentionItems })
+ : undefined,
+ })
+ return (result.data ?? []) as AttentionItemRow[]
+}
+
+export function useChannelRefDirectoryProjection(): ChannelRefDirectory | undefined {
+ const rows = useCollectionRows()
+ return useMemo(() => {
+ if (!rows.servers || !rows.channels) return undefined
+ const channels = rows.channels
+ return rows.servers.map((server) => ({
+ id: server.id,
+ name: server.name,
+ discriminator: server.discriminator,
+ channels: channels
+ .filter((channel) => channel.serverId === server.id)
+ .flatMap((channel) => (
+ channel.type === "text" || channel.type === "forum"
+ ? [{ id: channel.id, name: channel.name, type: channel.type }]
+ : []
+ )),
+ }))
+ }, [rows.channels, rows.servers])
+}
+
+export type CanonicalForumSidebarThread = {
+ id: string
+ parentChannelId: string
+ parentMessageId: string
+ title: string
+ activityAt: string
+ expiresAt: string
+ unread: boolean
+}
+
+const FORUM_SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000
+
+export function useForumSidebarProjection(
+ serverId: string,
+ retainId: string | null,
+ serverNowMs: number | null,
+) {
+ const rows = useCollectionRows()
+ return useMemo(() => {
+ if (
+ serverNowMs === null
+ || !rows.registry
+ || !rows.channels
+ || !rows.channelMemberships
+ || !rows.messages
+ ) return undefined
+ const viewerId = rows.registry.accountId
+ const participating = new Set(rows.channelMemberships
+ .filter((membership) => (
+ membership.relation === "notify"
+ && membership.userId === viewerId
+ ))
+ .map((membership) => membership.channelId))
+ const messageById = new Map(rows.messages.map((message) => [message.id, message]))
+ const candidates: CanonicalForumSidebarThread[] = rows.channels
+ .filter((channel) => (
+ channel.serverId === serverId
+ && channel.type === "thread"
+ && !channel.archived
+ && participating.has(channel.id)
+ && channel.parentChannelId
+ && channel.parentMessageId
+ ))
+ .map((channel) => {
+ const activityAt = channel.lastMessageAt ?? ""
+ const activityMs = Date.parse(activityAt)
+ return {
+ id: channel.id,
+ parentChannelId: channel.parentChannelId!,
+ parentMessageId: channel.parentMessageId!,
+ title: messageById.get(channel.parentMessageId!)?.content ?? channel.name,
+ activityAt,
+ expiresAt: Number.isFinite(activityMs)
+ ? new Date(activityMs + FORUM_SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()
+ : activityAt,
+ unread: channel.unread,
+ }
+ })
+ .filter((thread) => (
+ thread.id === retainId
+ || !Number.isFinite(Date.parse(thread.expiresAt))
+ || Date.parse(thread.expiresAt) > serverNowMs
+ ))
+ .sort((left, right) => (
+ left.parentChannelId.localeCompare(right.parentChannelId)
+ || right.activityAt.localeCompare(left.activityAt)
+ || right.id.localeCompare(left.id)
+ ))
+ const byParent = new Map<string, CanonicalForumSidebarThread[]>()
+ for (const thread of candidates) {
+ const siblings = byParent.get(thread.parentChannelId) ?? []
+ siblings.push(thread)
+ byParent.set(thread.parentChannelId, siblings)
+ }
+ const threads = [...byParent.values()].flatMap((siblings) => {
+ const retained = retainId
+ ? siblings.find((thread) => thread.id === retainId)
+ : undefined
+ if (!retained) return siblings.slice(0, 5)
+ if (siblings.slice(0, 5).some((thread) => thread.id === retained.id)) {
+ return siblings.slice(0, 5)
+ }
+ return [...siblings.filter((thread) => thread.id !== retained.id).slice(0, 4), retained]
+ .sort((left, right) => (
+ right.activityAt.localeCompare(left.activityAt)
+ || right.id.localeCompare(left.id)
+ ))
+ })
+ const renderedIds = new Set(threads.map((thread) => thread.id))
+ const parentUnread: Record<string, boolean> = {}
+ for (const parent of rows.channels.filter((channel) => (
+ channel.serverId === serverId && channel.type === "forum"
+ ))) {
+ parentUnread[parent.id] = parent.baseUnread ?? parent.unread
+ }
+ for (const child of rows.channels) {
+ if (
+ child.serverId === serverId
+ && child.type === "thread"
+ && child.unread
+ && child.parentChannelId
+ && !renderedIds.has(child.id)
+ ) {
+ parentUnread[child.parentChannelId] = true
+ }
+ }
+ return { threads, parentUnread }
+ }, [retainId, rows, serverId, serverNowMs])
+}
diff --git a/src/web/src/lib/community-db/schema.test.ts b/src/web/src/lib/community-db/schema.test.ts
new file mode 100644
index 000000000..d7d600eb6
--- /dev/null
+++ b/src/web/src/lib/community-db/schema.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest"
+import {
+ channelMembershipKey,
+ communityCollectionSchemas,
+ folderItemKey,
+ notificationSettingKey,
+ notificationSettingSchema,
+ serverSchema,
+ serverMembershipKey,
+} from "./schema"
+
+describe("community DB schemas", () => {
+ it("defines the canonical collection families, including independent attention state", () => {
+ expect(Object.keys(communityCollectionSchemas)).toEqual([
+ "servers",
+ "categories",
+ "channels",
+ "serverMemberships",
+ "channelMemberships",
+ "profiles",
+ "messages",
+ "readStates",
+ "readStateClock",
+ "attentionScopes",
+ "attentionItems",
+ "folders",
+ "folderItems",
+ "notificationSettings",
+ ])
+ })
+
+ it("uses stable relationship identities", () => {
+ expect(serverMembershipKey("s1", "u1")).toBe("s1:u1")
+ expect(channelMembershipKey("c1", "u1", "access")).toBe("c1:u1:access")
+ expect(channelMembershipKey("c1", "u1", "notify")).toBe("c1:u1:notify")
+ expect(folderItemKey("f1", "s1")).toBe("f1:s1")
+ expect(notificationSettingKey({ serverId: "s1" })).toBe("server:s1")
+ expect(notificationSettingKey({ channelId: "c1" })).toBe("channel:c1")
+ })
+
+ it("rejects notification rows without exactly one target", () => {
+ const base = { id: "setting", level: "all" }
+ expect(notificationSettingSchema.safeParse(base).success).toBe(false)
+ expect(notificationSettingSchema.safeParse({
+ ...base,
+ serverId: "s1",
+ channelId: "c1",
+ }).success).toBe(false)
+ expect(notificationSettingSchema.safeParse({
+ ...base,
+ serverId: "s1",
+ channelId: null,
+ }).success).toBe(true)
+ expect(() => notificationSettingKey({ serverId: null, channelId: null })).toThrow(
+ "notification setting target missing",
+ )
+ })
+
+ it("treats restored server identities without a detail marker as incomplete", () => {
+ const parsed = serverSchema.parse({
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ ownerId: "owner",
+ icon: null,
+ official: false,
+ isOwner: false,
+ unread: false,
+ mentions: 0,
+ })
+ expect(parsed.detailComplete).toBe(false)
+ expect(parsed).not.toHaveProperty("position")
+ })
+})
diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.ts
new file mode 100644
index 000000000..c9c34d625
--- /dev/null
+++ b/src/web/src/lib/community-db/schema.ts
@@ -0,0 +1,222 @@
+import { z } from "zod"
+
+const nullableString = z.string().nullable()
+const optionalNullableString = nullableString.optional()
+
+export const serverSchema = z.object({
+ id: z.string().min(1),
+ // Optional only for v2 rows written before canonical rail ordering landed.
+ // Registry restore migrates those rows from their persisted array order.
+ position: z.number().int().nonnegative().optional(),
+ name: z.string(),
+ discriminator: z.string(),
+ description: z.string(),
+ ownerId: z.string(),
+ icon: nullableString,
+ official: z.boolean(),
+ isOwner: z.boolean(),
+ unread: z.boolean(),
+ mentions: z.number().int().nonnegative(),
+ detailComplete: z.boolean().default(false),
+})
+
+export const categorySchema = z.object({
+ id: z.string().min(1),
+ serverId: z.string().min(1),
+ name: z.string(),
+ position: z.number(),
+ private: z.boolean(),
+ creatorId: optionalNullableString,
+ pending: z.boolean(),
+})
+
+export const channelSchema = z.object({
+ id: z.string().min(1),
+ serverId: optionalNullableString,
+ categoryId: optionalNullableString,
+ name: z.string(),
+ type: z.enum(["text", "forum", "thread", "dm"]),
+ parentChannelId: optionalNullableString,
+ parentMessageId: optionalNullableString,
+ creatorId: optionalNullableString,
+ position: z.number(),
+ archived: z.boolean(),
+ muted: z.boolean(),
+ unread: z.boolean(),
+ /** Forum channel's own unread bit, excluding participating child rows. */
+ baseUnread: z.boolean().optional(),
+ tags: z.array(z.string()),
+ pending: z.boolean(),
+ lastMessageAt: optionalNullableString,
+ preview: z.string().optional(),
+ lastUnreadSeq: z.number().int().nonnegative().optional(),
+})
+
+export const serverMembershipSchema = z.object({
+ id: z.string().min(1),
+ serverId: z.string().min(1),
+ userId: z.string().min(1),
+ memberId: z.string().optional(),
+ role: z.string(),
+ nickname: optionalNullableString,
+ joinedAt: z.string().optional(),
+ viewer: z.boolean(),
+})
+
+export const channelMembershipSchema = z.object({
+ id: z.string().min(1),
+ channelId: z.string().min(1),
+ userId: z.string().min(1),
+ relation: z.enum(["access", "notify"]),
+ memberId: z.string().optional(),
+ source: z.enum(["explicit", "inherited", "admin"]).optional(),
+ isCreator: z.boolean().optional(),
+})
+
+export const profileSchema = z.object({
+ userId: z.string().min(1),
+ name: z.string(),
+ discriminator: z.string(),
+ avatar: z.string(),
+ avatarVersion: z.number().int().nonnegative(),
+ aboutMe: z.string().optional(),
+ bannerColor: optionalNullableString,
+ kind: z.enum(["human", "bot"]).optional(),
+ ownerUserId: optionalNullableString,
+ statusEmoji: optionalNullableString,
+ statusText: optionalNullableString,
+})
+
+export const messageSchema = z.object({
+ id: z.string().min(1),
+ channelId: z.string().min(1),
+ type: z.enum(["chat", "system"]),
+ systemKind: z.literal("thread").optional(),
+ authorId: z.string().optional(),
+ authorName: z.string().optional(),
+ authorAvatar: z.string().optional(),
+ authorAvatarVersion: z.number().int().nonnegative().optional(),
+ seq: z.number().int().nonnegative().optional(),
+ createdAt: z.string().optional(),
+ clientNonce: z.string().optional(),
+ content: z.string().optional(),
+ failed: z.boolean().optional(),
+ replyToId: z.string().optional(),
+}).passthrough()
+
+export const readStateSchema = z.object({
+ channelId: z.string().min(1),
+ lastReadMessageId: nullableString,
+ lastReadAt: z.string(),
+ lastReadSeq: z.number().int().nonnegative(),
+})
+
+export const readStateClockSchema = z.object({
+ id: z.literal("account"),
+ revision: z.number().int().nonnegative(),
+})
+
+export const attentionScopeSchema = z.strictObject({
+ scopeId: z.string().min(1),
+ channelId: z.string().min(1),
+ serverId: optionalNullableString,
+ parentChannelId: optionalNullableString,
+ ordinaryUnread: z.boolean(),
+ lastUnreadSeq: z.number().int().nonnegative(),
+ lastAttentionSeq: z.number().int().nonnegative().nullable().optional(),
+ attentionCount: z.number().int().nonnegative(),
+})
+
+export const attentionItemSchema = z.strictObject({
+ id: z.string().min(1),
+ kind: z.enum(["mention", "reply", "friend_request", "pending"]),
+ sourceId: z.string().min(1),
+ scopeId: optionalNullableString,
+ messageId: optionalNullableString,
+ actorUserId: z.string().min(1),
+ createdAt: z.string(),
+})
+
+export const folderSchema = z.object({
+ id: z.string().min(1),
+ name: z.string(),
+ position: z.number(),
+})
+
+export const folderItemSchema = z.object({
+ id: z.string().min(1),
+ folderId: z.string().min(1),
+ serverId: z.string().min(1),
+ position: z.number(),
+})
+
+export const notificationSettingSchema = z.object({
+ id: z.string().min(1),
+ serverId: optionalNullableString,
+ channelId: optionalNullableString,
+ level: z.string(),
+}).superRefine((row, ctx) => {
+ if (Boolean(row.serverId) === Boolean(row.channelId)) {
+ ctx.addIssue({
+ code: "custom",
+ message: "notification setting requires exactly one target",
+ })
+ }
+})
+
+export const communityCollectionSchemas = {
+ servers: serverSchema,
+ categories: categorySchema,
+ channels: channelSchema,
+ serverMemberships: serverMembershipSchema,
+ channelMemberships: channelMembershipSchema,
+ profiles: profileSchema,
+ messages: messageSchema,
+ readStates: readStateSchema,
+ readStateClock: readStateClockSchema,
+ attentionScopes: attentionScopeSchema,
+ attentionItems: attentionItemSchema,
+ folders: folderSchema,
+ folderItems: folderItemSchema,
+ notificationSettings: notificationSettingSchema,
+} as const
+
+export type CommunityCollectionName = keyof typeof communityCollectionSchemas
+export type ServerRow = z.infer<typeof serverSchema>
+export type CategoryRow = z.infer<typeof categorySchema>
+export type ChannelRow = z.infer<typeof channelSchema>
+export type ServerMembershipRow = z.infer<typeof serverMembershipSchema>
+export type ChannelMembershipRow = z.infer<typeof channelMembershipSchema>
+export type ProfileRow = z.infer<typeof profileSchema>
+export type MessageRow = z.infer<typeof messageSchema>
+export type ReadStateRow = z.infer<typeof readStateSchema>
+export type ReadStateClockRow = z.infer<typeof readStateClockSchema>
+export type AttentionScopeRow = z.infer<typeof attentionScopeSchema>
+export type AttentionItemRow = z.infer<typeof attentionItemSchema>
+export type FolderRow = z.infer<typeof folderSchema>
+export type FolderItemRow = z.infer<typeof folderItemSchema>
+export type NotificationSettingRow = z.infer<typeof notificationSettingSchema>
+
+export function serverMembershipKey(serverId: string, userId: string) {
+ return `${serverId}:${userId}`
+}
+
+export function channelMembershipKey(
+ channelId: string,
+ userId: string,
+ relation: ChannelMembershipRow["relation"],
+) {
+ return `${channelId}:${userId}:${relation}`
+}
+
+export function folderItemKey(folderId: string, serverId: string) {
+ return `${folderId}:${serverId}`
+}
+
+export function notificationSettingKey(
+ row: Pick<NotificationSettingRow, "serverId" | "channelId">,
+) {
+ if (row.channelId) return `channel:${row.channelId}`
+ if (row.serverId) return `server:${row.serverId}`
+ throw new Error("notification setting target missing")
+}
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
new file mode 100644
index 000000000..fd76c7a0a
--- /dev/null
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -0,0 +1,2501 @@
+import { QueryClient } from "@tanstack/react-query"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import type { CommunityWsEvent } from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
+import { rememberMessageAccessScope } from "./message-access-scope"
+import { getLastChannel, setLastChannel } from "@/lib/community/last-channel"
+import {
+ getLastMeLeaf,
+ setLastMeLocation,
+} from "@/lib/community/last-me-location"
+import {
+ createCommunityDbRegistry,
+ getActiveCommunityDbRegistry,
+ registerCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "./collections"
+import {
+ ingestDms,
+ ingestAttentionSnapshot,
+ ingestMessages,
+ ingestReadStateSnapshot,
+ ingestServerDetail,
+ ingestServers,
+ installCommunityDbSync,
+ captureCommunityLiveSnapshotToken,
+ clearAttentionOptimistically,
+ clearAttentionScopeOptimistically,
+ commitAttentionOptimisticSnapshot,
+ commitAttentionScopeOptimisticSnapshot,
+ patchCanonicalCommunityMessage,
+ publishCommunityDmSummary,
+ publishCommunityMessages,
+ publishCommunityChannelDirectory,
+ publishCommunityLiveSnapshot as publishCommunityLiveSnapshotWithProof,
+ publishAccountAttentionSnapshot,
+ projectAttentionUnreadBump,
+ projectAttentionMentionHint,
+ projectCommunityWsEventToDb,
+ purgeCommunityChannel,
+ purgeCommunityServer,
+ restoreAttentionScopeOptimisticSnapshot,
+ type CommunityLiveSnapshot,
+} from "./sync"
+import { useCommunityStore } from "@/stores/community"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { emptyMessageOverlay } from "@/lib/community/message-stream"
+import { writeCommunityProfilePatches } from "@/lib/community/profile-seed"
+
+const registries: CommunityDbRegistry[] = []
+const unregisters: Array<() => void> = []
+
+async function registry() {
+ const result = createCommunityDbRegistry(new QueryClient(), "viewer")
+ registries.push(result)
+ await result.preload()
+ unregisters.push(registerCommunityDbRegistry(result))
+ return result
+}
+
+function publishCommunityLiveSnapshot(
+ queryClient: QueryClient,
+ snapshot: CommunityLiveSnapshot,
+) {
+ const token = captureCommunityLiveSnapshotToken(queryClient)
+ if (snapshot.kind === "read-state") {
+ return publishCommunityLiveSnapshotWithProof(queryClient, {
+ snapshot,
+ proof: {
+ kind: "read-state",
+ token,
+ signal: undefined,
+ requestGeneration: 0,
+ currentRequestGeneration: 0,
+ targetRevision: null,
+ },
+ })
+ }
+ return publishCommunityLiveSnapshotWithProof(queryClient, {
+ snapshot,
+ proof: { kind: "structural", token, signal: undefined },
+ })
+}
+
+afterEach(async () => {
+ unregisters.splice(0).forEach((unregister) => unregister())
+ await Promise.all(registries.splice(0).map((entry) => entry.cleanup()))
+ vi.unstubAllGlobals()
+})
+
+describe("community DB sync", () => {
+ it("does not regress a known channel subtype when directory transport omits it", async () => {
+ const db = await registry()
+ ingestServers(db, { servers: [{
+ id: "s1", name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "viewer",
+ }] })
+ ingestServerDetail(db, {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer", categories: [{
+ id: "cat1", name: "General", channels: [{
+ id: "forum1", name: "Forum", active: false, unread: false, type: "forum",
+ }],
+ }],
+ })
+
+ expect(publishCommunityChannelDirectory(db.queryClient, {
+ directory: [{
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ channels: [{ id: "forum1", name: "Forum renamed" }],
+ }],
+ proof: {
+ token: captureCommunityLiveSnapshotToken(db.queryClient),
+ signal: undefined,
+ },
+ })).toBe("published")
+ expect(db.collections.channels.get("forum1")).toMatchObject({
+ name: "Forum renamed",
+ type: "forum",
+ })
+ })
+
+ it("ingests an unknown legacy directory channel as text", async () => {
+ const db = await registry()
+
+ expect(publishCommunityChannelDirectory(db.queryClient, {
+ directory: [{
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ channels: [{ id: "c1", name: "General" }],
+ }],
+ proof: {
+ token: captureCommunityLiveSnapshotToken(db.queryClient),
+ signal: undefined,
+ },
+ })).toBe("published")
+ expect(db.collections.channels.get("c1")).toMatchObject({
+ name: "General",
+ type: "text",
+ })
+ })
+
+ it("keeps anonymous canonical ingestion free of viewer access rows", async () => {
+ const db = createCommunityDbRegistry(new QueryClient(), null)
+ registries.push(db)
+ await db.preload()
+
+ ingestServers(db, { servers: [{
+ id: "s1", name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "owner",
+ }] })
+ ingestServerDetail(db, {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "owner", categories: [{
+ id: "cat1", name: "General", channels: [{
+ id: "c1", name: "general", active: false, unread: false,
+ }],
+ }],
+ })
+
+ expect([...db.collections.serverMemberships.values()]).toEqual([])
+ expect([...db.collections.channelMemberships.values()]).toEqual([])
+ })
+
+ it.each(["signal", "account", "access"] as const)(
+ "rejects a structurally stale %s proof before destructive replacement",
+ async (race) => {
+ const db = await registry()
+ useCommunityWsStore.getState().activateProfileAccount(`viewer-${race}`)
+ ingestDms(db, {
+ conversations: [{
+ id: "dm-current",
+ userId: "peer",
+ name: "Peer",
+ discriminator: "0001",
+ avatar: "P",
+ status: "offline",
+ preview: "",
+ }],
+ })
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+ const controller = new AbortController()
+ if (race === "signal") controller.abort()
+ else if (race === "account") {
+ useCommunityWsStore.getState().activateProfileAccount("viewer-next")
+ } else {
+ useCommunityWsStore.setState((state) => ({ accessEpoch: state.accessEpoch + 1 }))
+ }
+
+ expect(() => publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: { kind: "dms", data: { conversations: [] } },
+ proof: { kind: "structural", token, signal: controller.signal },
+ })).toThrowError(expect.objectContaining({ name: "AbortError" }))
+ expect(db.collections.channels.get("dm-current")).toBeDefined()
+ },
+ )
+
+ it("keeps a projected Inbox DM over an older authoritative snapshot", async () => {
+ const db = await registry()
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+ const dm = {
+ id: "dm-first-click",
+ userId: "peer",
+ name: "Peer",
+ discriminator: "0001",
+ avatar: "P",
+ status: "offline" as const,
+ preview: "",
+ unread: false,
+ }
+
+ expect(publishCommunityDmSummary(db.queryClient, dm)).toBe("published")
+ publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: { kind: "dms", data: { conversations: [] } },
+ proof: { kind: "structural", token, signal: undefined },
+ })
+
+ expect(db.collections.channels.get(dm.id)).toMatchObject({ id: dm.id, type: "dm" })
+ expect(db.collections.channelMemberships.get(`${dm.id}:viewer:access`)).toBeDefined()
+ expect(db.collections.channelMemberships.get(`${dm.id}:peer:access`)).toBeDefined()
+ expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer" })
+ })
+
+ it("preserves a same-entity WS message edit over an older HTTP response", async () => {
+ const db = await registry()
+ const staleMessage = {
+ id: "m1",
+ type: "chat" as const,
+ seq: 1,
+ content: "stale HTTP",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }
+ ingestMessages(db, "c1", [staleMessage])
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:message.edited",
+ channelId: "c1",
+ messageId: "m1",
+ content: "new WS value",
+ } as CommunityWsEvent)
+ publishCommunityMessages(db.queryClient, {
+ channelId: "c1",
+ messages: [staleMessage],
+ proof: { token, signal: undefined },
+ })
+
+ expect(db.collections.messages.get("m1")?.content).toBe("new WS value")
+ })
+
+ it("preserves a local canonical message patch over an older HTTP response", async () => {
+ const db = await registry()
+ const staleMessage = {
+ id: "m-local",
+ type: "chat" as const,
+ seq: 1,
+ content: "message",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ reactions: [{ emoji: "👍", count: 1, me: false }],
+ }
+ ingestMessages(db, "c1", [staleMessage])
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ patchCanonicalCommunityMessage(db.queryClient, "m-local", (message) => ({
+ ...message,
+ reactions: [{ emoji: "👍", count: 2, me: true }],
+ }))
+ publishCommunityMessages(db.queryClient, {
+ channelId: "c1",
+ messages: [staleMessage],
+ proof: { token, signal: undefined },
+ })
+
+ expect(db.collections.messages.get("m-local")?.reactions).toEqual([
+ { emoji: "👍", count: 2, me: true },
+ ])
+ })
+
+ it("merges a WS message edit for an absent row into an older HTTP response", async () => {
+ const db = await registry()
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:message.edited",
+ channelId: "c1",
+ messageId: "m1",
+ content: "new WS value",
+ } as CommunityWsEvent)
+ publishCommunityMessages(db.queryClient, {
+ channelId: "c1",
+ messages: [{
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ content: "stale HTTP",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }],
+ proof: { token, signal: undefined },
+ })
+
+ expect(db.collections.messages.get("m1")?.content).toBe("new WS value")
+
+ db.collections.messages.utils.writeDelete("m1")
+ db.queryClient.setQueryData(
+ communityKeys.communityDbCollection("viewer", "messages"),
+ [],
+ )
+ publishCommunityMessages(db.queryClient, {
+ channelId: "c1",
+ messages: [{
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ content: "stale HTTP replay",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }],
+ proof: { token, signal: undefined },
+ })
+ expect(db.collections.messages.get("m1")).toBeUndefined()
+ })
+
+ it("does not retain pending closures for WS patches that hit an existing row", async () => {
+ const db = await registry()
+ ingestMessages(db, "c1", [{
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ content: "seed",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }])
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+ for (let index = 0; index < 100; index += 1) {
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:message.edited",
+ channelId: "c1",
+ messageId: "m1",
+ content: `edit ${index}`,
+ } as CommunityWsEvent)
+ }
+
+ db.collections.messages.utils.writeDelete("m1")
+ db.queryClient.setQueryData(
+ communityKeys.communityDbCollection("viewer", "messages"),
+ [],
+ )
+ publishCommunityMessages(db.queryClient, {
+ channelId: "c1",
+ messages: [{
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ content: "stale HTTP",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }],
+ proof: { token, signal: undefined },
+ })
+
+ expect(db.collections.messages.get("m1")).toBeUndefined()
+ })
+
+ it("preserves same-entity WS server/channel writes over older HTTP", async () => {
+ const db = await registry()
+ const detail = {
+ id: "s1",
+ name: "Stale server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "cat1",
+ name: "General",
+ channels: [{
+ id: "c1",
+ name: "stale channel",
+ active: false,
+ unread: false,
+ type: "text" as const,
+ }, {
+ id: "c2",
+ name: "deleted channel",
+ active: false,
+ unread: false,
+ type: "text" as const,
+ }],
+ }],
+ }
+ ingestServers(db, { servers: [{
+ id: "s1", name: "Stale server", initial: "S", active: false,
+ unread: false, mentions: 0, ownerId: "viewer",
+ }] })
+ ingestServerDetail(db, detail)
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:server.update",
+ serverId: "s1",
+ changes: { name: "Fresh server" },
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.update",
+ serverId: "s1",
+ channelId: "c1",
+ changes: { name: "fresh channel" },
+ } as CommunityWsEvent)
+ publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: { kind: "server-detail", data: detail },
+ proof: { kind: "structural", token, signal: undefined },
+ })
+
+ expect(db.collections.servers.get("s1")?.name).toBe("Fresh server")
+ expect(db.collections.channels.get("c1")?.name).toBe("fresh channel")
+ })
+
+ it("promotes server detail completeness over a newer WS server update", async () => {
+ const db = await registry()
+ ingestServers(db, { servers: [{
+ id: "s1", name: "Stale server", initial: "S", active: false,
+ unread: false, mentions: 0, ownerId: "viewer",
+ }] })
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:server.update",
+ serverId: "s1",
+ changes: { name: "Fresh server" },
+ } as CommunityWsEvent)
+ publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: {
+ kind: "server-detail",
+ data: {
+ id: "s1", name: "Stale server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer", categories: [{
+ id: "cat1", name: "General", channels: [{
+ id: "c1", name: "general", active: false, unread: false,
+ }],
+ }],
+ },
+ },
+ proof: { kind: "structural", token, signal: undefined },
+ })
+
+ expect(db.collections.servers.get("s1")).toMatchObject({
+ name: "Fresh server",
+ detailComplete: true,
+ })
+ expect(db.collections.channels.get("c1")?.name).toBe("general")
+ })
+
+ it("merges a WS channel update for an absent row into older HTTP", async () => {
+ const db = await registry()
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+ const detail = {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer", categories: [{
+ id: "cat1", name: "General", channels: [{
+ id: "c1", name: "stale channel", active: false, unread: false,
+ type: "text" as const,
+ }],
+ }],
+ }
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.update",
+ serverId: "s1",
+ channelId: "c1",
+ changes: { name: "fresh channel" },
+ } as CommunityWsEvent)
+ publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: { kind: "server-detail", data: detail },
+ proof: { kind: "structural", token, signal: undefined },
+ })
+
+ expect(db.collections.channels.get("c1")?.name).toBe("fresh channel")
+ })
+
+ it("does not revive a channel deleted after an HTTP request starts", async () => {
+ const db = await registry()
+ const detail = {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer", categories: [{
+ id: "cat1", name: "General", channels: [{
+ id: "c1", name: "deleted channel", active: false, unread: false,
+ type: "text" as const,
+ }],
+ }],
+ }
+ ingestServers(db, { servers: [{
+ id: "s1", name: "Server", initial: "S", active: false,
+ unread: false, mentions: 0, ownerId: "viewer",
+ }] })
+ ingestServerDetail(db, detail)
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.delete",
+ serverId: "s1",
+ channelId: "c1",
+ } as CommunityWsEvent)
+ expect(() => publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: { kind: "server-detail", data: detail },
+ proof: { kind: "structural", token, signal: undefined },
+ })).toThrowError(expect.objectContaining({ name: "AbortError" }))
+ expect(db.collections.channels.get("c1")).toBeUndefined()
+ })
+
+ it("keeps an absent WS-deleted channel out of an older HTTP response", async () => {
+ const db = await registry()
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+ const detail = {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer", categories: [{
+ id: "cat1", name: "General", channels: [{
+ id: "c1", name: "deleted channel", active: false, unread: false,
+ type: "text" as const,
+ }],
+ }],
+ }
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.delete",
+ serverId: "s1",
+ channelId: "c1",
+ } as CommunityWsEvent)
+ expect(publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: { kind: "server-detail", data: detail },
+ proof: { kind: "structural", token, signal: undefined },
+ })).toBe("published")
+
+ expect(db.collections.channels.get("c1")).toBeUndefined()
+ })
+
+ it("rejects a superseded read-state freshness proof before replacement", async () => {
+ const db = await registry()
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "read-state",
+ data: {
+ revision: 1,
+ readStates: [
+ { channelId: "c1", lastReadMessageId: null, lastReadAt: "2026-09-26T00:00:00.000Z", lastReadSeq: 1 },
+ { channelId: "c2", lastReadMessageId: null, lastReadAt: "2026-09-26T00:00:00.000Z", lastReadSeq: 2 },
+ ],
+ },
+ })
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ expect(publishCommunityLiveSnapshotWithProof(db.queryClient, {
+ snapshot: {
+ kind: "read-state",
+ data: {
+ revision: 2,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: null,
+ lastReadAt: "2026-09-26T00:00:01.000Z",
+ lastReadSeq: 3,
+ }],
+ },
+ },
+ proof: {
+ kind: "read-state",
+ token,
+ signal: undefined,
+ requestGeneration: 1,
+ currentRequestGeneration: 2,
+ targetRevision: 2,
+ },
+ })).toBe("superseded")
+ expect(db.collections.readStates.get("c2")).toBeDefined()
+ })
+
+ it("never treats raw server-detail query keys as canonical writers", async () => {
+ const db = await registry()
+ const uninstall = installCommunityDbSync(db.queryClient, db)
+
+ db.queryClient.setQueryData(communityKeys.channelRefDirectory(), [{
+ channelId: "channel-directory-only",
+ serverId: "not-a-detail",
+ }])
+ db.queryClient.setQueryData(communityKeys.server("__none__"), { sentinel: true })
+ db.queryClient.setQueryData(communityKeys.server("__pending__"), { sentinel: true })
+ expect(db.collections.servers.size).toBe(0)
+
+ db.queryClient.setQueryData(communityKeys.server("s1"), {
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [],
+ })
+ expect(db.collections.servers.get("s1")).toBeUndefined()
+ uninstall()
+ })
+
+ it("does not replay hydrated or setQueryData transport payloads into canonical DB", async () => {
+ const db = await registry()
+ db.queryClient.setQueryData(communityKeys.servers(), { servers: [{
+ id: "s1", name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "viewer",
+ }] })
+ db.queryClient.setQueryData(communityKeys.dms(), { conversations: [{
+ id: "dm1", userId: "peer", name: "Peer", discriminator: "0002",
+ avatar: "P", avatarVersion: 1, status: "offline", preview: "hello",
+ }] })
+ db.queryClient.getQueryCache().build(db.queryClient, {
+ queryKey: ["community", "pending-ingest"],
+ queryFn: async () => null,
+ })
+ const uninstall = installCommunityDbSync(db.queryClient, db)
+ await db.preload()
+ expect(db.collections.servers.get("s1")).toBeUndefined()
+ expect(db.collections.channels.get("dm1")).toBeUndefined()
+ db.queryClient.setQueryData(communityKeys.folders(), {
+ folders: [{
+ id: "f1", name: "Folder", position: 1,
+ servers: [{ id: "s1", name: "Server", initial: "S", icon: null }],
+ }],
+ })
+ db.queryClient.setQueryData(communityKeys.channelMeta("s1", "c1"), {
+ id: "c1", serverId: "s1", name: "chat", type: "text",
+ parentChannelId: null, parentMessageId: null, creatorId: null,
+ archived: 0, lastMessageAt: null,
+ })
+ db.queryClient.setQueryData(communityKeys.channelMeta("s1", "c1"), {
+ id: "c1", serverId: "s1", name: "chat renamed", type: "text",
+ parentChannelId: null, parentMessageId: null, creatorId: null,
+ archived: 1, lastMessageAt: null,
+ })
+ db.queryClient.setQueryData(communityKeys.channelMeta("s1", "ignored"), {
+ id: "ignored", serverId: "s1", name: "ignored", type: "dm",
+ parentChannelId: null, parentMessageId: null, creatorId: null,
+ archived: 0, lastMessageAt: null,
+ })
+ db.queryClient.setQueryData(communityKeys.channelMessages("c1"), {
+ pages: [{ messages: [{
+ id: "page-message", type: "chat", authorId: "peer", authorName: "Peer",
+ content: "page", createdAt: "2026-09-25T00:00:00.000Z",
+ }] }],
+ pageParams: [null],
+ })
+ db.queryClient.setQueryData(communityKeys.messageContext("channel", "c1", 1), {
+ messages: [{
+ id: "context-message", type: "chat", authorId: "peer", authorName: "Peer",
+ content: "context", createdAt: "2026-09-25T00:00:01.000Z",
+ }],
+ })
+ db.queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 2,
+ readStates: [{
+ channelId: "c1", lastReadMessageId: "page-message",
+ lastReadAt: "2026-09-25T00:00:02.000Z", lastReadSeq: 2,
+ }],
+ })
+ db.queryClient.setQueryData(communityKeys.notificationSettings(), {
+ raw: [
+ { serverId: "s1", level: "all" },
+ { channelId: "c1", level: "mentions" },
+ { serverId: "s1", channelId: "c1", level: "nothing" },
+ ],
+ server: {},
+ channel: {},
+ })
+ db.queryClient.setQueryData(communityKeys.folders(), {
+ folders: [{ id: "f2", name: "Replacement", position: 0, servers: [] }],
+ })
+ db.queryClient.setQueryData(communityKeys.notificationSettings(), {
+ raw: [{ channelId: "c1", level: "nothing" }],
+ server: {},
+ channel: {},
+ })
+ db.queryClient.setQueryData(communityKeys.channelMessages("empty"), {})
+ db.queryClient.setQueryData(communityKeys.forumFeed("c1", "all"), {})
+ db.queryClient.setQueryData(communityKeys.forumFeed("c1", "invalid"), {
+ pages: [{ included: { parentMessages: [{ id: 42, channelId: "c1" }] } }],
+ pageParams: [null],
+ })
+
+ expect(db.collections.folders.get("f1")).toBeUndefined()
+ expect(db.collections.folders.get("f2")).toBeUndefined()
+ expect(db.collections.folderItems.get("f1:s1")).toBeUndefined()
+ expect(db.collections.channels.get("c1")).toBeUndefined()
+ expect(db.collections.channels.get("ignored")).toBeUndefined()
+ expect(db.collections.messages.get("page-message")).toBeUndefined()
+ expect(db.collections.messages.get("context-message")).toBeUndefined()
+ expect(db.collections.readStateClock.get("account")).toBeUndefined()
+ expect([...db.collections.notificationSettings.keys()]).toEqual([])
+ uninstall()
+ })
+
+ it("never deletes or revokes from cached-success replay", async () => {
+ const db = await registry()
+ const uninstall = installCommunityDbSync(db.queryClient, db)
+ const server = (id: string) => ({
+ id,
+ name: id,
+ initial: id[0]!.toUpperCase(),
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ })
+ const dm = (id: string, userId: string) => ({
+ id,
+ userId,
+ name: userId,
+ discriminator: "0001",
+ avatar: userId[0]!.toUpperCase(),
+ avatarVersion: 1,
+ status: "offline" as const,
+ preview: "",
+ })
+ const detail = (channelIds: string[]) => ({
+ id: "merge-s1",
+ name: "Merge",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "merge-cat",
+ name: "General",
+ channels: channelIds.map((id) => ({
+ id,
+ name: id,
+ active: false,
+ unread: false,
+ })),
+ }],
+ })
+
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "servers",
+ data: { servers: [server("merge-s1"), server("merge-s2")] },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "server-detail",
+ data: detail(["merge-c1", "merge-c2"]),
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "dms",
+ data: { conversations: [dm("merge-dm1", "peer1"), dm("merge-dm2", "peer2")] },
+ })
+ 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, {
+ kind: "read-state",
+ data: {
+ revision: 1,
+ readStates: [
+ { channelId: "merge-c1", lastReadMessageId: null, lastReadAt: "2026-09-26T00:00:00.000Z", lastReadSeq: 1 },
+ { channelId: "merge-c2", lastReadMessageId: null, lastReadAt: "2026-09-26T00:00:00.000Z", lastReadSeq: 2 },
+ ],
+ },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "notification-settings",
+ data: {
+ raw: [
+ { serverId: "merge-s1", level: "all" },
+ { channelId: "merge-c2", level: "mentions" },
+ ],
+ server: {},
+ channel: {},
+ },
+ })
+
+ db.queryClient.setQueryData(communityKeys.servers(), {
+ servers: [server("merge-s1")],
+ })
+ db.queryClient.setQueryData(communityKeys.server("merge-s1"), detail(["merge-c1"]))
+ db.queryClient.setQueryData(communityKeys.dms(), {
+ conversations: [dm("merge-dm1", "peer1")],
+ })
+ db.queryClient.setQueryData(communityKeys.folders(), {
+ folders: [{ id: "merge-f1", name: "One", position: 0, servers: [] }],
+ })
+ db.queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 2,
+ readStates: [{
+ channelId: "merge-c1",
+ lastReadMessageId: null,
+ lastReadAt: "2026-09-26T00:00:01.000Z",
+ lastReadSeq: 3,
+ }],
+ })
+ db.queryClient.setQueryData(communityKeys.notificationSettings(), {
+ raw: [{ serverId: "merge-s1", level: "nothing" }],
+ server: {},
+ channel: {},
+ })
+ void db.queryClient.invalidateQueries({
+ queryKey: communityKeys.servers(),
+ exact: true,
+ refetchType: "none",
+ })
+
+ expect(db.collections.servers.get("merge-s2")).toBeDefined()
+ expect(useCommunityWsStore.getState().revokedServerIds.has("merge-s2")).toBe(false)
+ expect(db.collections.channels.get("merge-c2")).toBeDefined()
+ expect(db.collections.channels.get("merge-dm2")).toBeDefined()
+ expect(db.collections.folders.get("merge-f2")).toBeDefined()
+ expect(db.collections.readStates.get("merge-c2")).toBeDefined()
+ expect(db.collections.notificationSettings.get("channel:merge-c2")).toBeDefined()
+ uninstall()
+ })
+
+ it("gives destructive replacement only to live publishers and explicit events", async () => {
+ const db = await registry()
+ const server = (id: string) => ({
+ id,
+ name: id,
+ initial: id[0]!.toUpperCase(),
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ })
+ const dm = (id: string, userId: string) => ({
+ id,
+ userId,
+ name: userId,
+ discriminator: "0001",
+ avatar: userId[0]!.toUpperCase(),
+ avatarVersion: 1,
+ status: "offline" as const,
+ preview: "",
+ })
+ const detail = (channelIds: string[]) => ({
+ id: "live-s1",
+ name: "Live",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "live-cat",
+ name: "General",
+ channels: channelIds.map((id) => ({
+ id,
+ name: id,
+ active: false,
+ unread: false,
+ })),
+ }],
+ })
+
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "servers",
+ data: { servers: [server("live-s1"), server("live-s2")] },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "server-detail",
+ data: detail(["live-c1", "live-c2"]),
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "dms",
+ data: { conversations: [dm("live-dm1", "peer1"), dm("live-dm2", "peer2")] },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "folders",
+ data: { folders: [
+ {
+ id: "live-f1",
+ name: "One",
+ position: 0,
+ servers: [{ id: "live-s1", name: "Live one", initial: "L", icon: null }],
+ },
+ {
+ id: "live-f2",
+ name: "Two",
+ position: 1,
+ servers: [{ id: "live-s2", name: "Live two", initial: "L", icon: null }],
+ },
+ ] },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "read-state",
+ data: {
+ revision: 1,
+ readStates: [
+ { channelId: "live-c1", lastReadMessageId: null, lastReadAt: "2026-09-26T00:00:00.000Z", lastReadSeq: 1 },
+ { channelId: "live-c2", lastReadMessageId: null, lastReadAt: "2026-09-26T00:00:00.000Z", lastReadSeq: 2 },
+ ],
+ },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "notification-settings",
+ data: {
+ raw: [
+ { serverId: "live-s1", level: "all" },
+ { channelId: "live-c2", level: "mentions" },
+ ],
+ server: {},
+ channel: {},
+ },
+ })
+
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "server-detail",
+ data: detail(["live-c1"]),
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "dms",
+ data: { conversations: [dm("live-dm1", "peer1")] },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "folders",
+ data: { folders: [{
+ id: "live-f1",
+ name: "One",
+ position: 0,
+ servers: [{ id: "live-s1", name: "Live one", initial: "L", icon: null }],
+ }] },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "read-state",
+ data: {
+ revision: 2,
+ readStates: [{
+ channelId: "live-c1",
+ lastReadMessageId: null,
+ lastReadAt: "2026-09-26T00:00:01.000Z",
+ lastReadSeq: 3,
+ }],
+ },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "notification-settings",
+ data: {
+ raw: [{ serverId: "live-s1", level: "nothing" }],
+ server: {},
+ channel: {},
+ },
+ })
+ publishCommunityLiveSnapshot(db.queryClient, {
+ kind: "servers",
+ data: { servers: [server("live-s1")] },
+ })
+
+ expect(db.collections.servers.get("live-s2")).toBeUndefined()
+ expect(useCommunityWsStore.getState().revokedServerIds.has("live-s2")).toBe(true)
+ expect(db.collections.channels.get("live-c2")).toBeUndefined()
+ expect(useCommunityWsStore.getState().isChannelAccessRevoked("live-c2", "live-s1")).toBe(true)
+ expect(db.collections.channels.get("live-dm2")).toBeUndefined()
+ expect(db.collections.folders.get("live-f2")).toBeUndefined()
+ expect(db.collections.folderItems.get("live-f2:live-s2")).toBeUndefined()
+ expect(db.collections.readStates.get("live-c2")).toBeUndefined()
+ expect(db.collections.notificationSettings.get("channel:live-c2")).toBeUndefined()
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:server.delete",
+ serverId: "live-s1",
+ } as CommunityWsEvent)
+ expect(db.collections.servers.get("live-s1")).toBeUndefined()
+ expect(useCommunityWsStore.getState().revokedServerIds.has("live-s1")).toBe(true)
+ useCommunityWsStore.getState().grantServerAccess("live-s1")
+ useCommunityWsStore.getState().grantServerAccess("live-s2")
+ })
+
+ it("preserves completed server detail when the rail identity refreshes", async () => {
+ const db = await registry()
+ const rail = {
+ id: "s1",
+ name: "Server",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ }
+
+ ingestServers(db, { servers: [rail] })
+ expect(db.collections.servers.get("s1")?.detailComplete).toBe(false)
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [],
+ })
+ expect(db.collections.servers.get("s1")?.detailComplete).toBe(true)
+ ingestServerDetail(db, {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer",
+ categories: [{
+ id: "cat1", name: "General",
+ channels: [{ id: "c1", name: "chat", active: false, unread: false }],
+ }],
+ })
+ ingestServerDetail(db, {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer",
+ categories: [{
+ id: "cat1", name: "General",
+ channels: [{ id: "c1", name: "renamed", active: false, unread: false }],
+ }],
+ })
+ ingestServers(db, { servers: [rail] })
+ expect(db.collections.servers.get("s1")?.detailComplete).toBe(true)
+ expect(getActiveCommunityDbRegistry()).toBe(db)
+
+ const originalGetQueryData = db.queryClient.getQueryData.bind(db.queryClient)
+ const collectionKey = communityKeys.communityDbCollection(db.scopeId, "servers")
+ const getQueryData = vi.spyOn(db.queryClient, "getQueryData").mockImplementation((key) => (
+ JSON.stringify(key) === JSON.stringify(collectionKey)
+ ? undefined
+ : originalGetQueryData(key)
+ ))
+ ingestServers(db, { servers: [rail] })
+ getQueryData.mockRestore()
+ })
+
+ it("normalizes server, tree, and DM relationships into canonical identities", async () => {
+ const db = await registry()
+ ingestServers(db, {
+ servers: [{
+ id: "s1",
+ name: "Alook",
+ discriminator: "0001",
+ description: "",
+ ownerId: "viewer",
+ initial: "A",
+ active: false,
+ unread: false,
+ mentions: 0,
+ isOwner: true,
+ }],
+ })
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Alook",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "cat1",
+ name: "General",
+ channels: [{
+ id: "c1",
+ name: "chat",
+ active: false,
+ unread: false,
+ type: "text",
+ }],
+ }],
+ })
+ ingestDms(db, {
+ conversations: [{
+ id: "dm1",
+ userId: "peer",
+ name: "Peer",
+ discriminator: "0002",
+ avatar: "P",
+ avatarVersion: 1,
+ status: "offline",
+ preview: "hello",
+ unread: true,
+ lastUnreadSeq: 7,
+ }],
+ })
+
+ expect(db.collections.servers.get("s1")).toMatchObject({ ownerId: "viewer" })
+ expect(db.collections.serverMemberships.get("s1:viewer")).toMatchObject({ viewer: true })
+ 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")).toMatchObject({
+ relation: "access",
+ source: "inherited",
+ })
+ expect(db.collections.channels.get("dm1")).toMatchObject({ type: "dm", serverId: null })
+ expect(db.collections.channelMemberships.get("dm1:viewer:access")).toBeDefined()
+ expect(db.collections.channelMemberships.get("dm1:peer:access")).toBeDefined()
+ expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer" })
+ })
+
+ it("keeps read-state replacement monotonic", async () => {
+ const db = await registry()
+ ingestReadStateSnapshot(db, {
+ revision: 4,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m4",
+ lastReadAt: "2026-09-25T00:00:00.000Z",
+ lastReadSeq: 4,
+ }],
+ })
+ ingestReadStateSnapshot(db, {
+ revision: 3,
+ readStates: [],
+ })
+ ingestReadStateSnapshot(db, {
+ revision: 4,
+ readStates: [],
+ })
+ expect(db.collections.readStateClock.get("account")?.revision).toBe(4)
+ expect(db.collections.readStates.get("c1")?.lastReadSeq).toBe(4)
+ ingestReadStateSnapshot(db, {
+ revision: 5,
+ readStates: [],
+ })
+ expect(db.collections.readStateClock.get("account")?.revision).toBe(5)
+ expect(db.collections.readStates.get("c1")).toBeUndefined()
+ })
+
+ it("preserves a WS fact that exists before an older snapshot request begins", async () => {
+ const db = await registry()
+ const scope = {
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: 4,
+ attentionCount: 1,
+ }
+ projectAttentionUnreadBump(db.queryClient, {
+ type: "community:unread.bump",
+ userId: db.accountId,
+ channelId: "c1",
+ serverId: "s1",
+ isMention: true,
+ }, { seq: 4 })
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+
+ expect(publishAccountAttentionSnapshot(db.queryClient, {
+ snapshot: { scopes: [], items: [], limit: 100, truncated: false },
+ proof: { token, signal: undefined },
+ })).toBe("published")
+ expect(db.collections.attentionScopes.get("c1")).toMatchObject(scope)
+ })
+
+ it("does not roll back an optimistic clear started before or during a snapshot GET", async () => {
+ const db = await registry()
+ const scope = {
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: 4,
+ attentionCount: 1,
+ }
+ ingestAttentionSnapshot(db, { scopes: [scope], items: [], limit: 100, truncated: false })
+
+ const before = clearAttentionOptimistically(db)
+ const beforeToken = captureCommunityLiveSnapshotToken(db.queryClient)
+ publishAccountAttentionSnapshot(db.queryClient, {
+ snapshot: { scopes: [scope], items: [], limit: 100, truncated: false },
+ proof: { token: beforeToken, signal: undefined },
+ })
+ expect(db.collections.attentionScopes.get("c1")).toBeUndefined()
+ commitAttentionOptimisticSnapshot(db, before)
+
+ ingestAttentionSnapshot(db, { scopes: [scope], items: [], limit: 100, truncated: false })
+ const duringToken = captureCommunityLiveSnapshotToken(db.queryClient)
+ const during = clearAttentionOptimistically(db)
+ publishAccountAttentionSnapshot(db.queryClient, {
+ snapshot: { scopes: [scope], items: [], limit: 100, truncated: false },
+ proof: { token: duringToken, signal: undefined },
+ })
+ expect(db.collections.attentionScopes.get("c1")).toBeUndefined()
+ commitAttentionOptimisticSnapshot(db, during)
+ })
+
+ it("keeps a higher-seq scope and item through a target-seq attention reconcile", async () => {
+ const db = await registry()
+ ingestMessages(db, "c1", [
+ {
+ id: "m4",
+ type: "chat",
+ authorId: "u2",
+ seq: 4,
+ createdAt: "2026-09-27T01:00:00.000Z",
+ },
+ {
+ id: "m5",
+ type: "chat",
+ authorId: "u2",
+ seq: 5,
+ createdAt: "2026-09-27T01:01:00.000Z",
+ },
+ ])
+ const oldItem = {
+ id: "mention:old",
+ kind: "mention" as const,
+ sourceId: "old",
+ scopeId: "c1",
+ messageId: "m4",
+ actorUserId: "u2",
+ createdAt: "2026-09-27T01:00:00.000Z",
+ }
+ const newItem = {
+ id: "mention:new",
+ kind: "mention" as const,
+ sourceId: "new",
+ scopeId: "c1",
+ messageId: "m5",
+ actorUserId: "u2",
+ createdAt: "2026-09-27T01:01:00.000Z",
+ }
+ const oldScope = {
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: 4,
+ attentionCount: 1,
+ }
+ ingestAttentionSnapshot(db, {
+ scopes: [{
+ ...oldScope,
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 2,
+ }],
+ items: [newItem, oldItem],
+ limit: 100,
+ truncated: false,
+ })
+ expect(db.collections.messages.get("m5")?.seq).toBe(5)
+ expect(db.collections.attentionScopes.get("c1")?.lastUnreadSeq).toBe(5)
+ const optimistic = clearAttentionScopeOptimistically(db, "c1", 4)
+ expect(db.collections.attentionScopes.get("c1")).toMatchObject({
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 1,
+ })
+ expect(db.collections.attentionItems.get(oldItem.id)).toBeUndefined()
+ expect(db.collections.attentionItems.get(newItem.id)).toMatchObject(newItem)
+
+ ingestAttentionSnapshot(db, {
+ scopes: [{
+ ...oldScope,
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 2,
+ }],
+ items: [newItem, oldItem],
+ limit: 100,
+ truncated: false,
+ })
+ commitAttentionScopeOptimisticSnapshot(db, optimistic)
+
+ expect(db.collections.attentionScopes.get("c1")).toMatchObject({
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 1,
+ })
+ expect(db.collections.attentionItems.get(oldItem.id)).toBeUndefined()
+ expect(db.collections.attentionItems.get(newItem.id)).toMatchObject(newItem)
+ })
+
+ it.each(["success", "failure"] as const)(
+ "uses the exact aggregate baseline for a truncated target-seq %s",
+ async (terminal) => {
+ const db = await registry()
+ ingestMessages(db, "c1", [{
+ id: "m4",
+ type: "chat",
+ authorId: "u2",
+ seq: 4,
+ createdAt: "2026-09-27T01:00:00.000Z",
+ }, {
+ id: "m5",
+ type: "chat",
+ authorId: "u2",
+ seq: 5,
+ createdAt: "2026-09-27T01:01:00.000Z",
+ }, {
+ id: "m6",
+ type: "chat",
+ authorId: "u2",
+ seq: 6,
+ createdAt: "2026-09-27T01:02:00.000Z",
+ }])
+ const newItem = {
+ id: "mention:new",
+ kind: "mention" as const,
+ sourceId: "new",
+ scopeId: "c1",
+ messageId: "m5",
+ actorUserId: "u2",
+ createdAt: "2026-09-27T01:01:00.000Z",
+ }
+ const truncatedSnapshot = {
+ scopes: [{
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 151,
+ }],
+ items: [newItem],
+ limit: 100,
+ truncated: true,
+ }
+ ingestAttentionSnapshot(db, truncatedSnapshot)
+
+ const optimistic = clearAttentionScopeOptimistically(db, "c1", 4)
+ expect(optimistic.clearedAttentionCount).toBe(150)
+ expect(db.collections.attentionScopes.get("c1")).toMatchObject({
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 1,
+ })
+ expect(db.collections.attentionItems.get(newItem.id)).toMatchObject(newItem)
+ projectAttentionUnreadBump(db.queryClient, {
+ type: "community:unread.bump",
+ userId: "viewer",
+ channelId: "c1",
+ serverId: "s1",
+ isMention: true,
+ }, { seq: 4 })
+ projectAttentionMentionHint(db.queryClient, {
+ type: "community:mention.create",
+ userId: "viewer",
+ channelId: "c1",
+ messageId: "m4",
+ authorName: "Peer",
+ })
+ expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(1)
+ expect(db.collections.attentionItems.get("pending:m4")).toBeUndefined()
+
+ if (terminal === "success") {
+ ingestAttentionSnapshot(db, truncatedSnapshot)
+ commitAttentionScopeOptimisticSnapshot(db, optimistic)
+ expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(1)
+ } else {
+ projectAttentionUnreadBump(db.queryClient, {
+ type: "community:unread.bump",
+ userId: "viewer",
+ channelId: "c1",
+ serverId: "s1",
+ isMention: true,
+ }, { seq: 6 })
+ projectAttentionMentionHint(db.queryClient, {
+ type: "community:mention.create",
+ userId: "viewer",
+ channelId: "c1",
+ messageId: "m6",
+ authorName: "Peer",
+ })
+ expect(restoreAttentionScopeOptimisticSnapshot(db, optimistic)).toBe(false)
+ expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(2)
+ expect(db.collections.attentionItems.get("pending:m6")).toMatchObject({
+ messageId: "m6",
+ })
+ }
+ expect(db.collections.attentionItems.get(newItem.id)).toMatchObject(newItem)
+ },
+ )
+
+ it.each(["older-first", "newer-first", "rollback-older", "rollback-both"] as const)(
+ "does not double-subtract nested scope fences when %s settles",
+ async (settledFirst) => {
+ const db = await registry()
+ ingestMessages(db, "c1", [{
+ id: "m4",
+ type: "chat",
+ authorId: "u2",
+ seq: 4,
+ }, {
+ id: "m5",
+ type: "chat",
+ authorId: "u2",
+ seq: 5,
+ }])
+ const items = [4, 5].map((seq) => ({
+ id: `mention:${seq}`,
+ kind: "mention" as const,
+ sourceId: String(seq),
+ scopeId: "c1",
+ messageId: `m${seq}`,
+ actorUserId: "u2",
+ createdAt: `2026-09-27T01:0${seq}:00.000Z`,
+ }))
+ const snapshot = {
+ scopes: [{
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 2,
+ }],
+ items,
+ limit: 100,
+ truncated: false,
+ }
+ ingestAttentionSnapshot(db, snapshot)
+ const older = clearAttentionScopeOptimistically(db, "c1", 4)
+ const newer = clearAttentionScopeOptimistically(db, "c1", 5)
+
+ ingestAttentionSnapshot(db, snapshot)
+ expect(db.collections.attentionScopes.get("c1")).toBeUndefined()
+ if (settledFirst === "older-first") {
+ commitAttentionScopeOptimisticSnapshot(db, older)
+ expect(restoreAttentionScopeOptimisticSnapshot(db, newer)).toBe(true)
+ expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(1)
+ expect(db.collections.attentionItems.get("mention:4")).toBeUndefined()
+ expect(db.collections.attentionItems.get("mention:5")).toBeDefined()
+ } else if (settledFirst === "newer-first") {
+ commitAttentionScopeOptimisticSnapshot(db, newer)
+ expect(restoreAttentionScopeOptimisticSnapshot(db, older)).toBe(false)
+ expect(db.collections.attentionScopes.get("c1")).toBeUndefined()
+ } else {
+ expect(restoreAttentionScopeOptimisticSnapshot(db, older)).toBe(false)
+ ingestAttentionSnapshot(db, snapshot)
+ expect(db.collections.attentionScopes.get("c1")).toBeUndefined()
+ if (settledFirst === "rollback-older") {
+ commitAttentionScopeOptimisticSnapshot(db, newer)
+ } else {
+ expect(restoreAttentionScopeOptimisticSnapshot(db, newer)).toBe(false)
+ ingestAttentionSnapshot(db, snapshot)
+ expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(2)
+ }
+ }
+ },
+ )
+
+ it("merges a committed fence into the newest of multiple successors", async () => {
+ const db = await registry()
+ ingestMessages(db, "c1", [4, 5, 6].map((seq) => ({
+ id: `m${seq}`,
+ type: "chat" as const,
+ authorId: "u2",
+ seq,
+ })))
+ const items = [4, 5, 6].map((seq) => ({
+ id: `mention:${seq}`,
+ kind: "mention" as const,
+ sourceId: String(seq),
+ scopeId: "c1",
+ messageId: `m${seq}`,
+ actorUserId: "u2",
+ createdAt: `2026-09-27T01:0${seq}:00.000Z`,
+ }))
+ ingestAttentionSnapshot(db, {
+ scopes: [{
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 6,
+ lastAttentionSeq: 6,
+ attentionCount: 3,
+ }],
+ items,
+ limit: 100,
+ truncated: false,
+ })
+ const oldest = clearAttentionScopeOptimistically(db, "c1", 4)
+ const middle = clearAttentionScopeOptimistically(db, "c1", 5)
+ const newest = clearAttentionScopeOptimistically(db, "c1", 6)
+
+ commitAttentionScopeOptimisticSnapshot(db, oldest)
+ commitAttentionScopeOptimisticSnapshot(db, middle)
+ expect(restoreAttentionScopeOptimisticSnapshot(db, newest)).toBe(true)
+ expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(1)
+ expect(db.collections.attentionItems.get("mention:6")).toBeDefined()
+ })
+
+ it("preserves a higher-seq WS scope and item when the older optimistic read fails", async () => {
+ const db = await registry()
+ ingestMessages(db, "c1", [{
+ id: "m5",
+ type: "chat",
+ authorId: "u2",
+ seq: 5,
+ createdAt: "2026-09-27T01:01:00.000Z",
+ }])
+ ingestAttentionSnapshot(db, {
+ scopes: [{
+ scopeId: "c1",
+ channelId: "c1",
+ serverId: "s1",
+ parentChannelId: null,
+ ordinaryUnread: true,
+ lastUnreadSeq: 4,
+ lastAttentionSeq: 4,
+ attentionCount: 1,
+ }],
+ items: [{
+ id: "mention:old",
+ kind: "mention",
+ sourceId: "old",
+ scopeId: "c1",
+ messageId: "m4",
+ actorUserId: "u2",
+ createdAt: "2026-09-27T01:00:00.000Z",
+ }],
+ limit: 100,
+ truncated: false,
+ })
+ const optimistic = clearAttentionScopeOptimistically(db, "c1", 4)
+ projectAttentionUnreadBump(db.queryClient, {
+ type: "community:unread.bump",
+ userId: "viewer",
+ channelId: "c1",
+ serverId: "s1",
+ isMention: true,
+ }, { seq: 5 })
+ projectAttentionMentionHint(db.queryClient, {
+ type: "community:mention.create",
+ userId: "viewer",
+ channelId: "c1",
+ messageId: "m5",
+ authorName: "Peer",
+ })
+
+ expect(restoreAttentionScopeOptimisticSnapshot(db, optimistic)).toBe(false)
+ expect(db.collections.attentionScopes.get("c1")).toMatchObject({
+ lastUnreadSeq: 5,
+ lastAttentionSeq: 5,
+ attentionCount: 1,
+ })
+ expect(db.collections.attentionItems.get("pending:m5")).toMatchObject({
+ messageId: "m5",
+ })
+ expect(db.collections.attentionItems.get("mention:old")).toBeUndefined()
+ })
+
+ it("merges partial attention hydration without erasing richer profile or message fields", async () => {
+ const db = await registry()
+ writeCommunityProfilePatches([{
+ id: "u2",
+ identityAbout: {
+ name: "Alice",
+ discriminator: "0002",
+ aboutMe: "rich bio",
+ ownerUserId: "owner",
+ },
+ avatar: { avatar: "rich.png", avatarVersion: 2 },
+ status: { statusEmoji: "🌿", statusText: "Shipping" },
+ }], db)
+ ingestMessages(db, "c1", [{
+ id: "m1",
+ channelId: "c1",
+ type: "chat",
+ authorId: "u2",
+ authorName: "Alice",
+ content: "rich",
+ attachments: [{ id: "a1", name: "proof.png" }],
+ replyTo: { id: "m0", authorId: "u3", authorName: "Bob", content: "earlier" },
+ }])
+
+ ingestAttentionSnapshot(db, {
+ scopes: [],
+ items: [],
+ limit: 100,
+ truncated: false,
+ included: {
+ profiles: [{
+ userId: "u2",
+ name: "Alice Updated",
+ discriminator: "0002",
+ avatar: "base.png",
+ avatarVersion: 2,
+ }],
+ messages: [{
+ id: "m1",
+ channelId: "c1",
+ type: "chat",
+ authorId: "u2",
+ content: "new preview",
+ }],
+ },
+ })
+
+ expect(db.collections.profiles.get("u2")).toMatchObject({
+ name: "Alice Updated",
+ aboutMe: "rich bio",
+ ownerUserId: "owner",
+ statusEmoji: "🌿",
+ statusText: "Shipping",
+ })
+ expect(db.collections.messages.get("m1")).toMatchObject({
+ content: "new preview",
+ attachments: [{ id: "a1", name: "proof.png" }],
+ replyTo: { id: "m0", authorId: "u3" },
+ })
+ })
+
+ it("cascades roots removed by authoritative server, tree, and DM replacement", async () => {
+ const db = await registry()
+ const navigationMemory = new Map<string, string>()
+ vi.stubGlobal("window", {})
+ vi.stubGlobal("localStorage", {
+ getItem: (key: string) => navigationMemory.get(key) ?? null,
+ setItem: (key: string, value: string) => navigationMemory.set(key, value),
+ removeItem: (key: string) => navigationMemory.delete(key),
+ })
+ const unreadProjection = getAccountUnreadProjection(db.queryClient, "viewer")
+ ingestServers(db, {
+ servers: [{
+ id: "s1", name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "viewer",
+ }],
+ })
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "cat1",
+ name: "General",
+ channels: [{ id: "c1", name: "chat", active: false, unread: false }],
+ }],
+ })
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.child_create",
+ parentChannelId: "c1",
+ parentMessageId: "opener",
+ channel: {
+ id: "thread1", name: "Thread", type: "thread",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ },
+ } as CommunityWsEvent)
+ ingestMessages(db, "thread1", [{
+ id: "m1", type: "chat", authorId: "thread-author", authorName: "Thread Author",
+ content: "thread", createdAt: "2026-09-25T00:00:01.000Z",
+ }])
+ unreadProjection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
+ db.queryClient.setQueryData(communityKeys.inboxUnreads(), {
+ friendRequests: [],
+ servers: [{
+ serverId: "s1",
+ serverName: "Server",
+ channels: [{
+ channelId: "c1",
+ channelName: "chat",
+ lastMessageAt: "2026-09-25T00:00:00.000Z",
+ mentionCount: 0,
+ children: [{
+ channelId: "thread1",
+ channelName: "Thread",
+ lastMessageAt: "2026-09-25T00:00:01.000Z",
+ mentionCount: 0,
+ }],
+ }],
+ }],
+ dms: [],
+ })
+ setLastChannel("s1", "c1")
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [],
+ })
+ expect(db.collections.channels.get("c1")).toBeUndefined()
+ expect(db.collections.channels.get("thread1")).toBeUndefined()
+ expect(db.collections.messages.get("m1")).toBeUndefined()
+ expect(db.collections.channelMemberships.get("c1:viewer:access")).toBeUndefined()
+ expect(db.collections.profiles.get("thread-author")).toBeUndefined()
+ expect(unreadProjection.projectUnread("inbox-unreads", "c1", true)).toBe(false)
+ expect(db.queryClient.getQueryData<{ servers: unknown[] }>(
+ communityKeys.inboxUnreads(),
+ )?.servers).toEqual([])
+ expect(getLastChannel("s1")).toBeNull()
+
+ ingestDms(db, {
+ conversations: [{
+ id: "dm1", userId: "peer", name: "Peer", discriminator: "0002",
+ avatar: "P", avatarVersion: 1, status: "offline", preview: "",
+ }],
+ })
+ ingestMessages(db, "dm1", [{
+ id: "dm-message", type: "chat", authorId: "peer", authorName: "Peer",
+ content: "dm", createdAt: "2026-09-25T00:00:02.000Z",
+ }])
+ unreadProjection.recordArrival({ channelId: "dm1", seq: 2 })
+ db.queryClient.setQueryData(communityKeys.inboxUnreads(), {
+ friendRequests: [],
+ servers: [],
+ dms: [{ channelId: "dm1" }],
+ })
+ setLastMeLocation("/c/me/dm1")
+ ingestDms(db, { conversations: [] })
+ expect(db.collections.channels.get("dm1")).toBeUndefined()
+ expect(db.collections.channelMemberships.get("dm1:viewer:access")).toBeUndefined()
+ expect(db.collections.channelMemberships.get("dm1:peer:access")).toBeUndefined()
+ expect(db.collections.messages.get("dm-message")).toBeUndefined()
+ expect(db.collections.profiles.get("peer")).toBeUndefined()
+ expect(unreadProjection.projectUnread("inbox-unreads", "dm1", true)).toBe(false)
+ expect(db.queryClient.getQueryData<{ dms: unknown[] }>(
+ communityKeys.inboxUnreads(),
+ )?.dms).toEqual([])
+ expect(getLastMeLeaf()).toBeNull()
+
+ ingestServers(db, { servers: [] })
+ expect(db.collections.servers.get("s1")).toBeUndefined()
+ expect(db.collections.serverMemberships.get("s1:viewer")).toBeUndefined()
+ })
+
+ it("keeps profiles referenced only by a surviving server owner", async () => {
+ const db = await registry()
+ ingestServers(db, {
+ servers: [
+ {
+ id: "s1", name: "Removed", initial: "R", active: false, unread: false,
+ mentions: 0, ownerId: "owner-removed",
+ },
+ {
+ id: "s2", name: "Kept", initial: "K", active: false, unread: false,
+ mentions: 0, ownerId: "owner-kept",
+ },
+ ],
+ })
+ for (const [userId, name] of [["owner-removed", "Removed"], ["owner-kept", "Kept"]] as const) {
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:profile.update",
+ userId,
+ name,
+ discriminator: "0001",
+ aboutMe: "",
+ bannerColor: null,
+ kind: "human",
+ ownerUserId: null,
+ } as CommunityWsEvent)
+ }
+
+ ingestServers(db, {
+ servers: [{
+ id: "s2", name: "Kept", initial: "K", active: false, unread: false,
+ mentions: 0, ownerId: "owner-kept",
+ }],
+ })
+
+ expect(db.collections.profiles.get("owner-removed")).toBeUndefined()
+ expect(db.collections.profiles.get("owner-kept")).toMatchObject({ name: "Kept" })
+ })
+
+ it("keeps canonical profile patches monotonic before hydration and across sparse authors", async () => {
+ const db = await registry()
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:status.update",
+ userId: "peer",
+ statusEmoji: "🌱",
+ statusText: "Growing",
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:identity.update",
+ userId: "peer",
+ avatar: "/peer-v5.png",
+ avatarVersion: 5,
+ } as CommunityWsEvent)
+ ingestDms(db, {
+ conversations: [{
+ id: "dm1", userId: "peer", name: "Peer", discriminator: "0002",
+ avatar: "/stale.png", avatarVersion: 4, status: "offline", preview: "",
+ }],
+ })
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:profile.update",
+ userId: "peer",
+ name: "Rich Peer",
+ discriminator: "0002",
+ aboutMe: "rich bio",
+ bannerColor: "#fff",
+ kind: "human",
+ ownerUserId: null,
+ } as CommunityWsEvent)
+ ingestMessages(db, "dm1", [{
+ id: "m1", type: "chat", authorId: "peer", authorName: "Sparse Peer",
+ authorAvatar: "/older.png", authorAvatarVersion: 3,
+ content: "hello", createdAt: "2026-09-25T00:00:00.000Z",
+ }])
+ expect(db.collections.profiles.get("peer")).toMatchObject({
+ name: "Sparse Peer",
+ discriminator: "0002",
+ avatar: "/peer-v5.png",
+ avatarVersion: 5,
+ aboutMe: "rich bio",
+ bannerColor: "#fff",
+ statusEmoji: "🌱",
+ statusText: "Growing",
+ })
+ })
+
+ it("purges the complete server closure while preserving DMs", async () => {
+ const db = await registry()
+ ingestServers(db, {
+ servers: [{
+ id: "s1",
+ name: "Alook",
+ initial: "A",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ }],
+ })
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Alook",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "cat1",
+ name: "General",
+ channels: [{ id: "c1", name: "chat", active: false, unread: false }],
+ }],
+ })
+ ingestDms(db, {
+ conversations: [{
+ id: "dm1",
+ userId: "peer",
+ name: "Peer",
+ discriminator: "0002",
+ avatar: "P",
+ avatarVersion: 1,
+ status: "offline",
+ preview: "",
+ }],
+ })
+ purgeCommunityServer(db, "s1")
+ expect(db.collections.servers.get("s1")).toBeUndefined()
+ expect(db.collections.categories.get("cat1")).toBeUndefined()
+ expect(db.collections.channels.get("c1")).toBeUndefined()
+ expect(db.collections.channels.get("dm1")).toBeDefined()
+ })
+
+ it("purges a scoped raw single-message query before it materializes canonically", async () => {
+ const db = await registry()
+ rememberMessageAccessScope(db.queryClient, "cold-opener", {
+ channelId: "detail-not-loaded",
+ serverId: "s1",
+ })
+ db.queryClient.setQueryData(communityKeys.message("cold-opener"), {
+ id: "cold-opener",
+ type: "chat",
+ authorId: "peer",
+ authorName: "Peer",
+ authorAvatar: "P",
+ authorAvatarVersion: 0,
+ content: "raw only",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ })
+
+ expect(db.collections.messages.get("cold-opener")).toBeUndefined()
+ purgeCommunityServer(db, "s1")
+
+ expect(db.queryClient.getQueryState(communityKeys.message("cold-opener"))).toBeUndefined()
+ })
+
+ it("purges only the selected child channel without removing its parent or siblings", async () => {
+ const db = await registry()
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Alook",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "cat1",
+ name: "General",
+ channels: [{ id: "c1", name: "chat", active: false, unread: false }],
+ }],
+ })
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.child_create",
+ parentChannelId: "c1",
+ parentMessageId: "m1",
+ channel: {
+ id: "thread1",
+ name: "Thread one",
+ type: "thread",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ },
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.child_create",
+ parentChannelId: "c1",
+ parentMessageId: "m2",
+ channel: {
+ id: "thread2",
+ name: "Thread two",
+ type: "thread",
+ createdAt: "2026-09-25T00:00:01.000Z",
+ },
+ } as CommunityWsEvent)
+
+ purgeCommunityChannel(db, "thread1")
+
+ expect(db.collections.channels.get("thread1")).toBeUndefined()
+ expect(db.collections.channels.get("c1")).toBeDefined()
+ expect(db.collections.channels.get("thread2")).toBeDefined()
+ })
+
+ it("purges durable rows and transient owners for channel and server scopes", async () => {
+ const db = await registry()
+ const navigationMemory = new Map<string, string>()
+ vi.stubGlobal("window", {})
+ vi.stubGlobal("localStorage", {
+ getItem: (key: string) => navigationMemory.get(key) ?? null,
+ setItem: (key: string, value: string) => navigationMemory.set(key, value),
+ removeItem: (key: string) => navigationMemory.delete(key),
+ })
+ const uninstall = installCommunityDbSync(db.queryClient, db)
+ ingestServerDetail(db, {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "owner",
+ categories: [{
+ id: "cat1", name: "General",
+ channels: [
+ { id: "c1", name: "one", active: false, unread: false },
+ { id: "c2", name: "two", active: false, unread: false },
+ ],
+ }],
+ })
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "opener",
+ channel: { id: "thread1", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" },
+ } as CommunityWsEvent)
+ ingestMessages(db, "c1", [{
+ id: "m1", type: "chat", authorId: "author", authorName: "Author", content: "rich",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ replyTo: { id: "reply", authorId: "reply-author", authorName: "Reply", text: "reply" },
+ thread: {
+ channelId: "thread1", messageCount: 1,
+ participants: [{ id: "participant", name: "Participant", avatar: "P", avatarVersion: 1 }],
+ },
+ approval: {
+ status: "pending",
+ otherProfile: { id: "approval", name: "Approval", discriminator: "0004", image: null, avatarVersion: 1 },
+ },
+ }])
+ ingestReadStateSnapshot(db, {
+ revision: 1,
+ readStates: [{
+ channelId: "c1", lastReadMessageId: "m1",
+ lastReadAt: "2026-09-25T00:00:01.000Z", lastReadSeq: 1,
+ }],
+ })
+ db.queryClient.setQueryData(communityKeys.folders(), {
+ folders: [{ id: "f1", name: "Folder", position: 0, servers: [{ id: "s1", name: "Server", initial: "S", icon: null }] }],
+ })
+ db.queryClient.setQueryData(communityKeys.notificationSettings(), {
+ raw: [
+ { serverId: "s1", level: "all" },
+ { channelId: "c1", level: "mentions" },
+ ],
+ server: {}, channel: {},
+ })
+ db.queryClient.setQueryData(communityKeys.inboxUnreads(), {
+ friendRequests: [],
+ servers: [{
+ serverId: "s1",
+ channels: [
+ { channelId: "c1", children: [{ channelId: "thread1" }] },
+ { channelId: "c2", children: [] },
+ { channelId: "stale-server-child", children: [] },
+ ],
+ }],
+ dms: [],
+ })
+ db.queryClient.setQueryData(communityKeys.messageContext("channel", "c1", 1), {
+ messages: [],
+ })
+ setLastChannel("s1", "c1")
+ useCommunityStore.setState({
+ currentServerId: "s1",
+ currentChannelId: "c1",
+ currentChannelMeta: { name: "one", parentChannelId: null },
+ typingByScope: new Map([
+ ["ch:c1", new Map([["author", "Author"]])],
+ ["dm:c1", new Map([["author", "Author"]])],
+ ]),
+ subscription: { channelId: "c1", secondaryChannelId: "thread1", dmConversationId: "c1" },
+ secondaryChannelOwner: Symbol("test"),
+ pendingReply: { channelId: "c1", target: { id: "m1", authorName: "Author", text: "rich" } },
+ })
+ useMessageStreamStore.setState({
+ entries: new Map([["channel:c1", {
+ scope: { kind: "channel", id: "c1", serverId: "s1" },
+ state: emptyMessageOverlay(),
+ }]]),
+ })
+
+ purgeCommunityChannel(db, "thread1")
+ expect(db.queryClient.getQueryData<{ servers: Array<{ channels: Array<{ children: unknown[] }> }> }>(
+ communityKeys.inboxUnreads(),
+ )?.servers[0]?.channels[0]?.children).toEqual([])
+ purgeCommunityServer(db, "s1")
+
+ expect(db.collections.readStates.get("c1")).toBeUndefined()
+ expect(db.collections.folderItems.get("f1:s1")).toBeUndefined()
+ expect(db.collections.notificationSettings.size).toBe(0)
+ expect(useCommunityStore.getState()).toMatchObject({
+ currentServerId: null,
+ currentChannelId: null,
+ currentChannelMeta: null,
+ subscription: {},
+ pendingReply: null,
+ })
+ expect(useMessageStreamStore.getState().entries.size).toBe(0)
+ uninstall()
+ useCommunityStore.getState().reset()
+ useMessageStreamStore.getState().resetAll()
+ })
+
+ it("keeps writes safe across idle collections, anonymous DMs, and absent registries", async () => {
+ const idleClient = new QueryClient()
+ const idle = createCommunityDbRegistry(idleClient, "viewer")
+ ingestServers(idle, { servers: [{
+ id: "idle", name: "Idle", initial: "I", active: false, unread: false,
+ mentions: 0, ownerId: "viewer",
+ }] })
+ expect(idleClient.getQueryData(communityKeys.communityDbCollection("viewer", "servers"))).toBeDefined()
+ await idle["cleanup"]()
+
+ const anonymous = createCommunityDbRegistry(new QueryClient(), null)
+ await anonymous.preload()
+ ingestDms(anonymous, { conversations: [{
+ id: "dm", userId: "peer", name: "Peer", discriminator: "0001",
+ avatar: "P", avatarVersion: 1, status: "offline", preview: "",
+ }] })
+ expect(anonymous.collections.channels.size).toBe(0)
+ await anonymous["cleanup"]()
+
+ projectCommunityWsEventToDb(new QueryClient(), {
+ type: "community:message.edited", channelId: "missing", messageId: "missing", content: "noop",
+ } as CommunityWsEvent)
+ })
+
+ it("leaves channel membership projection to the type-resolved handler", async () => {
+ const db = await registry()
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Alook",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "cat1",
+ name: "General",
+ channels: [{ id: "c1", name: "chat", active: false, unread: false }],
+ }],
+ })
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.child_create",
+ parentChannelId: "c1",
+ parentMessageId: "m1",
+ channel: {
+ id: "thread1",
+ name: "Thread one",
+ type: "thread",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ },
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.member_add",
+ serverId: "s1",
+ channelId: "thread1",
+ userId: "viewer",
+ } as CommunityWsEvent)
+
+ expect(db.collections.channelMemberships.get("thread1:viewer:notify")).toBeUndefined()
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.member_remove",
+ serverId: "s1",
+ channelId: "thread1",
+ userId: "viewer",
+ } as CommunityWsEvent)
+
+ expect(db.collections.channelMemberships.get("thread1:viewer:notify")).toBeUndefined()
+ expect(db.collections.channels.get("thread1")).toBeDefined()
+ expect(db.collections.channels.get("c1")).toBeDefined()
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.member_remove",
+ serverId: "s1",
+ channelId: "c1",
+ userId: "viewer",
+ } as CommunityWsEvent)
+ expect(db.collections.channels.get("c1")).toBeDefined()
+ expect(db.collections.channels.get("thread1")).toBeDefined()
+ })
+
+ it("projects structural, message, and profile websocket deltas into canonical rows", async () => {
+ const db = await registry()
+ ingestServers(db, {
+ servers: [{
+ id: "s1",
+ name: "Alook",
+ initial: "A",
+ active: false,
+ unread: false,
+ mentions: 0,
+ ownerId: "viewer",
+ }],
+ })
+ ingestDms(db, {
+ conversations: [{
+ id: "dm1",
+ userId: "peer",
+ name: "Peer",
+ discriminator: "0002",
+ avatar: "P",
+ avatarVersion: 1,
+ status: "offline",
+ preview: "",
+ }],
+ })
+
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.create",
+ serverId: "s1",
+ channel: {
+ id: "c1",
+ name: "general",
+ type: "text",
+ categoryId: null,
+ position: 2,
+ createdAt: "2026-09-25T00:00:00.000Z",
+ },
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:message.create",
+ channelId: "c1",
+ serverId: "s1",
+ message: {
+ id: "m1",
+ type: "chat",
+ authorId: "peer",
+ authorName: "Peer",
+ content: "hello",
+ createdAt: "2026-09-25T00:00:01.000Z",
+ },
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:status.update",
+ userId: "peer",
+ statusEmoji: "🌱",
+ statusText: "Growing",
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:identity.update",
+ userId: "peer",
+ avatar: "/peer-v2.png",
+ avatarVersion: 2,
+ } as CommunityWsEvent)
+
+ expect(db.collections.channels.get("c1")).toMatchObject({
+ serverId: "s1",
+ categoryId: null,
+ position: 2,
+ })
+ expect(db.collections.messages.get("m1")).toMatchObject({
+ channelId: "c1",
+ content: "hello",
+ })
+ expect(db.collections.profiles.get("peer")).toMatchObject({
+ statusEmoji: "🌱",
+ statusText: "Growing",
+ avatar: "/peer-v2.png",
+ avatarVersion: 2,
+ })
+ })
+
+ it("normalizes raw websocket attachments once at canonical DB ingress", async () => {
+ const db = await registry()
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:message.create",
+ channelId: "c1",
+ serverId: "s1",
+ message: {
+ id: "m-attachment",
+ seq: 1,
+ type: "chat",
+ authorId: "peer",
+ authorName: "Peer",
+ authorAvatarVersion: 0,
+ content: "files",
+ createdAt: "2026-09-25T00:00:01.000Z",
+ attachments: [
+ {
+ id: "image",
+ filename: "photo.png",
+ url: "/photo.png",
+ contentType: "image/png",
+ size: 2_048,
+ width: null,
+ height: 480,
+ },
+ {
+ id: "file",
+ filename: "notes.txt",
+ url: "/notes.txt",
+ },
+ ],
+ },
+ } as CommunityWsEvent)
+
+ expect(db.collections.messages.get("m-attachment")?.attachments).toEqual([
+ {
+ kind: "image",
+ name: "photo.png",
+ url: "/photo.png",
+ contentType: "image/png",
+ sizeBytes: 2_048,
+ width: undefined,
+ height: 480,
+ },
+ {
+ kind: "file",
+ name: "notes.txt",
+ url: "/notes.txt",
+ contentType: undefined,
+ sizeBytes: undefined,
+ size: "",
+ },
+ ])
+ })
+
+ it("projects every canonical websocket delta family", async () => {
+ const db = await registry()
+ ingestServers(db, { servers: [{
+ id: "s1", name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "viewer",
+ }] })
+ ingestServerDetail(db, {
+ id: "s1", name: "Server", discriminator: "0001", description: "",
+ icon: null, ownerId: "viewer",
+ categories: [{
+ id: "cat1", name: "General",
+ channels: [
+ { id: "c1", name: "one", active: false, unread: false },
+ { id: "c2", name: "two", active: false, unread: false },
+ ],
+ }],
+ })
+ ingestMessages(db, "c1", [{
+ id: "m1", type: "chat", authorId: "peer", authorName: "Peer", content: "old",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
+ }])
+ const event = (value: object) => projectCommunityWsEventToDb(
+ db.queryClient,
+ value as CommunityWsEvent,
+ )
+
+ event({ type: "community:channel.update", serverId: "s1", channelId: "missing", changes: { name: "noop" } })
+ event({
+ type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: null,
+ channel: { id: "missing-opener", name: "Missing", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" },
+ })
+ event({
+ type: "community:channel.child_create", parentChannelId: "missing", parentMessageId: "m1",
+ channel: { id: "missing-parent", name: "Missing", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" },
+ })
+ event({ type: "community:unread.bump", serverId: "s1", channelId: "c1", userId: "other", isMention: true })
+ event({ type: "community:message.updated", channelId: "c1", messageId: "m1", approval: { status: "pending" } })
+ event({ type: "community:reaction.add", channelId: "c1", messageId: "m1", userId: "viewer", emoji: "👍" })
+ event({ type: "community:reaction.remove", channelId: "c1", messageId: "m1", userId: "peer", emoji: "👍" })
+ event({ type: "community:server.update", serverId: "s1", changes: { name: "Renamed" } })
+ event({ type: "community:channel.update", serverId: "s1", channelId: "c1", changes: { name: "renamed" } })
+ event({ type: "community:channel.reorder", serverId: "s1", channels: [{ id: "c1", position: 9 }] })
+ event({ type: "community:category.create", serverId: "s1", category: { id: "cat2", name: "Other", position: 2, private: false } })
+ event({ type: "community:category.update", serverId: "s1", categoryId: "cat2", changes: { name: "Updated" } })
+ event({ type: "community:category.reorder", serverId: "s1", categories: [{ id: "cat2", position: 0 }] })
+ event({
+ type: "community:member.join", serverId: "s1",
+ member: {
+ id: "member-peer", userId: "peer", role: "member",
+ joinedAt: "2026-09-25T00:00:00.000Z", name: "Peer", discriminator: "0002",
+ avatar: "P", avatarVersion: 1,
+ },
+ })
+ event({
+ type: "community:member.update", serverId: "s1", memberId: "member-peer",
+ userId: "peer", changes: { role: "admin" },
+ })
+ event({ type: "community:channel.member_add", serverId: "s1", channelId: "c1", userId: "peer" })
+ event({ type: "community:channel.member_remove", serverId: "s1", channelId: "c1", userId: "peer" })
+ event({ type: "community:unread.bump", serverId: "s1", channelId: "c1", railChannelId: "c2", userId: "viewer", isMention: true })
+ event({
+ type: "community:profile.update", userId: "peer", name: "Peer Two",
+ discriminator: "0003", aboutMe: "hello", bannerColor: "#fff", kind: "human",
+ ownerUserId: null,
+ })
+ event({
+ type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "m1",
+ channel: { id: "thread1", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:01.000Z" },
+ })
+ event({
+ type: "community:channel.child_update", channelId: "thread1",
+ changes: { name: "Thread renamed", archived: false, tags: ["tag"], lastMessageAt: "2026-09-25T00:00:02.000Z" },
+ })
+ event({ type: "community:member.leave", serverId: "s1", userId: "peer" })
+ event({ type: "community:category.delete", serverId: "s1", categoryId: "cat2" })
+
+ expect(db.collections.servers.get("s1")).toMatchObject({ name: "Renamed", unread: true, mentions: 1 })
+ expect(db.collections.channels.get("c1")).toMatchObject({ name: "renamed", position: 9, unread: true })
+ expect(db.collections.channels.get("thread1")).toMatchObject({ name: "Thread renamed", tags: ["tag"] })
+ expect(db.collections.messages.get("m1")?.reactions).toEqual([
+ { emoji: "👍", count: 1, me: true, userIds: ["viewer"] },
+ ])
+ expect(db.collections.serverMemberships.get("s1:peer")).toBeUndefined()
+ expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer Two", aboutMe: "hello" })
+
+ event({
+ type: "community:channel.child_update", channelId: "thread1",
+ changes: { archived: true },
+ })
+ expect(db.collections.channels.get("thread1")).toMatchObject({ archived: true })
+ event({ type: "community:channel.delete", serverId: "s1", channelId: "c2" })
+ expect(db.collections.channels.get("c2")).toBeUndefined()
+ event({ type: "community:server.delete", serverId: "s1" })
+ expect(db.collections.servers.get("s1")).toBeUndefined()
+ ingestServers(db, { servers: [{
+ id: "leave", name: "Leave", initial: "L", active: false, unread: false,
+ mentions: 0, ownerId: "viewer",
+ }] })
+ event({ type: "community:member.leave", serverId: "leave", userId: "viewer" })
+ expect(db.collections.servers.get("leave")).toBeUndefined()
+ event({ type: "community:unknown" })
+ })
+
+ it("ignores raw message-bearing surfaces while canonical rows still accept WS deltas", async () => {
+ const db = await registry()
+ const uninstall = installCommunityDbSync(db.queryClient, db)
+ const message = (id: string, content: string) => ({
+ id,
+ type: "chat" as const,
+ authorId: "peer",
+ authorName: "Peer",
+ content,
+ createdAt: "2026-09-25T00:00:00.000Z",
+ reactions: [],
+ })
+ db.queryClient.setQueryData(communityKeys.inboxMentions(), {})
+ db.queryClient.setQueryData(communityKeys.inboxMarked(), {})
+ db.queryClient.setQueryData(communityKeys.pins("c1"), { pins: [message("pin", "pin")] })
+ db.queryClient.setQueryData(communityKeys.inboxMentions(), {
+ mentions: [{ id: "mention", channelId: "c1", m: message("mention-message", "mention") }],
+ })
+ db.queryClient.setQueryData(communityKeys.inboxMarked(), {
+ marked: [{ id: "mark", channelId: "c1", m: message("marked-message", "marked") }],
+ })
+ db.queryClient.setQueryData(communityKeys.forumFeed("c1", null), {
+ pages: [{
+ included: {
+ parentMessages: [{
+ id: "forum-message",
+ channelId: "c1",
+ type: "chat",
+ authorId: "peer",
+ authorName: "Peer",
+ authorImage: null,
+ authorAvatarVersion: 0,
+ content: "forum",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ seq: 1,
+ }],
+ },
+ }],
+ pageParams: [null],
+ })
+
+ expect([...db.collections.messages.keys()]).toEqual([])
+ ingestMessages(db, "c1", [message("pin", "pin")])
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:message.edited",
+ channelId: "c1",
+ messageId: "pin",
+ content: "edited",
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:reaction.add",
+ channelId: "c1",
+ messageId: "pin",
+ userId: "viewer",
+ emoji: "👍",
+ } as CommunityWsEvent)
+ expect(db.collections.messages.get("pin")).toMatchObject({
+ content: "edited",
+ reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["viewer"] }],
+ })
+ db.queryClient.setQueryData(communityKeys.message("pin"), message("pin", "stale"))
+ purgeCommunityChannel(db, "c1")
+ expect(db.collections.messages.size).toBe(0)
+ expect(db.queryClient.getQueryState(communityKeys.message("pin"))).toBeUndefined()
+ uninstall()
+ })
+
+ it("does not infer a cold opener from raw Query but accepts explicit canonical publication", async () => {
+ const db = await registry()
+ const uninstall = installCommunityDbSync(db.queryClient, db)
+ ingestServers(db, {
+ servers: [{
+ id: "s1", name: "Server", initial: "S", active: false, unread: false,
+ mentions: 0, ownerId: "viewer",
+ }],
+ })
+ ingestServerDetail(db, {
+ id: "s1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "viewer",
+ categories: [{
+ id: "cat1",
+ name: "Forum",
+ channels: [{ id: "forum1", name: "forum", active: false, unread: false, type: "forum" }],
+ }],
+ })
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:channel.child_create",
+ parentChannelId: "forum1",
+ parentMessageId: "opener",
+ channel: {
+ id: "thread1",
+ name: "Thread",
+ type: "thread",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ },
+ } as CommunityWsEvent)
+
+ db.queryClient.setQueryData(communityKeys.message("opener"), {
+ id: "opener",
+ type: "chat",
+ authorId: "peer",
+ authorName: "Peer",
+ authorAvatar: "P",
+ authorAvatarVersion: 0,
+ content: "cold opener",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ })
+
+ expect(db.collections.messages.get("opener")).toBeUndefined()
+ ingestMessages(db, "forum1", [{
+ id: "opener",
+ type: "chat",
+ authorId: "peer",
+ authorName: "Peer",
+ authorAvatar: "P",
+ authorAvatarVersion: 0,
+ content: "cold opener",
+ createdAt: "2026-09-25T00:00:00.000Z",
+ }])
+ expect(db.collections.messages.get("opener")).toMatchObject({
+ channelId: "forum1",
+ content: "cold opener",
+ })
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:message.edited",
+ channelId: "forum1",
+ messageId: "opener",
+ content: "edited opener",
+ } as CommunityWsEvent)
+ projectCommunityWsEventToDb(db.queryClient, {
+ type: "community:reaction.add",
+ channelId: "forum1",
+ messageId: "opener",
+ userId: "viewer",
+ emoji: "👍",
+ } as CommunityWsEvent)
+ expect(db.collections.messages.get("opener")).toMatchObject({
+ content: "edited opener",
+ reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["viewer"] }],
+ })
+ uninstall()
+ })
+})
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
new file mode 100644
index 000000000..7014d3aa5
--- /dev/null
+++ b/src/web/src/lib/community-db/sync.ts
@@ -0,0 +1,2761 @@
+import { notifyManager, type QueryClient } from "@tanstack/react-query"
+import type { Query } from "@tanstack/react-query"
+import {
+ UNCATEGORIZED_CATEGORY_ID,
+ type AccountAttentionSnapshot,
+ type CommunityWsEvent,
+} from "@alook/shared"
+import type { DmsResponse } from "@/hooks/community/use-dms"
+import type { FoldersResponse } from "@/hooks/community/use-folders"
+import type {
+ AccountReadStateSnapshot,
+} from "@/hooks/community/community-ws/read-state-reconciliation"
+import type { ServerDetail, ServersResponse } from "@/hooks/community/use-servers"
+import type { Msg } from "@/lib/community/models/message"
+import type { NotificationSettings } from "@/hooks/community/use-notification-settings"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ communityUserProfilePatch,
+ messageProfilePatches,
+ writeCommunityProfilePatches,
+} from "@/lib/community/profile-seed"
+import type { CommunityProfilePatch } from "@/lib/community/models/people"
+import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
+import { useCommunityStore } from "@/stores/community"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+import { projectCommunityMessageCreate } from "@/lib/community/message-wire"
+import { clearTypingIndicator } from "@/hooks/community/community-ws/typing"
+import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
+import { takeMessageIdsForAccessScope } from "./message-access-scope"
+import { clearLastChannel, getLastChannel } from "@/lib/community/last-channel"
+import { clearLastMeLocation, getLastMeLeaf } from "@/lib/community/last-me-location"
+import {
+ getCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "./collections"
+import {
+ categorySchema,
+ attentionItemSchema,
+ attentionScopeSchema,
+ channelMembershipKey,
+ channelMembershipSchema,
+ channelSchema,
+ folderItemKey,
+ folderItemSchema,
+ folderSchema,
+ messageSchema,
+ notificationSettingKey,
+ notificationSettingSchema,
+ profileSchema,
+ readStateClockSchema,
+ readStateSchema,
+ serverMembershipKey,
+ serverMembershipSchema,
+ serverSchema,
+ type CategoryRow,
+ type AttentionItemRow,
+ type AttentionScopeRow,
+ type ChannelMembershipRow,
+ type ChannelRow,
+ type FolderItemRow,
+ type FolderRow,
+ type MessageRow,
+ type NotificationSettingRow,
+ type ReadStateClockRow,
+ type ReadStateRow,
+ type ServerMembershipRow,
+ type ServerRow,
+} from "./schema"
+import type { z } from "zod"
+
+type CollectionName = keyof CommunityDbRegistry["collections"]
+type SnapshotIngestMode = "authoritative" | "merge"
+
+type CanonicalRevisionState = {
+ revision: number
+ entityRevisions: Map<string, number>
+ pendingOperations: Map<string, CanonicalPendingOperation[]>
+}
+
+type CanonicalPendingOperation =
+ | { revision: number; kind: "patch"; apply: (row: object) => object }
+ | { revision: number; kind: "delete" }
+
+type CanonicalWriteContext =
+ | { kind: "event" }
+ | { kind: "query"; requestRevision: number }
+
+const canonicalRevisionStates = new WeakMap<QueryClient, CanonicalRevisionState>()
+const canonicalWriteContexts = new WeakMap<QueryClient, CanonicalWriteContext>()
+
+function canonicalRevisionState(queryClient: QueryClient) {
+ let state = canonicalRevisionStates.get(queryClient)
+ if (!state) {
+ state = { revision: 0, entityRevisions: new Map(), pendingOperations: new Map() }
+ canonicalRevisionStates.set(queryClient, state)
+ }
+ return state
+}
+
+function canonicalEntityKey(name: CollectionName, key: string) {
+ return `${name}:${key}`
+}
+
+function isProtectedFromQueryWrite(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ key: string,
+) {
+ const context = canonicalWriteContexts.get(registry.queryClient)
+ if (context?.kind !== "query") return false
+ return (canonicalRevisionState(registry.queryClient).entityRevisions.get(
+ canonicalEntityKey(name, key),
+ ) ?? 0) > context.requestRevision
+}
+
+function recordEventWrites(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ keys: Iterable<string>,
+) {
+ if (canonicalWriteContexts.get(registry.queryClient)?.kind !== "event") return
+ const state = canonicalRevisionState(registry.queryClient)
+ for (const key of new Set(keys)) {
+ state.revision += 1
+ state.entityRevisions.set(canonicalEntityKey(name, key), state.revision)
+ }
+}
+
+function recordEventPatches<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ keys: Iterable<string>,
+ patch: (row: T) => T,
+ presentKeys: ReadonlySet<string>,
+) {
+ if (canonicalWriteContexts.get(registry.queryClient)?.kind !== "event") return
+ const state = canonicalRevisionState(registry.queryClient)
+ for (const key of new Set(keys)) {
+ state.revision += 1
+ const entityKey = canonicalEntityKey(name, key)
+ state.entityRevisions.set(entityKey, state.revision)
+ if (presentKeys.has(key)) {
+ state.pendingOperations.delete(entityKey)
+ continue
+ }
+ const pending = state.pendingOperations.get(entityKey) ?? []
+ pending.push({
+ revision: state.revision,
+ kind: "patch",
+ apply: patch as unknown as (row: object) => object,
+ })
+ state.pendingOperations.set(entityKey, pending)
+ }
+}
+
+function recordEventDeletes(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ keys: Iterable<string>,
+) {
+ if (canonicalWriteContexts.get(registry.queryClient)?.kind !== "event") return
+ const state = canonicalRevisionState(registry.queryClient)
+ for (const key of new Set(keys)) {
+ state.revision += 1
+ const entityKey = canonicalEntityKey(name, key)
+ state.entityRevisions.set(entityKey, state.revision)
+ state.pendingOperations.set(entityKey, [{
+ revision: state.revision,
+ kind: "delete",
+ }])
+ }
+}
+
+function clearPendingOperations(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ keys: Iterable<string>,
+) {
+ const pending = canonicalRevisionState(registry.queryClient).pendingOperations
+ for (const key of keys) pending.delete(canonicalEntityKey(name, key))
+}
+
+function mergePendingOperationsIntoQueryRow<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ key: string,
+ schema: z.ZodType<T>,
+ incoming: T,
+) {
+ const context = canonicalWriteContexts.get(registry.queryClient)
+ if (context?.kind !== "query") return incoming
+ const operations = canonicalRevisionState(registry.queryClient).pendingOperations
+ .get(canonicalEntityKey(name, key))
+ ?.filter((operation) => operation.revision > context.requestRevision)
+ if (!operations?.length) return undefined
+ let next: object | undefined = incoming
+ for (const operation of operations) {
+ if (operation.kind === "delete") next = undefined
+ else if (next) next = operation.apply(next)
+ }
+ if (!next) return undefined
+ clearPendingOperations(registry, name, [key])
+ return schema.parse(next)
+}
+
+function withCanonicalWriteContext<T>(
+ queryClient: QueryClient,
+ context: CanonicalWriteContext,
+ publish: () => T,
+) {
+ const previous = canonicalWriteContexts.get(queryClient)
+ canonicalWriteContexts.set(queryClient, context)
+ try {
+ return publish()
+ } finally {
+ if (previous) canonicalWriteContexts.set(queryClient, previous)
+ else canonicalWriteContexts.delete(queryClient)
+ }
+}
+
+function collectionRows<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ schema: z.ZodType<T>,
+) {
+ const cached = registry.queryClient.getQueryData<T[]>(
+ communityKeys.communityDbCollection(registry.scopeId, name),
+ )
+ if (cached) return cached.flatMap((row) => {
+ const parsed = schema.safeParse(row)
+ return parsed.success ? [parsed.data] : []
+ })
+ const collection = registry.collections[name] as unknown as {
+ values: () => IterableIterator<unknown>
+ }
+ return Array.from(collection.values()).flatMap((row) => {
+ const parsed = schema.safeParse(row)
+ return parsed.success ? [parsed.data] : []
+ })
+}
+
+function publishRows<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ rows: T[],
+) {
+ registry.queryClient.setQueryData(
+ communityKeys.communityDbCollection(registry.scopeId, name),
+ rows,
+ )
+}
+
+function writeCollectionRows<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ rows: T[],
+ getKey: (row: T) => string,
+) {
+ const collection = registry.collections[name] as unknown as {
+ status: string
+ keys: () => IterableIterator<string>
+ utils: {
+ writeBatch: (callback: () => void) => void
+ writeDelete: (keys: string | string[]) => void
+ writeUpsert: (rows: T | T[]) => void
+ }
+ }
+ if (collection.status !== "ready") return
+ const nextKeys = new Set(rows.map(getKey))
+ const removed = Array.from(collection.keys()).filter((key) => !nextKeys.has(key))
+ collection.utils.writeBatch(() => {
+ if (removed.length > 0) collection.utils.writeDelete(removed)
+ if (rows.length > 0) collection.utils.writeUpsert(rows)
+ })
+}
+
+function replaceRows<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ schema: z.ZodType<T>,
+ getKey: (row: T) => string,
+ incoming: T[],
+ owns: (row: T) => boolean,
+) {
+ const parsedIncoming = incoming.map((row) => schema.parse(row))
+ const current = collectionRows(registry, name, schema)
+ const nextByKey = new Map(current.flatMap((row) => {
+ const key = getKey(row)
+ return !owns(row) || isProtectedFromQueryWrite(registry, name, key)
+ ? [[key, row] as const]
+ : []
+ }))
+ for (const row of parsedIncoming) {
+ const key = getKey(row)
+ if (!isProtectedFromQueryWrite(registry, name, key)) {
+ nextByKey.set(key, row)
+ clearPendingOperations(registry, name, [key])
+ continue
+ }
+ if (nextByKey.has(key)) {
+ clearPendingOperations(registry, name, [key])
+ continue
+ }
+ const merged = mergePendingOperationsIntoQueryRow(registry, name, key, schema, row)
+ if (merged) nextByKey.set(key, merged)
+ }
+ const next = [...nextByKey.values()]
+ writeCollectionRows(registry, name, next, getKey)
+ publishRows(registry, name, next)
+ recordEventWrites(registry, name, [
+ ...current.filter(owns).map(getKey),
+ ...parsedIncoming.map(getKey),
+ ])
+}
+
+function upsertRows<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ schema: z.ZodType<T>,
+ getKey: (row: T) => string,
+ incoming: T[],
+) {
+ const parsedIncoming = incoming.map((row) => schema.parse(row))
+ const nextByKey = new Map(
+ collectionRows(registry, name, schema).map((row) => [getKey(row), row]),
+ )
+ const acceptedKeys: string[] = []
+ for (const row of parsedIncoming) {
+ const key = getKey(row)
+ if (!isProtectedFromQueryWrite(registry, name, key)) {
+ nextByKey.set(key, row)
+ acceptedKeys.push(key)
+ clearPendingOperations(registry, name, [key])
+ continue
+ }
+ if (nextByKey.has(key)) {
+ clearPendingOperations(registry, name, [key])
+ continue
+ }
+ const merged = mergePendingOperationsIntoQueryRow(registry, name, key, schema, row)
+ if (merged) nextByKey.set(key, merged)
+ }
+ const next = [...nextByKey.values()]
+ writeCollectionRows(registry, name, next, getKey)
+ publishRows(registry, name, next)
+ recordEventWrites(registry, name, acceptedKeys)
+}
+
+function promoteServerDetailComplete(
+ registry: CommunityDbRegistry,
+ serverId: string,
+) {
+ const current = collectionRows(registry, "servers", serverSchema)
+ let changed = false
+ const next = current.map((row) => {
+ if (row.id !== serverId || row.detailComplete) return row
+ changed = true
+ return serverSchema.parse({ ...row, detailComplete: true })
+ })
+ if (!changed) return
+ writeCollectionRows(registry, "servers", next, (row) => row.id)
+ publishRows(registry, "servers", next)
+}
+
+function patchRows<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ schema: z.ZodType<T>,
+ getKey: (row: T) => string,
+ patch: (row: T) => T,
+ matches: (row: T) => boolean,
+ eventKeys?: Iterable<string>,
+) {
+ const current = collectionRows(registry, name, schema)
+ let changed = false
+ const changedKeys: string[] = []
+ const next = current.map((row) => {
+ if (!matches(row)) return row
+ const key = getKey(row)
+ if (isProtectedFromQueryWrite(registry, name, key)) return row
+ changed = true
+ changedKeys.push(key)
+ return schema.parse(patch(row))
+ })
+ if (changed) {
+ writeCollectionRows(registry, name, next, getKey)
+ publishRows(registry, name, next)
+ }
+ if (eventKeys) {
+ recordEventPatches(registry, name, eventKeys, patch, new Set(changedKeys))
+ }
+ else recordEventWrites(registry, name, changedKeys)
+ return changed
+}
+
+function deleteRows<T extends object>(
+ registry: CommunityDbRegistry,
+ name: CollectionName,
+ schema: z.ZodType<T>,
+ remove: (row: T) => boolean,
+ eventKeys?: Iterable<string>,
+) {
+ const current = collectionRows(registry, name, schema)
+ const removedKeys: string[] = []
+ const next = current.filter((row) => {
+ if (!remove(row)) return true
+ const key = (registry.collections[name] as unknown as {
+ getKeyFromItem: (value: T) => string
+ }).getKeyFromItem(row)
+ if (isProtectedFromQueryWrite(registry, name, key)) return true
+ removedKeys.push(key)
+ return false
+ })
+ const keyByValue = new Map(current.map((row) => [row, (
+ registry.collections[name] as unknown as { getKeyFromItem: (value: T) => string }
+ ).getKeyFromItem(row)]))
+ writeCollectionRows(registry, name, next, (row) => keyByValue.get(row)!)
+ publishRows(registry, name, next)
+ if (eventKeys) recordEventDeletes(registry, name, eventKeys)
+ else recordEventWrites(registry, name, removedKeys)
+}
+
+function referencedProfileIds(registry: CommunityDbRegistry) {
+ const ids = new Set<string>(registry.accountId ? [registry.accountId] : [])
+ for (const row of collectionRows(registry, "servers", serverSchema)) {
+ if (row.ownerId) ids.add(row.ownerId)
+ }
+ for (const row of collectionRows(registry, "serverMemberships", serverMembershipSchema)) {
+ ids.add(row.userId)
+ }
+ for (const row of collectionRows(registry, "channelMemberships", channelMembershipSchema)) {
+ ids.add(row.userId)
+ }
+ for (const row of collectionRows(registry, "messages", messageSchema)) {
+ const message = row as MessageRow & Msg
+ if (message.authorId) ids.add(message.authorId)
+ if (message.replyTo?.authorId) ids.add(message.replyTo.authorId)
+ for (const participant of message.thread?.participants ?? []) ids.add(participant.id)
+ for (const profile of [
+ message.approval?.otherProfile,
+ message.approval?.botProfile,
+ message.approval?.waitingOnProfile,
+ ]) {
+ if (profile?.id) ids.add(profile.id)
+ }
+ }
+ return ids
+}
+
+function garbageCollectCommunityProfiles(registry: CommunityDbRegistry) {
+ const referenced = referencedProfileIds(registry)
+ deleteRows(
+ registry,
+ "profiles",
+ profileSchema,
+ (row) => !referenced.has(row.userId),
+ )
+}
+
+function pruneInboxCaches(
+ queryClient: QueryClient,
+ channelIds: ReadonlySet<string>,
+ serverId: string | null,
+) {
+ queryClient.setQueryData<{
+ friendRequests: unknown[]
+ servers: Array<{
+ serverId: string
+ channels: Array<{ channelId: string; children: Array<{ channelId: string }> }>
+ }>
+ dms: Array<{ channelId: string }>
+ } | undefined>(communityKeys.inboxUnreads(), (current) => {
+ if (!current) return current
+ const servers = current.servers.flatMap((server) => {
+ if (serverId && server.serverId === serverId) return []
+ const channels = server.channels.flatMap((channel) => {
+ if (channelIds.has(channel.channelId)) return []
+ const children = channel.children.filter((child) => !channelIds.has(child.channelId))
+ return [{ ...channel, children }]
+ })
+ return channels.length > 0 ? [{ ...server, channels }] : []
+ })
+ return {
+ ...current,
+ servers,
+ dms: current.dms.filter((dm) => !channelIds.has(dm.channelId)),
+ }
+ })
+ queryClient.setQueryData<{
+ mentions: Array<{ channelId?: string; serverId?: string }>
+ } | undefined>(communityKeys.inboxMentions(), (current) => current ? {
+ ...current,
+ mentions: current.mentions.filter((entry) => (
+ !entry.channelId || !channelIds.has(entry.channelId)
+ ) && (!serverId || entry.serverId !== serverId)),
+ } : current)
+ queryClient.setQueryData<{
+ marked: Array<{ channelId: string; serverId: string | null }>
+ } | undefined>(communityKeys.inboxMarked(), (current) => current ? {
+ ...current,
+ marked: current.marked.filter((entry) => (
+ !channelIds.has(entry.channelId) && (!serverId || entry.serverId !== serverId)
+ )),
+ } : current)
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.inbox(),
+ refetchType: "active",
+ })
+}
+
+function clearChannelTransientState(
+ registry: CommunityDbRegistry,
+ channelIds: ReadonlySet<string>,
+ serverId: string | null,
+) {
+ const messageIds = new Set([
+ ...takeMessageIdsForAccessScope(registry.queryClient, channelIds, serverId),
+ ...collectionRows(registry, "messages", messageSchema)
+ .filter((row) => channelIds.has(row.channelId))
+ .map((row) => row.id),
+ ])
+ for (const messageId of messageIds) {
+ void registry.queryClient.cancelQueries({
+ queryKey: communityKeys.message(messageId),
+ exact: true,
+ })
+ registry.queryClient.removeQueries({
+ queryKey: communityKeys.message(messageId),
+ exact: true,
+ })
+ }
+ if (channelIds.size === 0) return
+ for (const entry of useMessageStreamStore.getState().entries.values()) {
+ if (channelIds.has(entry.scope.id)) useMessageStreamStore.getState().removeScope(entry.scope)
+ }
+ const community = useCommunityStore.getState()
+ const unreadProjection = getAccountUnreadProjection(
+ registry.queryClient,
+ registry.accountId ?? "__anonymous__",
+ )
+ for (const channelId of channelIds) {
+ unreadProjection.retireAccessScope({ kind: "channel", channelId })
+ for (const scope of [`ch:${channelId}`, `dm:${channelId}`]) {
+ for (const userId of community.typingByScope.get(scope)?.keys() ?? []) {
+ clearTypingIndicator(scope, userId)
+ }
+ }
+ if (serverId) useCommunityWsStore.getState().revokeChannelAccess(serverId, channelId)
+ }
+ pruneInboxCaches(registry.queryClient, channelIds, null)
+ if (serverId) {
+ const remembered = getLastChannel(serverId)
+ if (remembered && channelIds.has(remembered)) clearLastChannel(serverId)
+ } else {
+ const remembered = getLastMeLeaf()
+ if (remembered && channelIds.has(remembered)) clearLastMeLocation()
+ }
+ if (community.currentChannelId && channelIds.has(community.currentChannelId)) {
+ community.setCurrentChannelMeta(null)
+ community.setCurrentChannelId(null)
+ }
+ const subscription = { ...community.subscription }
+ if (subscription.channelId && channelIds.has(subscription.channelId)) delete subscription.channelId
+ if (subscription.secondaryChannelId && channelIds.has(subscription.secondaryChannelId)) {
+ delete subscription.secondaryChannelId
+ useCommunityStore.setState({ secondaryChannelOwner: null })
+ }
+ if (subscription.dmConversationId && channelIds.has(subscription.dmConversationId)) {
+ delete subscription.dmConversationId
+ }
+ useCommunityStore.setState({ subscription })
+ if (community.pendingReply && channelIds.has(community.pendingReply.channelId)) {
+ community.setPendingReply(null)
+ }
+ const predicate = (query: Query) => {
+ const key = query.queryKey
+ if (key[0] !== "community" || key[1] === "db") return false
+ if ((key[1] === "channel" || key[1] === "dm") && channelIds.has(String(key[2]))) return true
+ if (key[1] === "message-context" && channelIds.has(String(key[3]))) return true
+ const data = query.state.data as { channelId?: unknown; scope?: { channelId?: unknown } } | undefined
+ return typeof data?.channelId === "string" && channelIds.has(data.channelId)
+ || typeof data?.scope?.channelId === "string" && channelIds.has(data.scope.channelId)
+ }
+ void registry.queryClient.cancelQueries({ predicate })
+ registry.queryClient.removeQueries({ predicate })
+}
+
+export function ingestServers(
+ registry: CommunityDbRegistry,
+ response: ServersResponse,
+ mode: SnapshotIngestMode = "authoritative",
+) {
+ const currentServers = collectionRows(registry, "servers", serverSchema)
+ const existingById = new Map(currentServers.map((server) => [server.id, server]))
+ const incomingServerIds = new Set(response.servers.map((server) => server.id))
+ const removedServerIds = currentServers
+ .filter((server) => !incomingServerIds.has(server.id))
+ .map((server) => server.id)
+ const servers: ServerRow[] = response.servers.map((server, position) => ({
+ id: server.id,
+ position,
+ name: server.name,
+ discriminator: server.discriminator ?? "",
+ description: server.description ?? "",
+ ownerId: server.ownerId ?? "",
+ icon: server.icon ?? null,
+ official: server.official === true,
+ isOwner: server.isOwner === true,
+ unread: server.unread,
+ mentions: server.mentions,
+ detailComplete: existingById.get(server.id)?.detailComplete ?? false,
+ }))
+ const viewerId = registry.accountId
+ const memberships: ServerMembershipRow[] = viewerId
+ ? response.servers.map((server) => ({
+ id: serverMembershipKey(server.id, viewerId),
+ serverId: server.id,
+ userId: viewerId,
+ role: server.isOwner ? "owner" : "member",
+ viewer: true,
+ }))
+ : []
+ notifyManager.batch(() => {
+ if (mode === "authoritative") {
+ for (const serverId of removedServerIds) purgeCommunityServer(registry, serverId)
+ replaceRows(registry, "servers", serverSchema, (row) => row.id, servers, () => true)
+ } else {
+ upsertRows(registry, "servers", serverSchema, (row) => row.id, servers)
+ }
+ if (viewerId) {
+ if (mode === "authoritative") {
+ replaceRows(
+ registry,
+ "serverMemberships",
+ serverMembershipSchema,
+ (row) => row.id,
+ memberships,
+ (row) => row.viewer,
+ )
+ } else {
+ upsertRows(
+ registry,
+ "serverMemberships",
+ serverMembershipSchema,
+ (row) => row.id,
+ memberships,
+ )
+ }
+ }
+ })
+}
+
+export function ingestServerDetail(
+ registry: CommunityDbRegistry,
+ detail: ServerDetail,
+ mode: SnapshotIngestMode = "authoritative",
+) {
+ const existing = collectionRows(registry, "servers", serverSchema)
+ .find((row) => row.id === detail.id)
+ const server: ServerRow = {
+ id: detail.id,
+ position: existing?.position ?? 0,
+ name: detail.name,
+ discriminator: detail.discriminator,
+ description: detail.description,
+ ownerId: detail.ownerId,
+ icon: detail.icon,
+ official: detail.official === true,
+ isOwner: existing?.isOwner ?? detail.ownerId === registry.accountId,
+ unread: existing?.unread ?? false,
+ mentions: existing?.mentions ?? 0,
+ detailComplete: true,
+ }
+ const categories: CategoryRow[] = []
+ const channels: ChannelRow[] = []
+ detail.categories.forEach((category, categoryIndex) => {
+ const uncategorized = category.id === UNCATEGORIZED_CATEGORY_ID
+ if (!uncategorized) {
+ categories.push({
+ id: category.id,
+ serverId: detail.id,
+ name: category.name,
+ position: categoryIndex,
+ private: category.private === true || category.private === 1,
+ creatorId: category.creatorId,
+ pending: category.pending === true,
+ })
+ }
+ category.channels.forEach((channel, channelIndex) => {
+ channels.push({
+ id: channel.id,
+ serverId: detail.id,
+ categoryId: uncategorized ? null : category.id,
+ name: channel.name,
+ type: channel.type ?? "text",
+ parentChannelId: null,
+ parentMessageId: null,
+ creatorId: channel.creatorId,
+ position: channelIndex,
+ archived: false,
+ muted: channel.muted === true,
+ unread: channel.unread,
+ ...(channel.type === "forum" ? {
+ baseUnread: detail.forumUnreadState?.[channel.id]?.baseUnread ?? channel.unread,
+ } : {}),
+ tags: channel.tags ?? [],
+ pending: channel.pending === true,
+ lastMessageAt: null,
+ })
+ })
+ })
+ const currentTopLevelIds = new Set(
+ collectionRows(registry, "channels", channelSchema)
+ .filter((row) => row.serverId === detail.id && row.type !== "thread")
+ .map((row) => row.id),
+ )
+ const incomingTopLevelIds = new Set(channels.map((row) => row.id))
+ const removedTopLevelIds = [...currentTopLevelIds]
+ .filter((channelId) => !incomingTopLevelIds.has(channelId))
+ const viewerId = registry.accountId
+ const accessMemberships: ChannelMembershipRow[] = viewerId
+ ? channels.map((channel) => ({
+ id: channelMembershipKey(channel.id, viewerId, "access"),
+ channelId: channel.id,
+ userId: viewerId,
+ relation: "access",
+ source: "inherited",
+ }))
+ : []
+ const existingChannels = new Map(
+ collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),
+ )
+ const unreadChildOwnership = Object.entries(detail.forumUnreadState ?? {})
+ .flatMap(([parentChannelId, state]) => state.childIds.map((childId) => ({
+ childId,
+ parentChannelId,
+ })))
+ const unreadChildStubs: ChannelRow[] = unreadChildOwnership.flatMap((ownership) => {
+ if (existingChannels.has(ownership.childId)) return []
+ return [{
+ id: ownership.childId,
+ serverId: detail.id,
+ categoryId: null,
+ name: "",
+ type: "thread" as const,
+ parentChannelId: ownership.parentChannelId,
+ parentMessageId: null,
+ creatorId: null,
+ position: 0,
+ archived: false,
+ muted: false,
+ unread: true,
+ tags: [],
+ pending: false,
+ lastMessageAt: null,
+ }]
+ })
+ const unreadChildMemberships: ChannelMembershipRow[] = viewerId
+ ? unreadChildOwnership.flatMap(({ childId }) => ([
+ {
+ id: channelMembershipKey(childId, viewerId, "access"),
+ channelId: childId,
+ userId: viewerId,
+ relation: "access" as const,
+ source: "explicit" as const,
+ },
+ {
+ id: channelMembershipKey(childId, viewerId, "notify"),
+ channelId: childId,
+ userId: viewerId,
+ relation: "notify" as const,
+ source: "explicit" as const,
+ },
+ ]))
+ : []
+ const authoritativeTopLevelIds = new Set([...currentTopLevelIds, ...incomingTopLevelIds])
+ notifyManager.batch(() => {
+ if (mode === "authoritative") {
+ for (const channelId of removedTopLevelIds) purgeCommunityChannel(registry, channelId)
+ }
+ upsertRows(registry, "servers", serverSchema, (row) => row.id, [server])
+ // Completeness is monotonic query state, not mutable server identity. A
+ // newer WS event may protect the row's fields without blocking this proof
+ // that its canonical tree has arrived.
+ promoteServerDetailComplete(registry, detail.id)
+ if (mode === "authoritative") {
+ replaceRows(
+ registry,
+ "categories",
+ categorySchema,
+ (row) => row.id,
+ categories,
+ (row) => row.serverId === detail.id,
+ )
+ replaceRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ channels,
+ (row) => row.serverId === detail.id && row.type !== "thread",
+ )
+ } else {
+ upsertRows(registry, "categories", categorySchema, (row) => row.id, categories)
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)
+ }
+ if (viewerId) {
+ if (mode === "authoritative") {
+ replaceRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ accessMemberships,
+ (row) => row.userId === viewerId
+ && row.relation === "access"
+ && authoritativeTopLevelIds.has(row.channelId),
+ )
+ } else {
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ accessMemberships,
+ )
+ }
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ unreadChildMemberships,
+ )
+ }
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, unreadChildStubs)
+ const unreadChildren = new Set(
+ Object.values(detail.forumUnreadState ?? {}).flatMap((state) => state.childIds),
+ )
+ patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ (row) => ({ ...row, unread: unreadChildren.has(row.id) }),
+ (row) => row.serverId === detail.id && row.type === "thread",
+ )
+ })
+}
+
+function ingestChannelMetadata(
+ registry: CommunityDbRegistry,
+ metadata: {
+ id: string
+ serverId: string
+ name: string
+ type: string
+ parentChannelId: string | null
+ parentMessageId: string | null
+ creatorId: string | null
+ archived: boolean | number
+ lastMessageAt: string | null
+ },
+) {
+ if (!(["text", "forum", "thread"] as const).includes(metadata.type as "text")) return
+ const existing = collectionRows(registry, "channels", channelSchema)
+ .find((row) => row.id === metadata.id)
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, [{
+ id: metadata.id,
+ serverId: metadata.serverId,
+ categoryId: existing?.categoryId ?? null,
+ name: metadata.name,
+ type: metadata.type as ChannelRow["type"],
+ parentChannelId: metadata.parentChannelId,
+ parentMessageId: metadata.parentMessageId,
+ creatorId: metadata.creatorId,
+ position: existing?.position ?? 0,
+ archived: metadata.archived === true || metadata.archived === 1,
+ muted: existing?.muted ?? false,
+ unread: existing?.unread ?? false,
+ ...(existing?.baseUnread === undefined ? {} : { baseUnread: existing.baseUnread }),
+ tags: existing?.tags ?? [],
+ pending: false,
+ lastMessageAt: metadata.lastMessageAt,
+ }])
+}
+
+export function ingestDms(
+ registry: CommunityDbRegistry,
+ response: DmsResponse,
+ mode: SnapshotIngestMode = "authoritative",
+) {
+ const viewerId = registry.accountId
+ if (!viewerId) return
+ const currentDmIds = new Set(
+ collectionRows(registry, "channels", channelSchema)
+ .filter((row) => row.type === "dm")
+ .map((row) => row.id),
+ )
+ const channels: ChannelRow[] = []
+ const memberships: ChannelMembershipRow[] = []
+ const profilePatches: CommunityProfilePatch[] = []
+ for (const dm of response.conversations) {
+ channels.push({
+ id: dm.id,
+ serverId: null,
+ categoryId: null,
+ name: "",
+ type: "dm",
+ parentChannelId: null,
+ parentMessageId: null,
+ creatorId: null,
+ position: 0,
+ archived: false,
+ muted: false,
+ unread: dm.unread === true,
+ tags: [],
+ pending: false,
+ lastMessageAt: null,
+ preview: dm.preview,
+ ...(dm.lastUnreadSeq === undefined ? {} : { lastUnreadSeq: dm.lastUnreadSeq }),
+ })
+ memberships.push(
+ {
+ id: channelMembershipKey(dm.id, viewerId, "access"),
+ channelId: dm.id,
+ userId: viewerId,
+ relation: "access",
+ },
+ {
+ id: channelMembershipKey(dm.id, dm.userId, "access"),
+ channelId: dm.id,
+ userId: dm.userId,
+ relation: "access",
+ },
+ )
+ profilePatches.push(communityUserProfilePatch(dm.userId, dm))
+ }
+ const dmIds = new Set(channels.map((row) => row.id))
+ const authoritativeDmIds = new Set([...currentDmIds, ...dmIds])
+ const removedDmIds = [...currentDmIds].filter((channelId) => !dmIds.has(channelId))
+ notifyManager.batch(() => {
+ if (mode === "authoritative") {
+ for (const channelId of removedDmIds) purgeCommunityChannel(registry, channelId)
+ replaceRows(registry, "channels", channelSchema, (row) => row.id, channels, (row) => row.type === "dm")
+ replaceRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ memberships,
+ (row) => row.relation === "access" && authoritativeDmIds.has(row.channelId),
+ )
+ } else {
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ memberships,
+ )
+ }
+ writeCommunityProfilePatches(profilePatches, registry)
+ })
+}
+
+/**
+ * Projects one locally confirmed DM summary before navigation. This is an
+ * additive event write: it cannot remove sibling conversations, and its
+ * revision fence prevents an older in-flight `/dms` snapshot from deleting
+ * the destination before the route mounts.
+ */
+export function publishCommunityDmSummary(
+ queryClient: QueryClient,
+ dm: DmsResponse["conversations"][number],
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
+ ingestDms(registry, { conversations: [dm] }, "merge")
+ return "published" as const
+ })
+}
+
+function ingestFolders(
+ registry: CommunityDbRegistry,
+ response: FoldersResponse,
+ mode: SnapshotIngestMode = "authoritative",
+) {
+ const folders: FolderRow[] = response.folders.map((folder) => ({
+ id: folder.id,
+ name: folder.name,
+ position: folder.position,
+ }))
+ const items: FolderItemRow[] = response.folders.flatMap((folder) => (
+ folder.servers.map((server, position) => ({
+ id: folderItemKey(folder.id, server.id),
+ folderId: folder.id,
+ serverId: server.id,
+ position,
+ }))
+ ))
+ notifyManager.batch(() => {
+ if (mode === "authoritative") {
+ replaceRows(registry, "folders", folderSchema, (row) => row.id, folders, () => true)
+ replaceRows(registry, "folderItems", folderItemSchema, (row) => row.id, items, () => true)
+ } else {
+ upsertRows(registry, "folders", folderSchema, (row) => row.id, folders)
+ upsertRows(registry, "folderItems", folderItemSchema, (row) => row.id, items)
+ }
+ })
+}
+
+export function ingestMessages(
+ registry: CommunityDbRegistry,
+ channelId: string,
+ messages: Msg[],
+) {
+ const rows: MessageRow[] = messages
+ .filter((message) => !message.id.startsWith("temp_") && message.failed !== true)
+ .map((message) => ({
+ ...message,
+ type: message.type ?? "chat",
+ channelId,
+ replyToId: message.replyTo?.id,
+ }))
+ upsertRows(registry, "messages", messageSchema, (row) => row.id, rows)
+ writeCommunityProfilePatches(messageProfilePatches(messages), registry)
+}
+
+export function ingestReadStateSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AccountReadStateSnapshot,
+ mode: SnapshotIngestMode = "authoritative",
+) {
+ const currentRevision = collectionRows(registry, "readStateClock", readStateClockSchema)
+ .find((row) => row.id === "account")?.revision ?? -1
+ if (snapshot.revision <= currentRevision) return
+ const readStates: ReadStateRow[] = snapshot.readStates.map((row) => ({ ...row }))
+ const clock: ReadStateClockRow = { id: "account", revision: snapshot.revision }
+ notifyManager.batch(() => {
+ if (mode === "authoritative") {
+ replaceRows(registry, "readStates", readStateSchema, (row) => row.channelId, readStates, () => true)
+ replaceRows(registry, "readStateClock", readStateClockSchema, (row) => row.id, [clock], () => true)
+ } else {
+ upsertRows(registry, "readStates", readStateSchema, (row) => row.channelId, readStates)
+ upsertRows(registry, "readStateClock", readStateClockSchema, (row) => row.id, [clock])
+ }
+ })
+}
+
+function ingestAttentionIncluded(
+ registry: CommunityDbRegistry,
+ included: AccountAttentionSnapshot["included"],
+) {
+ if (!included) return
+ const profiles = profileSchema.array().safeParse(included.profiles ?? [])
+ if (profiles.success) {
+ writeCommunityProfilePatches(profiles.data.map((profile) => (
+ communityUserProfilePatch(profile.userId, profile)
+ )), registry)
+ }
+ const messages = messageSchema.array().safeParse(included.messages ?? [])
+ if (messages.success) {
+ const current = new Map(
+ collectionRows(registry, "messages", messageSchema).map((row) => [row.id, row]),
+ )
+ const merged = messages.data.map((message) => ({
+ ...current.get(message.id),
+ ...Object.fromEntries(Object.entries(message).filter(([, value]) => value !== undefined)),
+ })) as MessageRow[]
+ upsertRows(registry, "messages", messageSchema, (row) => row.id, merged)
+ }
+}
+
+type AttentionProtectionState = {
+ optimisticClears: Set<symbol>
+ optimisticScopeDeletes: Map<symbol, {
+ scopeId: string
+ targetSeq: number
+ clearedAttentionCount: number
+ itemIds: Set<string>
+ requiresReconcileOnRestore: boolean
+ }>
+ optimisticItemDeletes: Map<symbol, Set<string>>
+ heldScopes: Set<string>
+ heldItems: Set<string>
+ heldScopeDeletes: Set<string>
+ heldItemDeletes: Set<string>
+}
+
+const attentionProtectionStates = new WeakMap<QueryClient, AttentionProtectionState>()
+
+function attentionProtectionState(queryClient: QueryClient) {
+ let state = attentionProtectionStates.get(queryClient)
+ if (!state) {
+ state = {
+ optimisticClears: new Set(),
+ optimisticScopeDeletes: new Map(),
+ optimisticItemDeletes: new Map(),
+ heldScopes: new Set(),
+ heldItems: new Set(),
+ heldScopeDeletes: new Set(),
+ heldItemDeletes: new Set(),
+ }
+ attentionProtectionStates.set(queryClient, state)
+ }
+ return state
+}
+
+export function hasAttentionScopeOptimisticFence(
+ queryClient: QueryClient,
+ scopeId: string,
+ targetSeq: number,
+) {
+ return [...attentionProtectionState(queryClient).optimisticScopeDeletes.values()]
+ .some((entry) => entry.scopeId === scopeId && entry.targetSeq >= targetSeq)
+}
+
+export function ingestAttentionSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AccountAttentionSnapshot,
+) {
+ const protection = attentionProtectionState(registry.queryClient)
+ const currentScopes = new Map(
+ collectionRows(registry, "attentionScopes", attentionScopeSchema)
+ .map((row) => [row.scopeId, row]),
+ )
+ const currentItems = new Map(
+ collectionRows(registry, "attentionItems", attentionItemSchema)
+ .map((row) => [row.id, row]),
+ )
+ const scopesById = new Map<string, AttentionScopeRow>(
+ snapshot.scopes.map((row) => [row.scopeId, { ...row }]),
+ )
+ const itemsById = new Map<string, AttentionItemRow>(
+ snapshot.items.map((row) => [row.id, { ...row }]),
+ )
+ const finalizedMessageIds = new Set(snapshot.items.flatMap((item) => (
+ item.messageId ? [item.messageId] : []
+ )))
+
+ // A local WS hint survives one snapshot that does not yet acknowledge it.
+ // The endpoint is primary-authoritative, so one retry is sufficient while
+ // still allowing a later snapshot to remove a genuinely obsolete hint.
+ for (const scopeId of protection.heldScopes) {
+ if (!scopesById.has(scopeId)) {
+ const current = currentScopes.get(scopeId)
+ if (current) scopesById.set(scopeId, current)
+ }
+ protection.heldScopes.delete(scopeId)
+ }
+ for (const itemId of protection.heldItems) {
+ const current = currentItems.get(itemId)
+ const finalized = current?.messageId && finalizedMessageIds.has(current.messageId)
+ if (!finalized && !itemsById.has(itemId) && current) itemsById.set(itemId, current)
+ protection.heldItems.delete(itemId)
+ }
+ for (const scopeId of protection.heldScopeDeletes) {
+ scopesById.delete(scopeId)
+ protection.heldScopeDeletes.delete(scopeId)
+ }
+ for (const itemId of protection.heldItemDeletes) {
+ itemsById.delete(itemId)
+ protection.heldItemDeletes.delete(itemId)
+ }
+
+ const optimisticClear = protection.optimisticClears.size > 0
+ const optimisticScopeDeletes = [...protection.optimisticScopeDeletes.values()]
+ const optimisticItemDeletes = new Set(
+ [...protection.optimisticItemDeletes.values()].flatMap((ids) => [...ids]),
+ )
+ const attentionMessages = new Map(
+ collectionRows(registry, "messages", messageSchema).map((message) => [message.id, message]),
+ )
+ for (const message of snapshot.included?.messages ?? []) {
+ const parsed = messageSchema.safeParse(message)
+ if (parsed.success) attentionMessages.set(parsed.data.id, parsed.data)
+ }
+ const fencedItems = new Set<string>()
+ for (const item of itemsById.values()) {
+ const fenced = optimisticScopeDeletes.some((entry) => (
+ item.scopeId === entry.scopeId
+ && (
+ entry.itemIds.has(item.id)
+ || (item.messageId
+ && (attentionMessages.get(item.messageId)?.seq ?? Number.POSITIVE_INFINITY)
+ <= entry.targetSeq)
+ )
+ ))
+ if (!fenced) continue
+ fencedItems.add(item.id)
+ }
+ const scopes = optimisticClear ? [] : [...scopesById.values()].flatMap((scope) => {
+ const targetSeq = optimisticScopeDeletes.reduce((target, entry) => (
+ entry.scopeId === scope.scopeId ? Math.max(target, entry.targetSeq) : target
+ ), -1)
+ if (targetSeq < 0) return [scope]
+ const clearedAttentionCount = optimisticScopeDeletes.reduce((count, entry) => (
+ entry.scopeId === scope.scopeId ? count + entry.clearedAttentionCount : count
+ ), 0)
+ const ordinaryUnread = scope.ordinaryUnread && scope.lastUnreadSeq > targetSeq
+ const lastAttentionSeq = scope.lastAttentionSeq !== null
+ && scope.lastAttentionSeq !== undefined
+ && scope.lastAttentionSeq > targetSeq
+ ? scope.lastAttentionSeq
+ : null
+ const attentionCount = lastAttentionSeq === null
+ ? 0
+ : Math.max(0, scope.attentionCount - clearedAttentionCount)
+ return ordinaryUnread || attentionCount > 0
+ ? [{ ...scope, ordinaryUnread, lastAttentionSeq, attentionCount }]
+ : []
+ })
+ const items = [...itemsById.values()].filter((item) => (
+ (!optimisticClear || item.kind === "friend_request")
+ && !fencedItems.has(item.id)
+ && !optimisticItemDeletes.has(item.id)
+ ))
+ notifyManager.batch(() => {
+ replaceRows(registry, "attentionScopes", attentionScopeSchema, (row) => row.scopeId, scopes, () => true)
+ replaceRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, items, () => true)
+ ingestAttentionIncluded(registry, snapshot.included)
+ })
+ return "applied" as const
+}
+
+export type AttentionOptimisticSnapshot = {
+ token: symbol
+ publicationRevision: number
+ scopes: AttentionScopeRow[]
+ items: AttentionItemRow[]
+}
+
+export function clearAttentionOptimistically(
+ registry: CommunityDbRegistry,
+): AttentionOptimisticSnapshot {
+ const token = Symbol("attention-clear")
+ const snapshot = {
+ token,
+ publicationRevision: 0,
+ scopes: collectionRows(registry, "attentionScopes", attentionScopeSchema),
+ items: collectionRows(registry, "attentionItems", attentionItemSchema),
+ }
+ const protection = attentionProtectionState(registry.queryClient)
+ protection.optimisticClears.add(token)
+ protection.heldScopes.clear()
+ protection.heldItems.clear()
+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {
+ notifyManager.batch(() => {
+ deleteRows(registry, "attentionScopes", attentionScopeSchema, () => true)
+ deleteRows(registry, "attentionItems", attentionItemSchema, () => true)
+ const friendRequests = snapshot.items.filter((row) => row.kind === "friend_request")
+ if (friendRequests.length > 0) {
+ upsertRows(
+ registry,
+ "attentionItems",
+ attentionItemSchema,
+ (row) => row.id,
+ friendRequests,
+ )
+ }
+ })
+ })
+ snapshot.publicationRevision = canonicalRevisionState(registry.queryClient).revision
+ return snapshot
+}
+
+export function commitAttentionOptimisticSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AttentionOptimisticSnapshot,
+) {
+ attentionProtectionState(registry.queryClient).optimisticClears.delete(snapshot.token)
+}
+
+export function restoreAttentionOptimisticDomains(
+ registry: CommunityDbRegistry,
+ snapshot: AttentionOptimisticSnapshot,
+ failedDomains: ReadonlySet<"channels" | "dms" | "mentions">,
+) {
+ const protection = attentionProtectionState(registry.queryClient)
+ protection.optimisticClears.delete(snapshot.token)
+ if (canonicalRevisionState(registry.queryClient).revision !== snapshot.publicationRevision) return false
+
+ const restoreMentions = failedDomains.has("mentions")
+ const scopes = snapshot.scopes.flatMap((scope): AttentionScopeRow[] => {
+ const isDm = scope.serverId == null
+ if (isDm) return failedDomains.has("dms") ? [scope] : []
+ const ordinaryUnread = failedDomains.has("channels") && scope.ordinaryUnread
+ const attentionCount = restoreMentions ? scope.attentionCount : 0
+ if (!ordinaryUnread && attentionCount === 0) return []
+ return [{
+ ...scope,
+ ordinaryUnread,
+ lastUnreadSeq: ordinaryUnread
+ ? scope.lastUnreadSeq
+ : scope.lastAttentionSeq ?? scope.lastUnreadSeq,
+ lastAttentionSeq: restoreMentions ? scope.lastAttentionSeq : null,
+ attentionCount,
+ }]
+ })
+ const items = restoreMentions
+ ? snapshot.items.filter((item) => item.kind !== "friend_request")
+ : []
+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {
+ notifyManager.batch(() => {
+ upsertRows(registry, "attentionScopes", attentionScopeSchema, (row) => row.scopeId, scopes)
+ upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, items)
+ })
+ })
+ return true
+}
+
+export function restoreAttentionOptimisticSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AttentionOptimisticSnapshot,
+) {
+ const protection = attentionProtectionState(registry.queryClient)
+ protection.optimisticClears.delete(snapshot.token)
+ if (canonicalRevisionState(registry.queryClient).revision !== snapshot.publicationRevision) return false
+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {
+ notifyManager.batch(() => {
+ replaceRows(
+ registry,
+ "attentionScopes",
+ attentionScopeSchema,
+ (row) => row.scopeId,
+ snapshot.scopes,
+ () => true,
+ )
+ replaceRows(
+ registry,
+ "attentionItems",
+ attentionItemSchema,
+ (row) => row.id,
+ snapshot.items,
+ () => true,
+ )
+ })
+ })
+ return true
+}
+
+export type AttentionScopeOptimisticSnapshot = {
+ token: symbol
+ publicationRevision: number
+ scopeId: string
+ targetSeq: number
+ clearedAttentionCount: number
+ scopes: AttentionScopeRow[]
+ items: AttentionItemRow[]
+}
+
+export function clearAttentionScopeOptimistically(
+ registry: CommunityDbRegistry,
+ scopeId: string,
+ targetSeq: number,
+): AttentionScopeOptimisticSnapshot {
+ const token = Symbol("attention-scope-delete")
+ const scopes = collectionRows(registry, "attentionScopes", attentionScopeSchema)
+ .filter((scope) => scope.scopeId === scopeId)
+ const messages = new Map(
+ collectionRows(registry, "messages", messageSchema).map((message) => [message.id, message]),
+ )
+ const currentScope = scopes[0]
+ const items = collectionRows(registry, "attentionItems", attentionItemSchema)
+ .filter((item) => {
+ if (item.scopeId !== scopeId) return false
+ const seq = item.messageId ? messages.get(item.messageId)?.seq : undefined
+ return seq !== undefined ? seq <= targetSeq : (currentScope?.lastUnreadSeq ?? 0) <= targetSeq
+ })
+ const itemIds = new Set(items.map((item) => item.id))
+ const survivingAttentionCount = collectionRows(registry, "attentionItems", attentionItemSchema)
+ .filter((item) => {
+ if (item.scopeId !== scopeId || !item.messageId) return false
+ const seq = messages.get(item.messageId)?.seq
+ return seq !== undefined && seq > targetSeq
+ })
+ .length
+ const clearedAttentionCount = Math.max(
+ 0,
+ (currentScope?.attentionCount ?? 0) - survivingAttentionCount,
+ )
+ const protection = attentionProtectionState(registry.queryClient)
+ protection.optimisticScopeDeletes.set(token, {
+ scopeId,
+ targetSeq,
+ clearedAttentionCount,
+ itemIds,
+ requiresReconcileOnRestore: false,
+ })
+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {
+ notifyManager.batch(() => {
+ const scope = currentScope
+ if (scope) {
+ const ordinaryUnread = scope.ordinaryUnread && scope.lastUnreadSeq > targetSeq
+ const lastAttentionSeq = scope.lastAttentionSeq !== null
+ && scope.lastAttentionSeq !== undefined
+ && scope.lastAttentionSeq > targetSeq
+ ? scope.lastAttentionSeq
+ : null
+ const attentionCount = lastAttentionSeq === null
+ ? 0
+ : Math.max(0, scope.attentionCount - clearedAttentionCount)
+ if (ordinaryUnread || attentionCount > 0) {
+ upsertRows(
+ registry,
+ "attentionScopes",
+ attentionScopeSchema,
+ (row) => row.scopeId,
+ [{ ...scope, ordinaryUnread, lastAttentionSeq, attentionCount }],
+ )
+ } else {
+ deleteRows(
+ registry,
+ "attentionScopes",
+ attentionScopeSchema,
+ (row) => row.scopeId === scopeId,
+ )
+ }
+ }
+ deleteRows(
+ registry,
+ "attentionItems",
+ attentionItemSchema,
+ (item) => itemIds.has(item.id),
+ )
+ })
+ })
+ return {
+ token,
+ publicationRevision: canonicalRevisionState(registry.queryClient).revision,
+ scopeId,
+ targetSeq,
+ clearedAttentionCount,
+ scopes,
+ items,
+ }
+}
+
+export function commitAttentionScopeOptimisticSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AttentionScopeOptimisticSnapshot,
+) {
+ const fences = attentionProtectionState(registry.queryClient).optimisticScopeDeletes
+ const settled = fences.get(snapshot.token)
+ if (!settled || !fences.delete(snapshot.token)) return
+ const remaining = [...fences.values()]
+ .filter((entry) => entry.scopeId === snapshot.scopeId)
+ .sort((left, right) => right.targetSeq - left.targetSeq)
+ const successor = remaining[0]
+ if (!successor) return
+ successor.targetSeq = Math.max(successor.targetSeq, settled.targetSeq)
+ successor.clearedAttentionCount += settled.clearedAttentionCount
+ for (const itemId of settled.itemIds) successor.itemIds.add(itemId)
+ successor.requiresReconcileOnRestore ||= settled.requiresReconcileOnRestore
+}
+
+export function restoreAttentionScopeOptimisticSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AttentionScopeOptimisticSnapshot,
+) {
+ const fences = attentionProtectionState(registry.queryClient).optimisticScopeDeletes
+ const settled = fences.get(snapshot.token)
+ fences.delete(snapshot.token)
+ const successor = [...fences.values()]
+ .find((entry) => (
+ entry.scopeId === snapshot.scopeId && entry.targetSeq >= snapshot.targetSeq
+ ))
+ if (settled && successor) {
+ successor.clearedAttentionCount += settled.clearedAttentionCount
+ for (const itemId of settled.itemIds) successor.itemIds.add(itemId)
+ successor.requiresReconcileOnRestore = true
+ }
+ const absorbedCommittedFence = Boolean(
+ settled
+ && settled.targetSeq > snapshot.targetSeq
+ )
+ if (
+ successor
+ || absorbedCommittedFence
+ || settled?.requiresReconcileOnRestore
+ || canonicalRevisionState(registry.queryClient).revision !== snapshot.publicationRevision
+ ) {
+ return false
+ }
+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {
+ notifyManager.batch(() => {
+ upsertRows(
+ registry,
+ "attentionScopes",
+ attentionScopeSchema,
+ (row) => row.scopeId,
+ snapshot.scopes,
+ )
+ upsertRows(
+ registry,
+ "attentionItems",
+ attentionItemSchema,
+ (row) => row.id,
+ snapshot.items,
+ )
+ })
+ })
+ return true
+}
+
+export type AttentionItemsOptimisticSnapshot = {
+ token: symbol
+ publicationRevision: number
+ items: AttentionItemRow[]
+}
+
+export function removeAttentionItemsOptimistically(
+ registry: CommunityDbRegistry,
+ remove: (item: AttentionItemRow) => boolean,
+): AttentionItemsOptimisticSnapshot {
+ const items = collectionRows(registry, "attentionItems", attentionItemSchema).filter(remove)
+ const token = Symbol("attention-item-delete")
+ const protection = attentionProtectionState(registry.queryClient)
+ protection.optimisticItemDeletes.set(token, new Set(items.map((item) => item.id)))
+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {
+ deleteRows(registry, "attentionItems", attentionItemSchema, remove)
+ })
+ return {
+ token,
+ publicationRevision: canonicalRevisionState(registry.queryClient).revision,
+ items,
+ }
+}
+
+export function commitAttentionItemsOptimisticSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AttentionItemsOptimisticSnapshot,
+) {
+ attentionProtectionState(registry.queryClient).optimisticItemDeletes.delete(snapshot.token)
+}
+
+export function restoreAttentionItemsOptimisticSnapshot(
+ registry: CommunityDbRegistry,
+ snapshot: AttentionItemsOptimisticSnapshot,
+) {
+ attentionProtectionState(registry.queryClient).optimisticItemDeletes.delete(snapshot.token)
+ if (canonicalRevisionState(registry.queryClient).revision !== snapshot.publicationRevision) return false
+ withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => {
+ upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, snapshot.items)
+ })
+ return true
+}
+
+function ingestNotificationSettings(
+ registry: CommunityDbRegistry,
+ settings: NotificationSettings,
+ mode: SnapshotIngestMode = "authoritative",
+) {
+ const rows: NotificationSettingRow[] = settings.raw.flatMap((row) => {
+ if (Boolean(row.serverId) === Boolean(row.channelId)) return []
+ const target = { serverId: row.serverId ?? null, channelId: row.channelId ?? null }
+ return [{ id: notificationSettingKey(target), ...target, level: row.level }]
+ })
+ if (mode === "authoritative") {
+ replaceRows(
+ registry,
+ "notificationSettings",
+ notificationSettingSchema,
+ (row) => row.id,
+ rows,
+ () => true,
+ )
+ } else {
+ upsertRows(
+ registry,
+ "notificationSettings",
+ notificationSettingSchema,
+ (row) => row.id,
+ rows,
+ )
+ }
+}
+
+export type CommunityLiveSnapshot =
+ | { kind: "servers"; data: ServersResponse }
+ | { kind: "server-detail"; data: ServerDetail }
+ | { kind: "folders"; data: FoldersResponse }
+ | { kind: "dms"; data: DmsResponse }
+ | { kind: "read-state"; data: AccountReadStateSnapshot }
+ | { kind: "notification-settings"; data: NotificationSettings }
+
+declare const communityLiveSnapshotTokenBrand: unique symbol
+
+export type CommunityLiveSnapshotToken = {
+ readonly viewerId: string | null
+ readonly accountEpoch: number
+ readonly accessEpoch: number
+ readonly canonicalRevision: number
+ readonly queryClient: QueryClient
+ readonly [communityLiveSnapshotTokenBrand]: true
+}
+
+type StructuralCommunityLiveSnapshot = Exclude<CommunityLiveSnapshot, { kind: "read-state" }>
+
+type CommunityLiveSnapshotPublication =
+ | {
+ snapshot: StructuralCommunityLiveSnapshot
+ proof: {
+ kind: "structural"
+ token: CommunityLiveSnapshotToken
+ signal: AbortSignal | undefined
+ }
+ }
+ | {
+ snapshot: Extract<CommunityLiveSnapshot, { kind: "read-state" }>
+ proof: {
+ kind: "read-state"
+ token: CommunityLiveSnapshotToken
+ signal: AbortSignal | undefined
+ requestGeneration: number
+ currentRequestGeneration: number
+ targetRevision: number | null
+ }
+ }
+
+export type CommunityFreshQueryProof = {
+ token: CommunityLiveSnapshotToken
+ signal: AbortSignal | undefined
+}
+
+export function captureCommunityLiveSnapshotToken(
+ queryClient: QueryClient,
+): CommunityLiveSnapshotToken {
+ const state = useCommunityWsStore.getState()
+ return {
+ viewerId: state.profileViewerId,
+ accountEpoch: state.profileAccountEpoch,
+ accessEpoch: state.accessEpoch,
+ canonicalRevision: canonicalRevisionState(queryClient).revision,
+ queryClient,
+ } as CommunityLiveSnapshotToken
+}
+
+export function assertCommunityLiveSnapshotTokenCurrent(
+ queryClient: QueryClient,
+ token: CommunityLiveSnapshotToken,
+ signal: AbortSignal | undefined,
+) {
+ const state = useCommunityWsStore.getState()
+ if (
+ signal?.aborted
+ || state.profileViewerId !== token.viewerId
+ || state.profileAccountEpoch !== token.accountEpoch
+ || state.accessEpoch !== token.accessEpoch
+ || queryClient !== token.queryClient
+ ) throw new DOMException("Stale community live snapshot", "AbortError")
+}
+
+/**
+ * Publishes a newly settled live snapshot into the canonical DB.
+ *
+ * This is the only query-owned path allowed to replace or delete canonical
+ * rows. Hydrated or manually written transport caches are never DB inputs;
+ * only the fresh queryFn that owns this proof may publish its response.
+ */
+export function publishCommunityLiveSnapshot(
+ queryClient: QueryClient,
+ publication: CommunityLiveSnapshotPublication,
+) {
+ const { proof, snapshot } = publication
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
+ if (proof.kind === "read-state") {
+ if (
+ proof.requestGeneration !== proof.currentRequestGeneration
+ || (
+ proof.targetRevision !== null
+ && (snapshot as Extract<CommunityLiveSnapshot, { kind: "read-state" }>).data.revision
+ < proof.targetRevision
+ )
+ ) return "superseded" as const
+ }
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, {
+ kind: "query",
+ requestRevision: proof.token.canonicalRevision,
+ }, () => {
+ switch (snapshot.kind) {
+ case "servers":
+ ingestServers(registry, snapshot.data)
+ break
+ case "server-detail":
+ ingestServerDetail(registry, snapshot.data)
+ break
+ case "folders":
+ ingestFolders(registry, snapshot.data)
+ break
+ case "dms":
+ ingestDms(registry, snapshot.data)
+ break
+ case "read-state":
+ ingestReadStateSnapshot(registry, snapshot.data)
+ break
+ case "notification-settings":
+ ingestNotificationSettings(registry, snapshot.data)
+ break
+ }
+ return "published" as const
+ })
+}
+
+export function publishAccountAttentionSnapshot(
+ queryClient: QueryClient,
+ publication: {
+ snapshot: AccountAttentionSnapshot
+ proof: CommunityFreshQueryProof
+ },
+) {
+ assertCommunityLiveSnapshotTokenCurrent(
+ queryClient,
+ publication.proof.token,
+ publication.proof.signal,
+ )
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, {
+ kind: "query",
+ requestRevision: publication.proof.token.canonicalRevision,
+ }, () => {
+ ingestAttentionSnapshot(registry, publication.snapshot)
+ return "published" as const
+ })
+}
+
+/** Merge confirmed rows from one fresh transport response into canonical DB. */
+export function publishCommunityMessages(
+ queryClient: QueryClient,
+ publication: {
+ channelId: string
+ messages: Msg[]
+ proof: CommunityFreshQueryProof
+ },
+) {
+ assertCommunityLiveSnapshotTokenCurrent(
+ queryClient,
+ publication.proof.token,
+ publication.proof.signal,
+ )
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, {
+ kind: "query",
+ requestRevision: publication.proof.token.canonicalRevision,
+ }, () => {
+ ingestMessages(registry, publication.channelId, publication.messages)
+ return "published" as const
+ })
+}
+
+/** Publish message entities embedded in a cross-scope transport response. */
+export function publishCommunityEmbeddedMessages(
+ queryClient: QueryClient,
+ publication: {
+ entries: Array<{ channelId: string; message: Msg }>
+ proof: CommunityFreshQueryProof
+ },
+) {
+ assertCommunityLiveSnapshotTokenCurrent(
+ queryClient,
+ publication.proof.token,
+ publication.proof.signal,
+ )
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, {
+ kind: "query",
+ requestRevision: publication.proof.token.canonicalRevision,
+ }, () => {
+ const byChannel = new Map<string, Msg[]>()
+ for (const { channelId, message } of publication.entries) {
+ byChannel.set(channelId, [...(byChannel.get(channelId) ?? []), message])
+ }
+ notifyManager.batch(() => {
+ for (const [channelId, messages] of byChannel) {
+ ingestMessages(registry, channelId, messages)
+ }
+ })
+ return "published" as const
+ })
+}
+
+export type CommunityChannelMetadata = {
+ id: string
+ serverId: string
+ name: string
+ type: string
+ parentChannelId: string | null
+ parentMessageId: string | null
+ creatorId: string | null
+ archived: boolean | number
+ lastMessageAt: string | null
+}
+
+/** Publish one verified channel metadata response and its viewer access fact. */
+export function publishCommunityChannelMetadata(
+ queryClient: QueryClient,
+ publication: {
+ metadata: CommunityChannelMetadata
+ proof: CommunityFreshQueryProof
+ },
+) {
+ assertCommunityLiveSnapshotTokenCurrent(
+ queryClient,
+ publication.proof.token,
+ publication.proof.signal,
+ )
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, {
+ kind: "query",
+ requestRevision: publication.proof.token.canonicalRevision,
+ }, () => {
+ ingestChannelMetadata(registry, publication.metadata)
+ const viewerId = registry.accountId
+ if (viewerId) {
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ [{
+ id: channelMembershipKey(publication.metadata.id, viewerId, "access"),
+ channelId: publication.metadata.id,
+ userId: viewerId,
+ relation: "access",
+ source: "explicit",
+ }],
+ )
+ }
+ return "published" as const
+ })
+}
+
+/** Merge the fresh all-server ref directory without degrading known rows. */
+export function publishCommunityChannelDirectory(
+ queryClient: QueryClient,
+ publication: {
+ directory: ChannelRefDirectory
+ proof: CommunityFreshQueryProof
+ },
+) {
+ assertCommunityLiveSnapshotTokenCurrent(
+ queryClient,
+ publication.proof.token,
+ publication.proof.signal,
+ )
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, {
+ kind: "query",
+ requestRevision: publication.proof.token.canonicalRevision,
+ }, () => {
+ const existingServers = new Map(
+ collectionRows(registry, "servers", serverSchema).map((row) => [row.id, row]),
+ )
+ const existingChannels = new Map(
+ collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),
+ )
+ const viewerId = registry.accountId
+ const servers: ServerRow[] = publication.directory.map((server, position) => ({
+ id: server.id,
+ position: existingServers.get(server.id)?.position ?? position,
+ name: server.name,
+ discriminator: server.discriminator,
+ description: existingServers.get(server.id)?.description ?? "",
+ ownerId: existingServers.get(server.id)?.ownerId ?? "",
+ icon: existingServers.get(server.id)?.icon ?? null,
+ official: existingServers.get(server.id)?.official ?? false,
+ isOwner: existingServers.get(server.id)?.isOwner ?? false,
+ unread: existingServers.get(server.id)?.unread ?? false,
+ mentions: existingServers.get(server.id)?.mentions ?? 0,
+ detailComplete: existingServers.get(server.id)?.detailComplete ?? false,
+ }))
+ const channels: ChannelRow[] = publication.directory.flatMap((server) => (
+ server.channels.flatMap((channel, position) => {
+ const existing = existingChannels.get(channel.id)
+ // Older directory payloads predate the subtype field and therefore only
+ // describe text channels. Preserve any richer canonical subtype first.
+ const type = channel.type ?? existing?.type ?? "text"
+ return [{
+ id: channel.id,
+ serverId: server.id,
+ categoryId: existing?.categoryId ?? null,
+ name: channel.name,
+ type,
+ parentChannelId: null,
+ parentMessageId: null,
+ creatorId: existing?.creatorId ?? null,
+ position: existing?.position ?? position,
+ archived: existing?.archived ?? false,
+ muted: existing?.muted ?? false,
+ unread: existing?.unread ?? false,
+ ...(existing?.baseUnread === undefined ? {} : { baseUnread: existing.baseUnread }),
+ tags: existing?.tags ?? [],
+ pending: existing?.pending ?? false,
+ lastMessageAt: existing?.lastMessageAt ?? null,
+ }]
+ })
+ ))
+ notifyManager.batch(() => {
+ upsertRows(registry, "servers", serverSchema, (row) => row.id, servers)
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)
+ if (viewerId) {
+ upsertRows(
+ registry,
+ "serverMemberships",
+ serverMembershipSchema,
+ (row) => row.id,
+ servers.map((server) => ({
+ id: serverMembershipKey(server.id, viewerId),
+ serverId: server.id,
+ userId: viewerId,
+ role: server.isOwner ? "owner" : "member",
+ viewer: true,
+ })),
+ )
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ channels.map((channel) => ({
+ id: channelMembershipKey(channel.id, viewerId, "access"),
+ channelId: channel.id,
+ userId: viewerId,
+ relation: "access" as const,
+ source: "inherited" as const,
+ })),
+ )
+ }
+ })
+ return "published" as const
+ })
+}
+
+export type CommunityForumSidebarChannel = {
+ id: string
+ name: string
+ parentChannelId: string | null
+ parentMessageId: string | null
+ activityAt: string
+ unread: boolean
+ serverId?: string
+ type?: string
+ creatorId?: string | null
+ archived?: boolean | number
+ lastMessageAt?: string | null
+ participating?: boolean
+}
+
+export type CommunityForumSidebarOpener = {
+ id: string
+ content: string
+ seq?: number
+ channelId?: string
+ type?: "chat" | "system"
+}
+
+/** Publish the service facts carried by one forum-sidebar response. */
+export function publishCommunityForumSidebar(
+ queryClient: QueryClient,
+ publication: {
+ serverId: string
+ channels: CommunityForumSidebarChannel[]
+ openers: CommunityForumSidebarOpener[]
+ negativeRetain?: {
+ id: string
+ disposition: "opener-archived" | "genuine-negative"
+ } | null
+ proof: CommunityFreshQueryProof
+ },
+) {
+ assertCommunityLiveSnapshotTokenCurrent(
+ queryClient,
+ publication.proof.token,
+ publication.proof.signal,
+ )
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return "no-registry" as const
+ return withCanonicalWriteContext(queryClient, {
+ kind: "query",
+ requestRevision: publication.proof.token.canonicalRevision,
+ }, () => {
+ const existingById = new Map(
+ collectionRows(registry, "channels", channelSchema).map((row) => [row.id, row]),
+ )
+ const channels: ChannelRow[] = publication.channels.flatMap((channel) => {
+ if (!channel.parentChannelId || !channel.parentMessageId) return []
+ const existing = existingById.get(channel.id)
+ return [{
+ id: channel.id,
+ serverId: channel.serverId ?? publication.serverId,
+ categoryId: null,
+ name: channel.name,
+ type: "thread" as const,
+ parentChannelId: channel.parentChannelId,
+ parentMessageId: channel.parentMessageId,
+ creatorId: channel.creatorId ?? existing?.creatorId ?? null,
+ position: existing?.position ?? 0,
+ archived: channel.archived === true || channel.archived === 1,
+ muted: existing?.muted ?? false,
+ unread: channel.unread,
+ tags: existing?.tags ?? [],
+ pending: false,
+ lastMessageAt: channel.lastMessageAt ?? channel.activityAt,
+ }]
+ })
+ const viewerId = registry.accountId
+ notifyManager.batch(() => {
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, channels)
+ if (viewerId) {
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ channels.map((channel) => ({
+ id: channelMembershipKey(channel.id, viewerId, "access"),
+ channelId: channel.id,
+ userId: viewerId,
+ relation: "access" as const,
+ source: "explicit" as const,
+ })),
+ )
+ const participating = publication.channels
+ .filter((channel) => channel.participating !== false)
+ .map((channel) => channel.id)
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ participating.map((channelId) => ({
+ id: channelMembershipKey(channelId, viewerId, "notify"),
+ channelId,
+ userId: viewerId,
+ relation: "notify" as const,
+ source: "explicit" as const,
+ })),
+ )
+ }
+ for (const opener of publication.openers) {
+ const channelId = opener.channelId
+ ?? channels.find((channel) => channel.parentMessageId === opener.id)?.parentChannelId
+ if (!channelId) continue
+ ingestMessages(registry, channelId, [{
+ ...opener,
+ type: opener.type ?? "chat",
+ } as Msg])
+ }
+ if (publication.negativeRetain) {
+ const { id, disposition } = publication.negativeRetain
+ deleteRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.channelId === id
+ && row.userId === viewerId
+ && row.relation === "notify",
+ )
+ if (disposition === "genuine-negative") {
+ patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ (row) => ({ ...row, unread: false }),
+ (row) => row.id === id,
+ )
+ }
+ }
+ })
+ return "published" as const
+ })
+}
+
+export function patchCanonicalCommunityChannel(
+ queryClient: QueryClient,
+ channelId: string,
+ patch: (row: ChannelRow) => ChannelRow,
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return false
+ return patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ patch,
+ (row) => row.id === channelId,
+ )
+}
+
+export function patchCanonicalCommunityMessage(
+ queryClient: QueryClient,
+ messageId: string,
+ patch: (row: MessageRow) => MessageRow,
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return false
+ return withCanonicalWriteContext(queryClient, { kind: "event" }, () => (
+ patchRows(
+ registry,
+ "messages",
+ messageSchema,
+ (row) => row.id,
+ patch,
+ (row) => row.id === messageId,
+ )
+ ))
+}
+
+export function removeCanonicalCommunityChannel(
+ queryClient: QueryClient,
+ channelId: string,
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return false
+ const exists = collectionRows(registry, "channels", channelSchema)
+ .some((row) => row.id === channelId)
+ if (exists) purgeCommunityChannel(registry, channelId)
+ return exists
+}
+
+export function removeCanonicalCommunityChannelMembership(
+ queryClient: QueryClient,
+ channelId: string,
+ relation: "access" | "notify",
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry?.accountId) return false
+ deleteRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.channelId === channelId
+ && row.userId === registry.accountId
+ && row.relation === relation,
+ )
+ return true
+}
+
+export function setCanonicalCommunityChannelMembership(
+ queryClient: QueryClient,
+ channelId: string,
+ relation: "access" | "notify",
+ present: boolean,
+ options?: { event?: boolean },
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry?.accountId) return false
+ if (!present) {
+ return removeCanonicalCommunityChannelMembership(queryClient, channelId, relation)
+ }
+ const viewerId = registry.accountId
+ const write = () => {
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ [{
+ id: channelMembershipKey(channelId, viewerId, relation),
+ channelId,
+ userId: viewerId,
+ relation,
+ source: "explicit",
+ }],
+ )
+ return true
+ }
+ return options?.event
+ ? withCanonicalWriteContext(queryClient, { kind: "event" }, write)
+ : write()
+}
+
+export function getCanonicalCommunityChannels(queryClient: QueryClient) {
+ const registry = getCommunityDbRegistry(queryClient)
+ return registry ? collectionRows(registry, "channels", channelSchema) : []
+}
+
+export function getCanonicalCommunityChannelMemberships(queryClient: QueryClient) {
+ const registry = getCommunityDbRegistry(queryClient)
+ return registry
+ ? collectionRows(registry, "channelMemberships", channelMembershipSchema)
+ : []
+}
+
+export function getCanonicalCommunityMessages(queryClient: QueryClient) {
+ const registry = getCommunityDbRegistry(queryClient)
+ return registry ? collectionRows(registry, "messages", messageSchema) : []
+}
+
+export function purgeCommunityServer(registry: CommunityDbRegistry, serverId: string) {
+ if (isProtectedFromQueryWrite(registry, "servers", serverId)) return
+ const removedChannelIds = new Set(
+ collectionRows(registry, "channels", channelSchema)
+ .filter((row) => row.serverId === serverId)
+ .map((row) => row.id),
+ )
+ clearChannelTransientState(registry, removedChannelIds, serverId)
+ pruneInboxCaches(registry.queryClient, removedChannelIds, serverId)
+ getAccountUnreadProjection(
+ registry.queryClient,
+ registry.accountId ?? "__anonymous__",
+ ).retireAccessScope({
+ kind: "server",
+ serverId,
+ })
+ clearLastChannel(serverId)
+ useCommunityWsStore.getState().revokeServerAccess(serverId)
+ useMessageStreamStore.getState().removeServer(serverId)
+ void registry.queryClient.cancelQueries({ queryKey: communityKeys.server(serverId) })
+ registry.queryClient.removeQueries({ queryKey: communityKeys.server(serverId) })
+ const community = useCommunityStore.getState()
+ if (community.currentServerId === serverId) {
+ community.setCurrentChannelMeta(null)
+ community.setCurrentChannelId(null)
+ community.setCurrentServerId(null)
+ }
+ notifyManager.batch(() => {
+ deleteRows(registry, "servers", serverSchema, (row) => row.id === serverId, [serverId])
+ deleteRows(registry, "categories", categorySchema, (row) => row.serverId === serverId)
+ deleteRows(registry, "channels", channelSchema, (row) => removedChannelIds.has(row.id))
+ deleteRows(registry, "serverMemberships", serverMembershipSchema, (row) => row.serverId === serverId)
+ deleteRows(registry, "channelMemberships", channelMembershipSchema, (row) => removedChannelIds.has(row.channelId))
+ deleteRows(registry, "messages", messageSchema, (row) => removedChannelIds.has(row.channelId))
+ deleteRows(registry, "readStates", readStateSchema, (row) => removedChannelIds.has(row.channelId))
+ deleteRows(registry, "attentionScopes", attentionScopeSchema, (row) => (
+ row.serverId === serverId || removedChannelIds.has(row.channelId)
+ ))
+ deleteRows(registry, "attentionItems", attentionItemSchema, (row) => (
+ Boolean(row.scopeId && removedChannelIds.has(row.scopeId))
+ ))
+ deleteRows(registry, "folderItems", folderItemSchema, (row) => row.serverId === serverId)
+ deleteRows(registry, "notificationSettings", notificationSettingSchema, (row) => (
+ row.serverId === serverId || Boolean(row.channelId && removedChannelIds.has(row.channelId))
+ ))
+ garbageCollectCommunityProfiles(registry)
+ })
+}
+
+export function purgeCommunityChannel(registry: CommunityDbRegistry, channelId: string) {
+ if (isProtectedFromQueryWrite(registry, "channels", channelId)) return
+ const channels = collectionRows(registry, "channels", channelSchema)
+ const root = channels.find((row) => row.id === channelId)
+ const removed = new Set([
+ channelId,
+ ...channels
+ .filter((row) => row.id === channelId || row.parentChannelId === channelId)
+ .map((row) => row.id),
+ ])
+ clearChannelTransientState(registry, removed, root?.serverId ?? null)
+ notifyManager.batch(() => {
+ deleteRows(registry, "channels", channelSchema, (row) => removed.has(row.id), [channelId])
+ deleteRows(registry, "channelMemberships", channelMembershipSchema, (row) => removed.has(row.channelId))
+ deleteRows(registry, "messages", messageSchema, (row) => removed.has(row.channelId))
+ deleteRows(registry, "readStates", readStateSchema, (row) => removed.has(row.channelId))
+ deleteRows(registry, "attentionScopes", attentionScopeSchema, (row) => removed.has(row.channelId))
+ deleteRows(registry, "attentionItems", attentionItemSchema, (row) => (
+ Boolean(row.scopeId && removed.has(row.scopeId))
+ ))
+ deleteRows(registry, "notificationSettings", notificationSettingSchema, (row) => (
+ Boolean(row.channelId && removed.has(row.channelId))
+ ))
+ garbageCollectCommunityProfiles(registry)
+ })
+}
+
+function projectProfilePatch(
+ registry: CommunityDbRegistry,
+ userId: string,
+ patch: Omit<CommunityProfilePatch, "id">,
+) {
+ writeCommunityProfilePatches([{ id: userId, ...patch }], registry, { event: true })
+}
+
+export function projectAttentionUnreadBump(
+ queryClient: QueryClient,
+ event: Extract<CommunityWsEvent, { type: "community:unread.bump" }>,
+ evidence?: { seq: number },
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry || event.userId !== registry.accountId) return
+ const current = collectionRows(registry, "attentionScopes", attentionScopeSchema)
+ .find((row) => row.scopeId === event.channelId)
+ const seq = evidence?.seq ?? current?.lastUnreadSeq ?? 0
+ if (hasAttentionScopeOptimisticFence(queryClient, event.channelId, seq)) return
+ const next: AttentionScopeRow = {
+ scopeId: event.channelId,
+ channelId: event.channelId,
+ serverId: event.serverId ?? current?.serverId ?? null,
+ parentChannelId: current?.parentChannelId ?? null,
+ ordinaryUnread: true,
+ lastUnreadSeq: Math.max(current?.lastUnreadSeq ?? 0, seq),
+ lastAttentionSeq: event.isMention
+ ? Math.max(current?.lastAttentionSeq ?? 0, seq)
+ : current?.lastAttentionSeq ?? null,
+ attentionCount: (current?.attentionCount ?? 0) + (event.isMention ? 1 : 0),
+ }
+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
+ upsertRows(registry, "attentionScopes", attentionScopeSchema, (row) => row.scopeId, [next])
+ })
+ attentionProtectionState(queryClient).heldScopes.add(event.channelId)
+}
+
+export function projectAttentionMentionHint(
+ queryClient: QueryClient,
+ event: Extract<CommunityWsEvent, { type: "community:mention.create" }>,
+ evidence?: { createdAt: string },
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry || event.userId !== registry.accountId || !event.channelId) return
+ const message = collectionRows(registry, "messages", messageSchema)
+ .find((row) => row.id === event.messageId)
+ if (!message?.authorId) return
+ if (
+ message.seq !== undefined
+ && hasAttentionScopeOptimisticFence(queryClient, event.channelId, message.seq)
+ ) return
+ const id = `pending:${event.messageId}`
+ const item: AttentionItemRow = {
+ id,
+ kind: "pending",
+ sourceId: event.messageId,
+ scopeId: event.channelId,
+ messageId: event.messageId,
+ actorUserId: message.authorId,
+ createdAt: evidence?.createdAt ?? message.createdAt ?? new Date().toISOString(),
+ }
+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
+ upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, [item])
+ })
+ attentionProtectionState(queryClient).heldItems.add(id)
+}
+
+export function projectAttentionFriendEvent(
+ queryClient: QueryClient,
+ event: Extract<CommunityWsEvent, {
+ type:
+ | "community:friend.request"
+ | "community:friend.accept"
+ | "community:friend.reject"
+ | "community:friend.remove"
+ | "community:friend.block"
+ }>,
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return
+ const protection = attentionProtectionState(queryClient)
+ if (event.type === "community:friend.request") {
+ if (event.friendship.addresseeId !== registry.accountId) return
+ const item: AttentionItemRow = {
+ id: `friend_request:${event.friendship.id}`,
+ kind: "friend_request",
+ sourceId: event.friendship.id,
+ scopeId: null,
+ messageId: null,
+ actorUserId: event.friendship.requesterId,
+ createdAt: event.friendship.createdAt,
+ }
+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
+ upsertRows(registry, "attentionItems", attentionItemSchema, (row) => row.id, [item])
+ })
+ protection.heldItems.add(item.id)
+ return
+ }
+ const removed = collectionRows(registry, "attentionItems", attentionItemSchema)
+ .filter((item) => item.kind === "friend_request" && (
+ event.type === "community:friend.block"
+ ? item.actorUserId === event.userId
+ : item.sourceId === event.friendshipId
+ ))
+ .map((item) => item.id)
+ if (removed.length === 0) return
+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
+ deleteRows(
+ registry,
+ "attentionItems",
+ attentionItemSchema,
+ (item) => removed.includes(item.id),
+ )
+ })
+ for (const id of removed) protection.heldItemDeletes.add(id)
+}
+
+/**
+ * Applies low-latency WS facts directly to the canonical account-scoped
+ * collections. Existing React Query handlers still own reconciliation and
+ * fetch invalidation; a successful queryFn explicitly publishes its fresh
+ * response into the same rows after its signal and account token are checked.
+ */
+export function projectCommunityWsEventToDb(
+ queryClient: QueryClient,
+ event: CommunityWsEvent,
+) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return
+ return withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
+ switch (event.type) {
+ case "community:message.create":
+ ingestMessages(registry, event.channelId, [projectCommunityMessageCreate(event.message)])
+ if (event.message.createdAt) {
+ patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ (row) => ({ ...row, lastMessageAt: event.message.createdAt }),
+ (row) => row.id === event.channelId,
+ [event.channelId],
+ )
+ }
+ return
+ case "community:message.edited":
+ patchRows(
+ registry,
+ "messages",
+ messageSchema,
+ (row) => row.id,
+ (row) => ({ ...row, content: event.content }),
+ (row) => row.id === event.messageId,
+ [event.messageId],
+ )
+ return
+ case "community:message.updated":
+ patchRows(
+ registry,
+ "messages",
+ messageSchema,
+ (row) => row.id,
+ (row) => ({ ...row, approval: event.approval }),
+ (row) => row.id === event.messageId,
+ [event.messageId],
+ )
+ return
+ case "community:reaction.add":
+ case "community:reaction.remove":
+ patchRows(
+ registry,
+ "messages",
+ messageSchema,
+ (row) => row.id,
+ (row) => {
+ const message = row as MessageRow & Msg
+ const reactions = (message.reactions ?? []).map((reaction) => ({
+ ...reaction,
+ userIds: [...reaction.userIds],
+ }))
+ const reaction = reactions.find((candidate) => candidate.emoji === event.emoji)
+ if (event.type === "community:reaction.add") {
+ if (reaction && !reaction.userIds.includes(event.userId)) reaction.userIds.push(event.userId)
+ else if (!reaction) reactions.push({
+ emoji: event.emoji,
+ count: 1,
+ me: event.userId === registry.accountId,
+ userIds: [event.userId],
+ })
+ } else if (reaction) {
+ reaction.userIds = reaction.userIds.filter((userId) => userId !== event.userId)
+ }
+ const normalized = reactions
+ .filter((candidate) => candidate.userIds.length > 0)
+ .map((candidate) => ({
+ ...candidate,
+ count: candidate.userIds.length,
+ me: Boolean(registry.accountId && candidate.userIds.includes(registry.accountId)),
+ }))
+ return { ...row, reactions: normalized }
+ },
+ (row) => row.id === event.messageId,
+ [event.messageId],
+ )
+ return
+ case "community:channel.child_create": {
+ if (!event.parentMessageId) return
+ const parent = collectionRows(registry, "channels", channelSchema)
+ .find((row) => row.id === event.parentChannelId)
+ if (!parent?.serverId) return
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, [{
+ id: event.channel.id,
+ serverId: parent.serverId,
+ categoryId: null,
+ name: event.channel.name,
+ type: "thread",
+ parentChannelId: event.parentChannelId,
+ parentMessageId: event.parentMessageId,
+ creatorId: event.channel.creatorId ?? null,
+ position: 0,
+ archived: false,
+ muted: false,
+ unread: false,
+ tags: [],
+ pending: false,
+ lastMessageAt: event.channel.createdAt,
+ }])
+ if (registry.accountId) {
+ upsertRows(
+ registry,
+ "channelMemberships",
+ channelMembershipSchema,
+ (row) => row.id,
+ [{
+ id: channelMembershipKey(event.channel.id, registry.accountId, "access"),
+ channelId: event.channel.id,
+ userId: registry.accountId,
+ relation: "access",
+ source: "explicit",
+ }],
+ )
+ }
+ return
+ }
+ case "community:channel.child_update":
+ patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ (row) => ({
+ ...row,
+ ...(event.changes.name === undefined ? {} : { name: event.changes.name }),
+ ...(event.changes.archived === undefined ? {} : { archived: event.changes.archived }),
+ ...(event.changes.tags === undefined ? {} : { tags: event.changes.tags ?? [] }),
+ ...(event.changes.lastMessageAt === undefined ? {} : { lastMessageAt: event.changes.lastMessageAt }),
+ }),
+ (row) => row.id === event.channelId,
+ [event.channelId],
+ )
+ return
+ case "community:server.update":
+ patchRows(
+ registry,
+ "servers",
+ serverSchema,
+ (row) => row.id,
+ (row) => ({ ...row, ...event.changes }),
+ (row) => row.id === event.serverId,
+ [event.serverId],
+ )
+ return
+ case "community:server.delete":
+ purgeCommunityServer(registry, event.serverId)
+ return
+ case "community:channel.create":
+ upsertRows(registry, "channels", channelSchema, (row) => row.id, [{
+ id: event.channel.id,
+ serverId: event.serverId,
+ categoryId: event.channel.categoryId ?? null,
+ name: event.channel.name,
+ type: event.channel.type,
+ parentChannelId: null,
+ parentMessageId: null,
+ creatorId: null,
+ position: event.channel.position,
+ archived: false,
+ muted: false,
+ unread: false,
+ tags: [],
+ pending: false,
+ lastMessageAt: event.channel.createdAt,
+ }])
+ return
+ case "community:channel.update":
+ patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ (row) => ({ ...row, ...event.changes }),
+ (row) => row.id === event.channelId,
+ [event.channelId],
+ )
+ return
+ case "community:channel.delete":
+ purgeCommunityChannel(registry, event.channelId)
+ return
+ case "community:channel.reorder": {
+ const positionById = new Map(event.channels.map((row) => [row.id, row.position]))
+ patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ (row) => ({ ...row, position: positionById.get(row.id) ?? row.position }),
+ (row) => row.serverId === event.serverId && positionById.has(row.id),
+ positionById.keys(),
+ )
+ return
+ }
+ case "community:channel.member_add":
+ case "community:channel.member_remove":
+ // Relation ownership depends on resolved channel type. The membership
+ // handler publishes this only after canonical metadata proves whether
+ // the event changes thread notify or top-level access.
+ return
+ case "community:category.create":
+ upsertRows(registry, "categories", categorySchema, (row) => row.id, [{
+ id: event.category.id,
+ serverId: event.serverId,
+ name: event.category.name,
+ position: event.category.position,
+ private: event.category.private,
+ pending: false,
+ }])
+ return
+ case "community:category.update":
+ patchRows(
+ registry,
+ "categories",
+ categorySchema,
+ (row) => row.id,
+ (row) => ({ ...row, ...event.changes }),
+ (row) => row.id === event.categoryId,
+ [event.categoryId],
+ )
+ return
+ case "community:category.delete":
+ deleteRows(
+ registry,
+ "categories",
+ categorySchema,
+ (row) => row.id === event.categoryId,
+ [event.categoryId],
+ )
+ return
+ case "community:category.reorder": {
+ const positionById = new Map(event.categories.map((row) => [row.id, row.position]))
+ patchRows(
+ registry,
+ "categories",
+ categorySchema,
+ (row) => row.id,
+ (row) => ({ ...row, position: positionById.get(row.id) ?? row.position }),
+ (row) => row.serverId === event.serverId && positionById.has(row.id),
+ positionById.keys(),
+ )
+ return
+ }
+ case "community:member.join":
+ upsertRows(registry, "serverMemberships", serverMembershipSchema, (row) => row.id, [{
+ id: serverMembershipKey(event.serverId, event.member.userId),
+ serverId: event.serverId,
+ userId: event.member.userId,
+ memberId: event.member.id,
+ role: event.member.role,
+ joinedAt: event.member.joinedAt,
+ viewer: event.member.userId === registry.accountId,
+ }])
+ writeCommunityProfilePatches([communityUserProfilePatch(event.member.userId, {
+ name: event.member.name,
+ discriminator: event.member.discriminator,
+ avatar: event.member.avatar ?? "",
+ avatarVersion: event.member.avatarVersion,
+ })], registry, { event: true })
+ return
+ case "community:member.leave":
+ if (event.userId === registry.accountId) {
+ purgeCommunityServer(registry, event.serverId)
+ } else {
+ deleteRows(
+ registry,
+ "serverMemberships",
+ serverMembershipSchema,
+ (row) => row.serverId === event.serverId && row.userId === event.userId,
+ )
+ }
+ return
+ case "community:member.update":
+ patchRows(
+ registry,
+ "serverMemberships",
+ serverMembershipSchema,
+ (row) => row.id,
+ (row) => ({ ...row, ...event.changes }),
+ (row) => row.serverId === event.serverId
+ && (row.memberId === event.memberId || Boolean(event.userId && row.userId === event.userId)),
+ )
+ return
+ case "community:unread.bump":
+ if (event.userId !== registry.accountId) return
+ patchRows(
+ registry,
+ "channels",
+ channelSchema,
+ (row) => row.id,
+ (row) => ({ ...row, unread: true }),
+ (row) => row.id === event.channelId || row.id === event.railChannelId,
+ [event.channelId, event.railChannelId]
+ .filter((channelId): channelId is string => Boolean(channelId)),
+ )
+ if (event.serverId) {
+ patchRows(
+ registry,
+ "servers",
+ serverSchema,
+ (row) => row.id,
+ (row) => ({
+ ...row,
+ unread: true,
+ mentions: row.mentions + (event.isMention ? 1 : 0),
+ }),
+ (row) => row.id === event.serverId,
+ [event.serverId],
+ )
+ }
+ return
+ case "community:status.update":
+ projectProfilePatch(registry, event.userId, {
+ status: {
+ statusEmoji: event.statusEmoji,
+ statusText: event.statusText,
+ },
+ })
+ return
+ case "community:identity.update":
+ projectProfilePatch(registry, event.userId, {
+ avatar: {
+ avatar: event.avatar,
+ avatarVersion: event.avatarVersion,
+ },
+ })
+ return
+ case "community:profile.update": {
+ projectProfilePatch(registry, event.userId, {
+ identityAbout: {
+ name: event.name,
+ discriminator: event.discriminator,
+ aboutMe: event.aboutMe,
+ bannerColor: event.bannerColor,
+ kind: event.kind,
+ ownerUserId: event.ownerUserId,
+ },
+ })
+ return
+ }
+ default:
+ return
+ }
+ })
+}
+
+export function installCommunityDbSync(
+ queryClient: QueryClient,
+ registry: CommunityDbRegistry,
+) {
+ // Canonical collections hydrate themselves. Raw Query payloads are never
+ // replayed into DB: a cache notification does not prove request freshness.
+ void queryClient
+ void registry.preload()
+ return () => {}
+}
diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.ts
index 1adb8116f..1c19ef512 100644
--- a/src/web/src/lib/community/channel-ref.ts
+++ b/src/web/src/lib/community/channel-ref.ts
@@ -9,7 +9,11 @@ import { parseNameAndTag, parseRef } from "@alook/shared"
* This file is used by `/c` UI only. Real-server segments still obey the
* public ref contract and require a name#discriminator handle.
*/
-type ChannelRefDirectoryChannel = { id: string; name: string }
+type ChannelRefDirectoryChannel = {
+ id: string
+ name: string
+ type?: "text" | "forum"
+}
export type ChannelRefDirectoryServer = {
id: string
name: string
diff --git a/src/web/src/lib/community/chat-syntax-plugin.test.ts b/src/web/src/lib/community/chat-syntax-plugin.test.ts
index 98bd03377..c816dadee 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.test.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.test.ts
@@ -127,8 +127,8 @@ describe("chatSyntaxPlugin — mention", () => {
})
it("does NOT treat @here as a mention — it was removed, renders as plain text", () => {
- // @here was removed as a broadcast trigger (plans/remove-here-mention.md,
- // option b). A literal @here is no longer a mention node; it stays text
+ // @here was removed as a broadcast trigger. A literal @here is no longer a
+ // mention node; it stays text
// (incl. historical messages — no legacy rendering).
const children = paragraphChildren(parse("@here ping"))
expect(children.some((c) => c.type === "mention")).toBe(false)
diff --git a/src/web/src/lib/community/chat-syntax-plugin.ts b/src/web/src/lib/community/chat-syntax-plugin.ts
index 2cdff315b..e891fa0a4 100644
--- a/src/web/src/lib/community/chat-syntax-plugin.ts
+++ b/src/web/src/lib/community/chat-syntax-plugin.ts
@@ -21,8 +21,7 @@ import type { SpoilerNode } from "./spoiler-syntax"
// in `spoiler-syntax.ts`.
// Matches a `/server#disc/channel`, `/server#disc/channel/#N` (thread), or
-// `/server#disc/channel/#N#M` (thread reply,
-// see plans/agent-thread-emoji-react.md) ref — the CLI's path grammar
+// `/server#disc/channel/#N#M` thread-reply ref — the CLI's path grammar
// (`parseRef`/`formatRef` in `community-cli-contract.ts`). Segment charset
// `[^\s/#.,;:!?)\]]+` = "any char slugify can emit, minus the terminator
// punctuation": server names travel with their required discriminator and
@@ -106,13 +105,13 @@ const SERVER_REF_RE = new RegExp(`(?<=^|\\s)/${HANDLE_SEG}(?=\\s|$|[${REF_TERM}]
// disambiguation: the prefix-anchored full-path form can't collide with a bare
// `#`, so no ordering hazard with mentions/spoilers/other `#` syntax.)
-// Two-branch mention grammar (see plans/mandatory-mention-discriminator.md):
+// Two-branch mention grammar:
//
// 1. The literal `@everyone` token, with a trailing `(?![\p{L}\p{N}_-])`
// boundary guard so `@everyoneee` is NOT matched as `@everyone` — this MUST
// agree with `detectMentionType`'s boundary check (mention-extension.ts)
-// and `community-mentions.ts`'s `ID_CHAR_RE`. (`@here` was removed as a
-// broadcast trigger — see plans/remove-here-mention.md; a literal `@here`
+// and `community-mentions.ts`'s `ID_CHAR_RE`. `@here` was removed as a
+// broadcast trigger; a literal `@here`
// now falls through as ordinary text, matching option b: no legacy
// rendering for historical `@here`.)
//
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
index f82f35fa8..4cacb3d34 100644
--- a/src/web/src/lib/community/community-route.test.ts
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -190,6 +190,24 @@ describe("community route", () => {
})
})
+ it("preserves a known target conversation subtype in the pending checkpoint", () => {
+ const committedFrame = {
+ ...normalizeCommunityHref("/c/channels/s1/c1"),
+ revision: 4,
+ }
+ expect(resolveCommunityCheckpointPlan({
+ committedFrame,
+ targetHref: "/c/channels/s1/c2",
+ pending: true,
+ targetReady: true,
+ targetConversationSubtype: "forum",
+ }).main).toEqual({
+ kind: "target-skeleton",
+ href: "/c/channels/s1/c2",
+ conversationSubtype: "forum",
+ })
+ })
+
it("keeps committed A as the source after the router publishes B", () => {
const committedFrame = {
...normalizeCommunityHref("/c/channels/s1/c1"),
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
index f8365677a..630d068e9 100644
--- a/src/web/src/lib/community/community-route.ts
+++ b/src/web/src/lib/community/community-route.ts
@@ -70,7 +70,11 @@ export type CommunityCheckpointPlan = {
| { kind: "keep" }
| { kind: "server-skeleton"; serverId: string }
| { kind: "me-skeleton" }
- main: { kind: "keep" } | { kind: "target-skeleton"; href: string }
+ main: { kind: "keep" } | {
+ kind: "target-skeleton"
+ href: string
+ conversationSubtype?: "text" | "forum" | "thread"
+ }
}
export function communityServerId(href: string): string | null {
@@ -283,11 +287,13 @@ export function resolveCommunityCheckpointPlan({
targetHref,
pending,
targetReady,
+ targetConversationSubtype,
}: {
committedFrame: CommunityCommittedFrame
targetHref: string | null
pending: boolean
targetReady: boolean
+ targetConversationSubtype?: "text" | "forum" | "thread"
}): CommunityCheckpointPlan {
if (!pending || !targetHref) {
return committedPlan(committedFrame)
@@ -308,7 +314,11 @@ export function resolveCommunityCheckpointPlan({
rail: { kind: "keep" },
sidebar: { kind: "keep" },
main: isConversationTarget
- ? { kind: "target-skeleton", href: target.href }
+ ? {
+ kind: "target-skeleton",
+ href: target.href,
+ ...(targetConversationSubtype ? { conversationSubtype: targetConversationSubtype } : {}),
+ }
: { kind: "keep" },
}
}
@@ -319,7 +329,11 @@ export function resolveCommunityCheckpointPlan({
mode: "warm-scope",
surface: target.surface,
main: isConversationTarget
- ? { kind: "target-skeleton", href: target.href }
+ ? {
+ kind: "target-skeleton",
+ href: target.href,
+ ...(targetConversationSubtype ? { conversationSubtype: targetConversationSubtype } : {}),
+ }
: { kind: "keep" },
}
}
@@ -336,7 +350,11 @@ export function resolveCommunityCheckpointPlan({
targetHref: target.href,
rail,
sidebar,
- main: { kind: "target-skeleton", href: target.href },
+ main: {
+ kind: "target-skeleton",
+ href: target.href,
+ ...(targetConversationSubtype ? { conversationSubtype: targetConversationSubtype } : {}),
+ },
}
}
diff --git a/src/web/src/lib/community/conversation-subtype.test.ts b/src/web/src/lib/community/conversation-subtype.test.ts
index 0a44c8da2..151d43176 100644
--- a/src/web/src/lib/community/conversation-subtype.test.ts
+++ b/src/web/src/lib/community/conversation-subtype.test.ts
@@ -6,7 +6,7 @@ describe("resolveConversationSubtype", () => {
["pending", true],
["terminal-error", true],
["ready", false],
- ] as const)("keeps stale or unproved metadata neutral: %s / access=%s", (routeLifecycle, accessAllowed) => {
+ ] as const)("keeps metadata neutral only when no structural hint exists: %s / access=%s", (routeLifecycle, accessAllowed) => {
expect(resolveConversationSubtype({
routeLifecycle,
accessAllowed,
@@ -29,7 +29,7 @@ describe("resolveConversationSubtype", () => {
})
it.each(["text", "forum", "thread"] as const)(
- "uses the persisted %s subtype only for a pending skeleton",
+ "uses the persisted %s subtype for every non-content skeleton state",
(structuralHint) => {
expect(resolveConversationSubtype({
routeLifecycle: "pending",
@@ -39,13 +39,18 @@ describe("resolveConversationSubtype", () => {
structuralHint,
})).toBe(structuralHint)
- expect(resolveConversationSubtype({
- routeLifecycle: "terminal-error",
- accessAllowed: true,
- isChild: false,
- isForum: false,
- structuralHint,
- })).toBe("unknown")
+ for (const [routeLifecycle, accessAllowed] of [
+ ["terminal-error", true],
+ ["ready", false],
+ ] as const) {
+ expect(resolveConversationSubtype({
+ routeLifecycle,
+ accessAllowed,
+ isChild: false,
+ isForum: false,
+ structuralHint,
+ })).toBe(structuralHint)
+ }
},
)
})
diff --git a/src/web/src/lib/community/conversation-subtype.ts b/src/web/src/lib/community/conversation-subtype.ts
index 23224e094..6b6bafdf5 100644
--- a/src/web/src/lib/community/conversation-subtype.ts
+++ b/src/web/src/lib/community/conversation-subtype.ts
@@ -17,8 +17,7 @@ export function resolveConversationSubtype({
isForum: boolean
structuralHint?: ConversationSubtype
}): ConversationSubtype {
- if (routeLifecycle === "pending") return structuralHint
- if (routeLifecycle !== "ready" || !accessAllowed) return "unknown"
+ if (routeLifecycle !== "ready" || !accessAllowed) return structuralHint
if (isChild) return "thread"
return isForum ? "forum" : "text"
}
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 734ca8607..ceeeb5726 100644
--- a/src/web/src/lib/community/desktop-system-notification.test.ts
+++ b/src/web/src/lib/community/desktop-system-notification.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest"
import type { CommunityMessageCreate, CommunityWsEvent } from "@alook/shared"
import { QueryClient } from "@tanstack/react-query"
-import type { StructuralSnapshotV1 } from "./structural-snapshot"
+import { communityKeys } from "@/lib/query-keys"
import {
buildDesktopSystemNotificationCandidate,
dismissDesktopSystemNotification,
@@ -48,27 +48,69 @@ const bump: UnreadBump = {
channelId: "channel_1",
serverId: "server_1",
}
-const snapshot: StructuralSnapshotV1 = {
- schemaVersion: 1,
- accountId: "viewer_1",
- capturedAt: 1,
- serverOrder: ["server_1"],
- folders: [],
- servers: [{
+const serverRows = [{
id: "server_1",
name: "Studio",
discriminator: "0042",
+ description: "",
+ ownerId: "owner_1",
icon: null,
- categories: [],
- channels: [{ id: "channel_1", name: "general", type: "text", categoryId: null }],
- childRouteHints: [{
- id: "thread_1",
- name: "Release notes",
- type: "thread",
- parentChannelId: "channel_1",
- parentMessageId: "message_0",
- }],
- }],
+ official: false,
+ isOwner: false,
+ unread: false,
+ mentions: 0,
+}]
+const channelRows = [
+ {
+ id: "channel_1",
+ serverId: "server_1",
+ categoryId: null,
+ name: "general",
+ type: "text" as const,
+ parentChannelId: null,
+ parentMessageId: null,
+ creatorId: null,
+ position: 0,
+ archived: false,
+ muted: false,
+ unread: false,
+ tags: [],
+ pending: false,
+ lastMessageAt: null,
+ },
+ {
+ id: "thread_1",
+ serverId: "server_1",
+ categoryId: null,
+ name: "Release notes",
+ type: "thread" as const,
+ parentChannelId: "channel_1",
+ parentMessageId: "message_0",
+ creatorId: "author_1",
+ position: 0,
+ archived: false,
+ muted: false,
+ unread: false,
+ tags: [],
+ pending: false,
+ lastMessageAt: null,
+ },
+]
+
+function seedCanonicalDirectory(
+ queryClient: QueryClient,
+ options: { channels?: boolean } = {},
+) {
+ queryClient.setQueryData(
+ communityKeys.communityDbCollection("viewer_1", "servers"),
+ serverRows,
+ )
+ if (options.channels !== false) {
+ queryClient.setQueryData(
+ communityKeys.communityDbCollection("viewer_1", "channels"),
+ channelRows,
+ )
+ }
}
afterEach(() => {
@@ -79,7 +121,11 @@ afterEach(() => {
describe("desktop system notification candidates", () => {
it("derives a hygienic server notification from one paired bundle", () => {
- expect(buildDesktopSystemNotificationCandidate(create, bump, "viewer_1", snapshot)).toEqual({
+ expect(buildDesktopSystemNotificationCandidate(create, bump, "viewer_1", {
+ conversationKind: "channel",
+ serverName: "Studio",
+ channelName: "general",
+ })).toEqual({
viewerUserId: "viewer_1",
title: "Studio · #general",
body: "Ada: Hello there",
@@ -97,26 +143,44 @@ describe("desktop system notification candidates", () => {
expect(buildDesktopSystemNotificationCandidate({
...create,
channelId: "thread_1",
- }, { ...bump, channelId: "thread_1" }, "viewer_1", snapshot)).toMatchObject({
+ }, { ...bump, channelId: "thread_1" }, "viewer_1", {
+ conversationKind: "thread",
+ serverName: "Studio",
+ channelName: "Release notes",
+ parentChannelName: "general",
+ })).toMatchObject({
title: "Studio · #general · Release notes",
body: "Ada: Hello there",
})
})
- it("does not reuse conversation names from another account's snapshot", () => {
+ it("uses neutral copy when no account-scoped collection row is available", () => {
expect(buildDesktopSystemNotificationCandidate(
create,
bump,
"viewer_1",
- { ...snapshot, accountId: "other" },
+ null,
)).toMatchObject({
title: "Server · #Channel",
body: "Ada: Hello there",
})
})
+ it("does not resolve account-scoped metadata without a viewer", async () => {
+ const queryClient = new QueryClient()
+
+ await expect(resolveDesktopSystemNotificationCandidate(
+ create,
+ bump,
+ null,
+ queryClient,
+ )).resolves.toBeNull()
+ expect(channelMetadataMocks.fetch).not.toHaveBeenCalled()
+ })
+
it("resolves a cold channel name before formatting the desktop copy", async () => {
const queryClient = new QueryClient()
+ seedCanonicalDirectory(queryClient, { channels: false })
channelMetadataMocks.fetch.mockResolvedValue({
id: "channel_1",
serverId: "server_1",
@@ -129,21 +193,11 @@ describe("desktop system notification candidates", () => {
lastMessageAt: null,
createdAt: "2026-09-12T00:00:00.000Z",
})
- const coldSnapshot = {
- ...snapshot,
- servers: snapshot.servers.map((server) => ({
- ...server,
- channels: [],
- childRouteHints: [],
- })),
- }
-
await expect(resolveDesktopSystemNotificationCandidate(
create,
bump,
"viewer_1",
queryClient,
- coldSnapshot,
)).resolves.toMatchObject({
title: "Studio · #general",
body: "Ada: Hello there",
@@ -180,6 +234,7 @@ describe("desktop system notification candidates", () => {
it("resolves cold thread and parent channel names before formatting the desktop copy", async () => {
const queryClient = new QueryClient()
+ seedCanonicalDirectory(queryClient, { channels: false })
channelMetadataMocks.fetch.mockResolvedValueOnce({
id: "thread_1",
serverId: "server_1",
@@ -203,21 +258,11 @@ describe("desktop system notification candidates", () => {
lastMessageAt: null,
createdAt: "2026-09-12T00:00:00.000Z",
})
- const coldSnapshot = {
- ...snapshot,
- servers: snapshot.servers.map((server) => ({
- ...server,
- channels: [],
- childRouteHints: [],
- })),
- }
-
await expect(resolveDesktopSystemNotificationCandidate(
{ ...create, channelId: "thread_1" },
{ ...bump, channelId: "thread_1" },
"viewer_1",
queryClient,
- coldSnapshot,
)).resolves.toMatchObject({
title: "Studio · #general · Release notes",
body: "Ada: Hello there",
@@ -228,32 +273,39 @@ describe("desktop system notification candidates", () => {
])
})
- it("uses the complete current-account snapshot without metadata I/O", async () => {
+ it("uses complete current-account collections without metadata I/O", async () => {
+ const queryClient = new QueryClient()
+ seedCanonicalDirectory(queryClient)
await expect(resolveDesktopSystemNotificationCandidate(
create,
bump,
"viewer_1",
- new QueryClient(),
- snapshot,
+ queryClient,
)).resolves.toMatchObject({
title: "Studio · #general",
body: "Ada: Hello there",
})
expect(channelMetadataMocks.fetch).not.toHaveBeenCalled()
+
+ await expect(resolveDesktopSystemNotificationCandidate(
+ { ...create, channelId: "thread_1" },
+ { ...bump, channelId: "thread_1" },
+ "viewer_1",
+ queryClient,
+ )).resolves.toMatchObject({
+ title: "Studio · #general · Release notes",
+ })
})
it("keeps safe fallback copy when cold metadata resolution fails", async () => {
+ const queryClient = new QueryClient()
+ seedCanonicalDirectory(queryClient, { channels: false })
channelMetadataMocks.fetch.mockRejectedValue(new Error("metadata unavailable"))
await expect(resolveDesktopSystemNotificationCandidate(
create,
bump,
"viewer_1",
- new QueryClient(),
- { ...snapshot, servers: snapshot.servers.map((server) => ({
- ...server,
- channels: [],
- childRouteHints: [],
- })) },
+ queryClient,
)).resolves.toMatchObject({
title: "Studio · #Channel",
body: "Ada: Hello there",
diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.ts
index 75c1f1c44..9784a8f47 100644
--- a/src/web/src/lib/community/desktop-system-notification.ts
+++ b/src/web/src/lib/community/desktop-system-notification.ts
@@ -8,7 +8,7 @@ import {
import type { QueryClient } from "@tanstack/react-query"
import { fetchChannelMetadata, type ChannelMetadata } from "@/hooks/community/channel-metadata"
import { communityKeys } from "@/lib/query-keys"
-import type { StructuralSnapshotV1 } from "./structural-snapshot"
+import type { ChannelRow, ServerRow } from "@/lib/community-db/schema"
import {
parseDesktopSystemNotificationActivation,
type DesktopSystemNotificationActivation,
@@ -31,24 +31,27 @@ type DesktopSystemNotificationConversation = {
parentChannelName?: string | null
}
-function snapshotConversation(
+function collectionConversation(
create: CommunityMessageCreate,
viewerUserId: string,
- snapshot: StructuralSnapshotV1 | null,
+ queryClient: QueryClient,
): DesktopSystemNotificationConversation | null {
if (!create.serverId) return null
- const server = snapshot?.accountId === viewerUserId
- ? snapshot.servers.find((entry) => entry.id === create.serverId)
- : undefined
- const child = server?.childRouteHints.find((entry) => entry.id === create.channelId)
- const channel = server?.channels.find((entry) => entry.id === create.channelId)
- const parent = child
- ? server?.channels.find((entry) => entry.id === child.parentChannelId)
+ const servers = queryClient.getQueryData<ServerRow[]>(
+ communityKeys.communityDbCollection(viewerUserId, "servers"),
+ ) ?? []
+ const channels = queryClient.getQueryData<ChannelRow[]>(
+ communityKeys.communityDbCollection(viewerUserId, "channels"),
+ ) ?? []
+ const server = servers.find((entry) => entry.id === create.serverId)
+ const channel = channels.find((entry) => entry.id === create.channelId)
+ const parent = channel?.parentChannelId
+ ? channels.find((entry) => entry.id === channel.parentChannelId)
: undefined
return {
- conversationKind: child ? "thread" : "channel",
+ conversationKind: channel?.type === "thread" ? "thread" : "channel",
serverName: server?.name,
- channelName: child?.name ?? channel?.name,
+ channelName: channel?.name,
parentChannelName: parent?.name,
}
}
@@ -57,8 +60,7 @@ export function buildDesktopSystemNotificationCandidate(
create: CommunityMessageCreate,
bump: CommunityUnreadBump,
viewerUserId: string | null,
- snapshot: StructuralSnapshotV1 | null = null,
- resolvedConversation: DesktopSystemNotificationConversation | null = null,
+ conversation: DesktopSystemNotificationConversation | null = null,
): DesktopSystemNotificationCandidate | null {
if (!viewerUserId || bump.userId !== viewerUserId) return null
if (create.channelId !== bump.channelId || create.serverId !== bump.serverId) return null
@@ -78,7 +80,6 @@ export function buildDesktopSystemNotificationCandidate(
messageId: create.message.id,
seq: create.message.seq,
}
- const conversation = resolvedConversation ?? snapshotConversation(create, viewerUserId, snapshot)
const copy = buildCommunityNotificationCopy({
conversationKind: create.serverId ? conversation?.conversationKind ?? "channel" : "dm",
authorName: create.message.authorName,
@@ -101,12 +102,13 @@ export async function resolveDesktopSystemNotificationCandidate(
bump: CommunityUnreadBump,
viewerUserId: string | null,
queryClient: QueryClient,
- snapshot: StructuralSnapshotV1 | null = null,
): Promise<DesktopSystemNotificationCandidate | null> {
- const fallback = buildDesktopSystemNotificationCandidate(create, bump, viewerUserId, snapshot)
+ const cached = viewerUserId
+ ? collectionConversation(create, viewerUserId, queryClient)
+ : null
+ const fallback = buildDesktopSystemNotificationCandidate(create, bump, viewerUserId, cached)
if (!fallback || !viewerUserId || !create.serverId) return fallback
- const cached = snapshotConversation(create, viewerUserId, snapshot)
if (
cached?.channelName
&& (cached.conversationKind !== "thread" || cached.parentChannelName)
@@ -126,7 +128,7 @@ export async function resolveDesktopSystemNotificationCandidate(
}) as ChannelMetadata
: null
- return buildDesktopSystemNotificationCandidate(create, bump, viewerUserId, snapshot, {
+ return buildDesktopSystemNotificationCandidate(create, bump, viewerUserId, {
conversationKind: channel.parentChannelId ? "thread" : "channel",
serverName: cached?.serverName,
channelName: channel.name,
diff --git a/src/web/src/lib/community/display-name.test.ts b/src/web/src/lib/community/display-name.test.ts
index c044876be..4c9496328 100644
--- a/src/web/src/lib/community/display-name.test.ts
+++ b/src/web/src/lib/community/display-name.test.ts
@@ -28,17 +28,17 @@ describe("displayName", () => {
expect(displayName({ email: "[email protected]" })).toBe("dave")
})
- it("returns 'Unknown member' when neither name nor email is present", () => {
- expect(displayName({})).toBe("Unknown member")
- expect(displayName(null)).toBe("Unknown member")
- expect(displayName(undefined)).toBe("Unknown member")
- expect(displayName({ name: null, email: null })).toBe("Unknown member")
+ it("returns 'Member unavailable' when neither name nor email is present", () => {
+ expect(displayName({})).toBe("Member unavailable")
+ expect(displayName(null)).toBe("Member unavailable")
+ expect(displayName(undefined)).toBe("Member unavailable")
+ expect(displayName({ name: null, email: null })).toBe("Member unavailable")
})
it("never returns a raw id", () => {
const id = "user_abc123"
expect(displayName({ name: "", email: "" })).not.toBe(id)
- expect(displayName({})).toBe("Unknown member")
+ expect(displayName({})).toBe("Member unavailable")
})
})
@@ -56,9 +56,9 @@ describe("makeUserNameResolver", () => {
expect(resolve("u3")).toBe("Carol")
})
- it("returns 'Unknown member' (not the id) for an unknown user", () => {
+ it("returns 'Member unavailable' (not the id) for an unavailable user", () => {
const resolve = makeUserNameResolver(list)
- expect(resolve("missing")).toBe("Unknown member")
+ expect(resolve("missing")).toBe("Member unavailable")
expect(resolve("missing")).not.toBe("missing")
})
})
@@ -67,7 +67,7 @@ describe("reaction tooltip resolution", () => {
// Reaction tooltips resolve reactor ids through makeUserNameResolver over the
// combined members + friends set. A reactor that arrived only over the WS
// event (id, no name) and is absent from the loaded set must fall back to
- // "Unknown member" — never the raw user id.
+ // "Member unavailable" — never the raw user id.
const roster = [
{ userId: "member_1", name: "Alice" },
{ userId: "friend_1", name: "", email: "[email protected]" },
@@ -79,10 +79,10 @@ describe("reaction tooltip resolution", () => {
expect(resolve("friend_1")).toBe("bob")
})
- it("resolves a live-WS reactor absent from the loaded set to 'Unknown member', never the id", () => {
+ it("resolves a live-WS reactor absent from the loaded set to 'Member unavailable', never the id", () => {
const resolve = makeUserNameResolver(roster)
const liveOnlyReactorId = "user_live_only_99"
- expect(resolve(liveOnlyReactorId)).toBe("Unknown member")
+ expect(resolve(liveOnlyReactorId)).toBe("Member unavailable")
expect(resolve(liveOnlyReactorId)).not.toBe(liveOnlyReactorId)
})
})
diff --git a/src/web/src/lib/community/display-name.ts b/src/web/src/lib/community/display-name.ts
index 51f4c5bb7..80f0a221d 100644
--- a/src/web/src/lib/community/display-name.ts
+++ b/src/web/src/lib/community/display-name.ts
@@ -1,4 +1,4 @@
-const UNKNOWN_MEMBER = "Unknown member"
+const UNAVAILABLE_MEMBER = "Member unavailable"
export function emailPrefix(email?: string | null): string {
return email?.split("@")[0]?.trim() ?? ""
@@ -12,7 +12,7 @@ export function displayName(user?: {
if (name) return name
const prefix = emailPrefix(user?.email)
if (prefix) return prefix
- return UNKNOWN_MEMBER
+ return UNAVAILABLE_MEMBER
}
export function makeUserNameResolver(
@@ -25,7 +25,7 @@ export function makeUserNameResolver(
): (userId: string) => string {
return (userId: string) => {
const row = list.find((r) => (r.userId ?? r.id) === userId)
- if (!row) return UNKNOWN_MEMBER
+ if (!row) return UNAVAILABLE_MEMBER
return displayName(row)
}
}
diff --git a/src/web/src/lib/community/eject-server.test.ts b/src/web/src/lib/community/eject-server.test.ts
index 58a24c588..5cd77658b 100644
--- a/src/web/src/lib/community/eject-server.test.ts
+++ b/src/web/src/lib/community/eject-server.test.ts
@@ -9,6 +9,7 @@ import {
consumeVoluntaryLeave,
createOwnerServerDeleteRouteToken,
isDefinitiveChildMetaFailure,
+ isOwnerServerDeleteMeRootLanding,
isOwnerServerDeleteCompleted,
isOwnerServerDeleteRouteProtected,
isOwnerServerDeleteScopeEvictionBlocked,
@@ -62,6 +63,20 @@ describe("owner-delete single-navigation lifecycle", () => {
beforeEach(() => {
cancelOwnerServerDelete(serverId)
+ observeOwnerServerDeleteRouteCommit("/c/me/friends")
+ })
+
+ it("keeps an explicit root landing terminal until a different route commits", () => {
+ const origin = createOwnerServerDeleteRouteToken()
+ beginOwnerServerDelete(serverId, origin)
+ expect(commitOwnerServerDelete(serverId, origin)).toBe(false)
+ expect(claimOwnerServerDeleteNavigation(serverId, origin, "/c/me")).toBe(true)
+ expect(isOwnerServerDeleteMeRootLanding()).toBe(true)
+
+ expect(observeOwnerServerDeleteRouteCommit("/c/me")).toEqual([serverId])
+ expect(isOwnerServerDeleteMeRootLanding()).toBe(true)
+ observeOwnerServerDeleteRouteCommit("/c/me/friends")
+ expect(isOwnerServerDeleteMeRootLanding()).toBe(false)
})
it("claims exactly one survivor navigation while the deleted route is committed", () => {
diff --git a/src/web/src/lib/community/eject-server.ts b/src/web/src/lib/community/eject-server.ts
index 14b0f2e3f..93677a21c 100644
--- a/src/web/src/lib/community/eject-server.ts
+++ b/src/web/src/lib/community/eject-server.ts
@@ -38,6 +38,24 @@ type OwnerServerDeleteState = {
type OwnerServerDeleteWindow = Window & {
__alookOwnerServerDeleteStateV8?: OwnerServerDeleteState
+ __alookOwnerServerDeleteMeRootLandingV1?: boolean
+}
+
+let ownerServerDeleteMeRootLandingFallback = false
+
+function setOwnerServerDeleteMeRootLanding(value: boolean): void {
+ if (typeof window === "undefined") {
+ ownerServerDeleteMeRootLandingFallback = value
+ return
+ }
+ ;(window as OwnerServerDeleteWindow).__alookOwnerServerDeleteMeRootLandingV1 = value
+}
+
+export function isOwnerServerDeleteMeRootLanding(): boolean {
+ if (typeof window === "undefined") return ownerServerDeleteMeRootLandingFallback
+ return Boolean(
+ (window as OwnerServerDeleteWindow).__alookOwnerServerDeleteMeRootLandingV1,
+ )
}
const ownerServerDeleteFallback: OwnerServerDeleteState = {
@@ -100,6 +118,7 @@ export function beginOwnerServerDelete(
if (current.scopes === "retained") current.participantTokens.add(originToken)
return
}
+ setOwnerServerDeleteMeRootLanding(false)
state.flushedServerIds.delete(serverId)
state.transactions.set(serverId, {
serverId,
@@ -150,6 +169,7 @@ export function claimOwnerServerDeleteNavigation(
record.request = "navigating"
record.targetHref = targetHref
record.navigationIssued = true
+ setOwnerServerDeleteMeRootLanding(targetHref === "/c/me")
return true
}
@@ -172,6 +192,7 @@ export function isOwnerServerDeleteCompleted(serverId: string): boolean {
}
export function observeOwnerServerDeleteRouteCommit(committedHref: string): string[] {
+ if (committedHref !== "/c/me") setOwnerServerDeleteMeRootLanding(false)
const state = ownerServerDeleteState()
for (const record of state.transactions.values()) {
record.lastCommittedHref = committedHref
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index 0211bb4ea..a6528753e 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -7,7 +7,7 @@ import { canonicalUserImage } from "@/lib/community/storage"
// Message enrichment shared by the channel messages route, the channel
// bootstrap route, and the DM messages route (previously three near-identical
-// copies — see plans/community-switch-perf-optimization.md WS2). Attaches
+// copies). Attaches
// attachments, reactions, reply-target previews, `latestSeq`, and — for
// non-DM channel scope only — child-channel thread indicators.
//
diff --git a/src/web/src/lib/community/highlight-range.ts b/src/web/src/lib/community/highlight-range.ts
index 2ba387c49..e4c0c4f70 100644
--- a/src/web/src/lib/community/highlight-range.ts
+++ b/src/web/src/lib/community/highlight-range.ts
@@ -1,4 +1,4 @@
-// Drag-to-highlight for the share card (plans/share-card-drag-highlight.md).
+// Drag-to-highlight for the share card.
//
// The card body is Streamdown-rendered rich markdown — a DOM tree of
// <p>/<strong>/<em>/<a>/… A user's text selection can span multiple elements,
diff --git a/src/web/src/lib/community/mention-extension.test.ts b/src/web/src/lib/community/mention-extension.test.ts
index 074fcd3b0..4ec347ebe 100644
--- a/src/web/src/lib/community/mention-extension.test.ts
+++ b/src/web/src/lib/community/mention-extension.test.ts
@@ -31,7 +31,7 @@ describe("rankMentionItems", () => {
]
it("puts everyone at the top in channel context with empty query", () => {
- // @here was removed (plans/remove-here-mention.md) — @everyone is the only
+ // @here was removed; @everyone is the only
// virtual mention item now.
const items = rankMentionItems(roster, "channel", "")
expect(items[0].id).toBe("everyone")
@@ -627,7 +627,7 @@ describe("detectMentionType", () => {
})
it("does NOT detect @here — it was removed as a broadcast trigger", () => {
- // plans/remove-here-mention.md: @here is no longer a mention type.
+ // @here is no longer a mention type.
expect(detectMentionType("ping @here please")).toBe(undefined)
})
diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.ts
index 6bad36027..63af21a33 100644
--- a/src/web/src/lib/community/mention-extension.ts
+++ b/src/web/src/lib/community/mention-extension.ts
@@ -60,8 +60,8 @@ export function rankMentionItems(
// Every member mention is serialized with its `#dddd` discriminator (via
// `renderText`), so each pill resolves to the EXACT user — no name-collision
- // ambiguity, and the trailing tag lets the display parser accept spaced names
- // (see plans/mandatory-mention-discriminator.md). A member with no
+ // ambiguity, and the trailing tag lets the display parser accept spaced names.
+ // A member with no
// discriminator can't produce a valid mention token, so it is filtered OUT of
// the popup entirely — the user physically can't pick an unmentionable member
// and get an inert, non-notifying dud. This is a should-never-happen guard
@@ -251,8 +251,7 @@ export function buildCommunityMentionExtension(opts: {
/**
* Standalone-token scan for `@everyone`. Used at send time to set
* `mentionType` on the outgoing POST body so the server fans out to all
- * members. Iterates `MENTION_TYPES` (now just `everyone`; `@here` was removed —
- * see plans/remove-here-mention.md).
+ * members. Iterates `MENTION_TYPES`, now just `everyone`; `@here` was removed.
*/
export function detectMentionType(text: string): MentionType | undefined {
if (!text) return undefined
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 3205587f0..0cb71d9fc 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -266,7 +266,7 @@ describe("createCommunityMessage — replyToId write-path scope validation (dang
})
})
-describe("createCommunityMessage — CAS race (plans/fix-agent-send-race-condition.md)", () => {
+describe("createCommunityMessage — CAS race", () => {
beforeEach(() => {
vi.clearAllMocks()
})
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 6f7fba051..ed892d30e 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -161,8 +161,7 @@ export async function createCommunityMessage(params: {
/** Provenance tag included in diagnostics when a requested reply target is out of scope. */
source?: "cli" | "daemon-http" | "web"
/**
- * CAS guard for the agent-send race fix
- * (plans/fix-agent-send-race-condition.md). Only the agent `send` route
+ * CAS guard for the agent-send race fix. Only the agent `send` route
* passes this — it's the `latestSeq` snapshot that route's own alignment
* check already computed. Omitted by every other caller (web/human sends,
* thread posts), which keep the unconditional, always-succeeds claim.
diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.ts
index 0acc883f9..141a3509e 100644
--- a/src/web/src/lib/community/message-payload.test.ts
+++ b/src/web/src/lib/community/message-payload.test.ts
@@ -68,7 +68,7 @@ describe("mapMessageForApi", () => {
it("emits { deleted: true } when replyToId is set but the target is missing (out-of-scope filtered upstream)", () => {
const out = mapMessageForApi({ ...baseRow, replyToId: "m-gone" }, emptyApiCtx)
- expect(out.replyTo).toEqual({ id: "m-gone", authorName: "Unknown", text: "", deleted: true })
+ expect(out.replyTo).toEqual({ id: "m-gone", authorName: "Deleted user", text: "", deleted: true })
})
it("gives API and WS projections the same ellipsized reply preview", () => {
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 390c76fa6..1a4a6028d 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -18,6 +18,7 @@ import { truncateMessagePreview, type MentionType } from "@alook/shared"
import type { FriendApprovalPayload } from "@alook/shared"
import { avatarInitial } from "@/lib/community/avatar"
import { canonicalUserImage } from "@/lib/community/storage"
+import { projectMessageWireType } from "@/lib/community/message-wire-type"
// The subset of fields on rows returned by
// queries.communityMessage.{listMessages, getMessage, getMessagesByIds} that
@@ -105,7 +106,7 @@ function coreFields(row: MessageRow) {
function resolveReply(row: MessageRow, replyMap: Map<string, ReplyTargetRow>): ReplyPreview | undefined {
if (!row.replyToId) return undefined
const target = replyMap.get(row.replyToId)
- if (!target) return { id: row.replyToId, authorName: "Unknown", text: "", deleted: true }
+ if (!target) return { id: row.replyToId, authorName: "Deleted user", text: "", deleted: true }
return {
id: target.id,
authorId: target.authorId,
@@ -134,12 +135,9 @@ export type ApiMessageContext = {
// can distinguish it from a bare `type: "system"` row with no known kind
// (which stays `systemKind: undefined`, falling back to the generic icon).
// Ordinary messages map to `type: "chat"` (never `undefined`) now that
-// `Msg.type` is a required, exhaustive discriminator (#12).
-function splitType(type: string | null): { type: "chat" | "system"; systemKind?: "thread" } {
- if (type === "thread_created") return { type: "system", systemKind: "thread" }
- if (type === "system") return { type: "system" }
- return { type: "chat" }
-}
+// `Msg.type` is a required, exhaustive discriminator (#12). The mapper lives
+// in message-wire-type so cross-scope feeds (Mentions/Marked) use the exact
+// same DB-to-wire normalization as channel message responses.
export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {
const core = coreFields(row)
@@ -149,7 +147,7 @@ export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext) {
row.clientNonce && !row.clientNonce.startsWith("srv:") ? row.clientNonce : undefined
return {
...core,
- ...splitType(row.type),
+ ...projectMessageWireType(row.type),
...(clientNonce ? { clientNonce } : {}),
replyTo: resolveReply(row, ctx.replyMap),
embeds: row.embeds,
@@ -184,7 +182,7 @@ export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext) {
ctx.clientNonce && !ctx.clientNonce.startsWith("srv:") ? ctx.clientNonce : undefined
return {
...core,
- ...splitType(row.type),
+ ...projectMessageWireType(row.type),
...(clientNonce ? { clientNonce } : {}),
replyTo: resolveReply(row, ctx.replyMap),
// The shared CommunityMessageCreate.embeds is `unknown[]` — narrow here
diff --git a/src/web/src/lib/community/message-read-projection.test.ts b/src/web/src/lib/community/message-read-projection.test.ts
new file mode 100644
index 000000000..244ae77a9
--- /dev/null
+++ b/src/web/src/lib/community/message-read-projection.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from "vitest"
+import { resolveMessageReadProjection } from "./message-read-projection"
+
+const messages = [
+ { id: "self", authorId: "viewer" },
+ { id: "anchor", authorId: "viewer" },
+ { id: "peer", authorId: "peer" },
+]
+
+describe("resolveMessageReadProjection", () => {
+ it("settles a warm canonical window without waiting for its query page marker", () => {
+ expect(resolveMessageReadProjection({
+ messages,
+ lastReadMessageId: "anchor",
+ viewerUserId: "viewer",
+ anchorReconciled: false,
+ })).toEqual({ newDividerBefore: "peer", anchorFound: true })
+ })
+
+ it("keeps an anchor-incomplete window unresolved until the anchor arrives", () => {
+ expect(resolveMessageReadProjection({
+ messages: [messages[2]],
+ lastReadMessageId: "anchor",
+ viewerUserId: "viewer",
+ anchorReconciled: false,
+ })).toEqual({ newDividerBefore: undefined, anchorFound: false })
+
+ expect(resolveMessageReadProjection({
+ messages: messages.slice(1),
+ lastReadMessageId: "anchor",
+ viewerUserId: "viewer",
+ anchorReconciled: true,
+ })).toEqual({ newDividerBefore: "peer", anchorFound: true })
+ })
+
+ it("distinguishes a pending first visit from a reconciled empty window", () => {
+ expect(resolveMessageReadProjection({
+ messages: [],
+ lastReadMessageId: null,
+ viewerUserId: "viewer",
+ anchorReconciled: false,
+ }).anchorFound).toBe(false)
+ expect(resolveMessageReadProjection({
+ messages: [],
+ lastReadMessageId: null,
+ viewerUserId: "viewer",
+ anchorReconciled: true,
+ }).anchorFound).toBe(true)
+ })
+
+ it("places a first-visit divider before the first peer row already in canonical data", () => {
+ expect(resolveMessageReadProjection({
+ messages,
+ lastReadMessageId: null,
+ viewerUserId: "viewer",
+ anchorReconciled: false,
+ })).toEqual({ newDividerBefore: "peer", anchorFound: true })
+ })
+})
diff --git a/src/web/src/lib/community/message-read-projection.ts b/src/web/src/lib/community/message-read-projection.ts
new file mode 100644
index 000000000..3a202b71c
--- /dev/null
+++ b/src/web/src/lib/community/message-read-projection.ts
@@ -0,0 +1,38 @@
+type ProjectionMessage = {
+ id: string
+ authorId?: string | null
+}
+
+export type MessageReadProjection = {
+ newDividerBefore: string | undefined
+ anchorFound: boolean
+}
+
+export function resolveMessageReadProjection({
+ messages,
+ lastReadMessageId,
+ viewerUserId,
+ anchorReconciled,
+}: {
+ messages: ProjectionMessage[]
+ lastReadMessageId: string | null
+ viewerUserId: string
+ anchorReconciled: boolean
+}): MessageReadProjection {
+ if (!lastReadMessageId) {
+ if (messages.length === 0 && !anchorReconciled) {
+ return { newDividerBefore: undefined, anchorFound: false }
+ }
+ const firstUnread = messages.find((message) => message.authorId !== viewerUserId)
+ return { newDividerBefore: firstUnread?.id, anchorFound: true }
+ }
+
+ const anchorIndex = messages.findIndex((message) => message.id === lastReadMessageId)
+ if (anchorIndex === -1) {
+ return { newDividerBefore: undefined, anchorFound: false }
+ }
+ const firstUnread = messages
+ .slice(anchorIndex + 1)
+ .find((message) => message.authorId !== viewerUserId)
+ return { newDividerBefore: firstUnread?.id, anchorFound: true }
+}
diff --git a/src/web/src/lib/community/message-wire-type.test.ts b/src/web/src/lib/community/message-wire-type.test.ts
new file mode 100644
index 000000000..0feff22cf
--- /dev/null
+++ b/src/web/src/lib/community/message-wire-type.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest"
+import { projectMessageWireType } from "./message-wire-type"
+
+describe("projectMessageWireType", () => {
+ it("normalizes every stored message discriminator to the canonical wire shape", () => {
+ expect(projectMessageWireType("default")).toEqual({ type: "chat" })
+ expect(projectMessageWireType("system")).toEqual({ type: "system" })
+ expect(projectMessageWireType("thread_created")).toEqual({
+ type: "system",
+ systemKind: "thread",
+ })
+ })
+})
diff --git a/src/web/src/lib/community/message-wire-type.ts b/src/web/src/lib/community/message-wire-type.ts
new file mode 100644
index 000000000..478c365cd
--- /dev/null
+++ b/src/web/src/lib/community/message-wire-type.ts
@@ -0,0 +1,15 @@
+export type MessageWireType = {
+ type: "chat" | "system"
+ systemKind?: "thread"
+}
+
+/** Normalize the stored message discriminator at every human-client wire boundary. */
+export function projectMessageWireType(
+ type: string | null | undefined,
+): MessageWireType {
+ if (type === "thread_created") {
+ return { type: "system", systemKind: "thread" }
+ }
+ if (type === "system") return { type: "system" }
+ return { type: "chat" }
+}
diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.ts
index 0ca186522..16fc36fd4 100644
--- a/src/web/src/lib/community/message-wire.ts
+++ b/src/web/src/lib/community/message-wire.ts
@@ -5,6 +5,7 @@ import { isInlineAttachmentContentType } from "@/lib/community/attachment-conten
import { formatAttachmentSize } from "@/lib/community/attachment-presentation"
import type { CanonicalMessage } from "@/lib/community/message-stream"
import { canonicalUserImage } from "@/lib/community/storage"
+import { projectMessageWireType } from "@/lib/community/message-wire-type"
type UiEmbed = NonNullable<Msg["embeds"]>[number]
@@ -149,15 +150,10 @@ export function projectPostedMessage(
return projected ? [projected] : []
})
: undefined
- const type = message.type === "thread_created"
- ? { type: "system" as const, systemKind: "thread" as const }
- : message.type === "system"
- ? { type: "system" as const }
- : { type: "chat" as const }
return {
id: message.id,
seq: message.seq,
- ...type,
+ ...projectMessageWireType(message.type),
authorId: message.authorId,
authorName: message.authorName,
authorAvatar: canonicalUserImage(
diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.ts
index 0d5fb4e3a..173d76b04 100644
--- a/src/web/src/lib/community/models/inbox.ts
+++ b/src/web/src/lib/community/models/inbox.ts
@@ -14,6 +14,8 @@ export type Mention = {
channel: string
channelId?: string
m: Msg
+ /** Canonical owners are still hydrating; render a keyed local skeleton. */
+ pending?: boolean
}
// A single per-user saved ("marked") message, as returned by
@@ -101,4 +103,5 @@ export type InboxFriendRequest = {
avatar: string
avatarVersion: number | null
createdAt: string
+ pendingIdentity?: boolean
}
diff --git a/src/web/src/lib/community/models/people.ts b/src/web/src/lib/community/models/people.ts
index f8e10fe92..3f0b93988 100644
--- a/src/web/src/lib/community/models/people.ts
+++ b/src/web/src/lib/community/models/people.ts
@@ -26,18 +26,12 @@ export type CommunityProfilePatch = {
presence?: Presence
}
-export type CommunityProfileSnapshot = {
- viewerId: string | null
- accountEpoch: number
- revision: number
-}
-
// ── Members / friends / DMs ──────────────────────────────────────────────────
// Identity fields shared by every community user view-model (member / friend /
// DM). All three are required `string`: `user.name`/`user.discriminator` are
// NOT NULL columns always projected on live payloads. Requiring `discriminator`
// here (in one place) moves the "a mention target always has a tag" guarantee
-// to compile time — see plans/mandatory-mention-discriminator.md. `userId` is
+// to compile time. `userId` is
// NOT part of the core: it's required on Member/DM but optional on Friend, so
// each type declares it. Only types whose identity fields are identically
// shaped extend this — AddableMember/ThreadParticipant (nullable projections),
diff --git a/src/web/src/lib/community/profile-read.ts b/src/web/src/lib/community/profile-read.ts
index 2194493e3..8a659ac51 100644
--- a/src/web/src/lib/community/profile-read.ts
+++ b/src/web/src/lib/community/profile-read.ts
@@ -5,7 +5,7 @@ export function readCommunityProfile(
profile: CommunityProfile | undefined,
userId: string,
) {
- const name = profile?.name ?? "Unknown"
+ const name = profile?.name ?? "Deleted user"
return {
id: userId,
name,
diff --git a/src/web/src/lib/community/profile-seed.test.ts b/src/web/src/lib/community/profile-seed.test.ts
index d5cd641f4..1235209d3 100644
--- a/src/web/src/lib/community/profile-seed.test.ts
+++ b/src/web/src/lib/community/profile-seed.test.ts
@@ -1,24 +1,26 @@
import { QueryClient } from "@tanstack/react-query"
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import type { Msg } from "@/lib/community/models/message"
import { communityKeys } from "@/lib/query-keys"
-import type { MessagesPage, Msg } from "@/lib/community/models/message"
import {
apiFetchProfiles,
+ beginCommunityProfileSeed,
communityUserProfilePatch,
- loadAndSeedProfiles,
messageProfilePatches,
- seedPersistedMessageProfiles,
+ writeCommunityProfilePatches,
} from "./profile-seed"
-import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ createCommunityDbRegistry,
+ registerCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
const apiFetch = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch }))
-function activate(viewerId = "viewer") {
- useCommunityWsStore.getState().activateProfileAccount(viewerId)
- return useCommunityWsStore.getState().beginProfileSnapshot()
-}
+let registry: CommunityDbRegistry
+let unregister: () => void
function chat(overrides: Partial<Msg> = {}): Msg {
return {
@@ -29,9 +31,16 @@ function chat(overrides: Partial<Msg> = {}): Msg {
}
}
-beforeEach(() => {
+beforeEach(async () => {
apiFetch.mockReset()
- useCommunityWsStore.getState().reset()
+ registry = createCommunityDbRegistry(new QueryClient(), "viewer")
+ await registry.preload()
+ unregister = registerCommunityDbRegistry(registry)
+})
+
+afterEach(async () => {
+ unregister()
+ await registry.cleanup()
})
describe("communityUserProfilePatch", () => {
@@ -131,36 +140,55 @@ describe("messageProfilePatches", () => {
})
describe("profile seeding boundaries", () => {
- it("seeds restored persisted messages without rewriting the raw Query payload", () => {
- const snapshot = activate()
- const queryClient = new QueryClient()
- const data = {
- pages: [{
- messages: [chat({
- authorId: "u1",
- authorName: "Persisted Alice",
- authorAvatar: "/persisted.png",
- authorAvatarVersion: 8,
- })],
- hasMore: false,
- } satisfies MessagesPage],
- pageParams: [{ mode: "newest" }],
- }
- queryClient.setQueryData(communityKeys.channelMessages("channel"), data)
- const rawBefore = queryClient.getQueryData(communityKeys.channelMessages("channel"))
-
- seedPersistedMessageProfiles(queryClient, snapshot)
-
- expect(queryClient.getQueryData(communityKeys.channelMessages("channel"))).toBe(rawBefore)
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
- name: "Persisted Alice",
- avatar: "/persisted.png",
+ it("writes profile patches into the canonical collection", () => {
+ writeCommunityProfilePatches([{
+ id: "u1",
+ identityAbout: { name: "Alice", discriminator: "0001" },
+ avatar: { avatar: "/alice.png", avatarVersion: 8 },
+ }], registry)
+
+ expect(registry.collections.profiles.get("u1")).toMatchObject({
+ name: "Alice",
+ avatar: "/alice.png",
avatarVersion: 8,
})
})
- it("returns the raw API object while seeding its typed profile projection", async () => {
- activate()
+ it("falls back to live collection rows when the canonical query cache is absent", () => {
+ writeCommunityProfilePatches([{
+ id: "u-cache-gap",
+ identityAbout: { name: "Before", discriminator: "0009" },
+ }], registry)
+ const queryKey = communityKeys.communityDbCollection(registry.scopeId, "profiles")
+ registry.queryClient.removeQueries({ queryKey, exact: true })
+
+ writeCommunityProfilePatches([{
+ id: "u-cache-gap",
+ status: { statusEmoji: "🌱", statusText: "Growing" },
+ }], registry)
+
+ expect(registry.collections.profiles.get("u-cache-gap")).toMatchObject({
+ name: "Before",
+ discriminator: "0009",
+ statusEmoji: "🌱",
+ })
+ })
+
+ it("rejects a request snapshot captured by a different registry", async () => {
+ const other = createCommunityDbRegistry(new QueryClient(), "other")
+ await other.preload()
+ const snapshot = beginCommunityProfileSeed(other)
+
+ writeCommunityProfilePatches([{
+ id: "u-mismatch",
+ identityAbout: { name: "Wrong account" },
+ }], registry, { snapshot })
+
+ expect(registry.collections.profiles.get("u-mismatch")).toBeUndefined()
+ await other.cleanup()
+ })
+
+ it("returns the raw API object while updating its canonical profile projection", async () => {
const raw = { member: { id: "u2", name: "API Alice" } }
apiFetch.mockResolvedValueOnce(raw)
@@ -174,27 +202,33 @@ describe("profile seeding boundaries", () => {
expect(result).toBe(raw)
expect(apiFetch).toHaveBeenCalledWith("/profiles")
- expect(useCommunityWsStore.getState().profilesByUserId.get("u2")?.name).toBe("API Alice")
+ expect(registry.collections.profiles.get("u2")?.name).toBe("API Alice")
})
- it("does not let a late request overwrite a newer authoritative group patch", async () => {
- activate()
- let resolve!: (value: { id: string; name: string }) => void
- const pending = new Promise<{ id: string; name: string }>((done) => { resolve = done })
- const resultPromise = loadAndSeedProfiles(
- () => pending,
- (data) => [{ id: data.id, identityAbout: { name: data.name } }],
- )
-
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
+ it("merges partial updates without erasing canonical fields", () => {
+ writeCommunityProfilePatches([{
id: "u3",
- identityAbout: { name: "WS Alice" },
- }])
- const raw = { id: "u3", name: "Late API Alice" }
- resolve(raw)
+ identityAbout: { name: "Alice", discriminator: "0003", aboutMe: "hello" },
+ avatar: { avatar: "/alice.png", avatarVersion: 3 },
+ }], registry)
+ writeCommunityProfilePatches([{
+ id: "u3",
+ status: { statusEmoji: "🌱", statusText: "Growing" },
+ }], registry)
+ writeCommunityProfilePatches([{
+ id: "u3",
+ avatar: { avatar: "/stale.png", avatarVersion: 2 },
+ status: { statusEmoji: null, statusText: null },
+ }], registry)
- await expect(resultPromise).resolves.toBe(raw)
- expect(useCommunityWsStore.getState().profilesByUserId.get("u3")?.name).toBe("WS Alice")
+ expect(registry.collections.profiles.get("u3")).toMatchObject({
+ name: "Alice",
+ discriminator: "0003",
+ aboutMe: "hello",
+ avatar: "/alice.png",
+ avatarVersion: 3,
+ statusEmoji: null,
+ statusText: null,
+ })
})
})
diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.ts
index 92b6b88d3..b8f3b1a61 100644
--- a/src/web/src/lib/community/profile-seed.ts
+++ b/src/web/src/lib/community/profile-seed.ts
@@ -1,16 +1,52 @@
import type {
CommunityProfilePatch,
- CommunityProfileSnapshot,
CommunityUserCore,
} from "@/lib/community/models/people"
-import type { InfiniteData, QueryClient } from "@tanstack/react-query"
-import type { MessagesPage, Msg } from "@/lib/community/models/message"
+import type { Msg } from "@/lib/community/models/message"
import type { FriendApprovalPayload } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { avatarInitial } from "@/lib/community/avatar"
-import { shouldPersistQueryKey } from "@/lib/query-persister"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ getActiveCommunityDbRegistry,
+ type CommunityDbRegistry,
+} from "@/lib/community-db/collections"
+import { profileSchema, type ProfileRow } from "@/lib/community-db/schema"
import { useCommunityWsStore } from "@/stores/community/ws"
+type ProfileFieldRevisions = {
+ identityAbout: number
+ avatar: number
+ status: number
+}
+
+type ProfileRevisionState = {
+ revision: number
+ fieldsByUserId: Map<string, ProfileFieldRevisions>
+}
+
+export type CommunityProfileSeedSnapshot = {
+ registry: CommunityDbRegistry | null
+ revision: number
+}
+
+const profileRevisionState = new WeakMap<CommunityDbRegistry, ProfileRevisionState>()
+
+function revisionState(registry: CommunityDbRegistry) {
+ let state = profileRevisionState.get(registry)
+ if (!state) {
+ state = { revision: 0, fieldsByUserId: new Map() }
+ profileRevisionState.set(registry, state)
+ }
+ return state
+}
+
+export function beginCommunityProfileSeed(
+ registry = getActiveCommunityDbRegistry(),
+): CommunityProfileSeedSnapshot {
+ return { registry, revision: registry ? revisionState(registry).revision : 0 }
+}
+
type CommunityUserProfileSeed = CommunityUserCore & {
statusEmoji?: string | null
statusText?: string | null
@@ -93,30 +129,105 @@ export function approvalProfilePatches(
}] : [])
}
-export function seedPersistedMessageProfiles(
- queryClient: QueryClient,
- snapshot: CommunityProfileSnapshot,
+export function writeCommunityProfilePatches(
+ patches: readonly CommunityProfilePatch[],
+ registry = getActiveCommunityDbRegistry(),
+ options?: { snapshot?: CommunityProfileSeedSnapshot; event?: boolean },
) {
- const patches: CommunityProfilePatch[] = []
- const cached = queryClient.getQueriesData<InfiniteData<MessagesPage>>({
- predicate: (query) => shouldPersistQueryKey(query.queryKey),
- })
- for (const [, data] of cached) {
- for (const page of data?.pages ?? []) {
- patches.push(...messageProfilePatches(page.messages))
+ if (!registry || patches.length === 0) 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.userId, profile]))
+ const revisions = revisionState(registry)
+ const guardedRevision = options?.snapshot?.revision
+ const writeRevision = guardedRevision === undefined ? revisions.revision + 1 : null
+ let advanced = false
+ for (const patch of patches) {
+ const current = profiles.get(patch.id)
+ const fieldRevisions = revisions.fieldsByUserId.get(patch.id) ?? {
+ identityAbout: 0,
+ avatar: 0,
+ status: 0,
}
+ const accepts = (field: keyof ProfileFieldRevisions) => (
+ guardedRevision === undefined || fieldRevisions[field] <= guardedRevision
+ )
+ const identityAbout = patch.identityAbout && accepts("identityAbout")
+ ? patch.identityAbout
+ : undefined
+ const status = patch.status && accepts("status") ? patch.status : undefined
+ const incomingAvatar = patch.avatar && accepts("avatar") && (
+ current === undefined
+ || patch.avatar.avatarVersion > current.avatarVersion
+ || (!options?.event && patch.avatar.avatarVersion === current.avatarVersion)
+ ) ? patch.avatar : undefined
+ const name = identityAbout?.name ?? current?.name ?? ""
+ const next = profileSchema.parse({
+ userId: patch.id,
+ name,
+ discriminator: identityAbout?.discriminator ?? current?.discriminator ?? "",
+ avatar: incomingAvatar?.avatar ?? current?.avatar ?? avatarInitial(name),
+ avatarVersion: incomingAvatar?.avatarVersion ?? current?.avatarVersion ?? 0,
+ aboutMe: identityAbout?.aboutMe ?? current?.aboutMe,
+ bannerColor: identityAbout?.bannerColor === undefined
+ ? current?.bannerColor
+ : identityAbout.bannerColor,
+ kind: identityAbout?.kind ?? current?.kind,
+ ownerUserId: identityAbout?.ownerUserId === undefined
+ ? current?.ownerUserId
+ : identityAbout.ownerUserId,
+ statusEmoji: status?.statusEmoji === undefined
+ ? current?.statusEmoji
+ : status.statusEmoji,
+ statusText: status?.statusText === undefined
+ ? current?.statusText
+ : status.statusText,
+ })
+ profiles.set(patch.id, next)
+ if (writeRevision !== null) {
+ const nextRevisions = { ...fieldRevisions }
+ if (identityAbout) nextRevisions.identityAbout = writeRevision
+ if (incomingAvatar) nextRevisions.avatar = writeRevision
+ if (status) nextRevisions.status = writeRevision
+ if (identityAbout || incomingAvatar || status) {
+ revisions.fieldsByUserId.set(patch.id, nextRevisions)
+ advanced = true
+ }
+ }
+ }
+ if (advanced && writeRevision !== null) revisions.revision = writeRevision
+ const rows = [...profiles.values()]
+ if (registry.collections.profiles.status === "ready") {
+ registry.collections.profiles.utils.writeUpsert(rows)
}
- useCommunityWsStore.getState().seedProfiles(snapshot, patches)
+ registry.queryClient.setQueryData(queryKey, rows)
}
export async function loadAndSeedProfiles<T>(
load: () => Promise<T>,
patches: (data: T) => readonly CommunityProfilePatch[],
): Promise<T> {
- const profiles = useCommunityWsStore.getState()
- const snapshot = profiles.beginProfileSnapshot()
+ const overlay = useCommunityWsStore.getState()
+ const overlaySnapshot = overlay.beginPresenceSnapshot()
+ const profileSnapshot = beginCommunityProfileSeed()
const data = await load()
- profiles.seedProfiles(snapshot, patches(data))
+ const projected = patches(data)
+ writeCommunityProfilePatches(projected, profileSnapshot.registry, {
+ snapshot: profileSnapshot,
+ })
+ const presence = projected.flatMap((patch) => (
+ patch.presence === undefined
+ ? []
+ : [{ id: patch.id, presence: patch.presence }]
+ ))
+ if (presence.length > 0) {
+ overlay.seedPresence(
+ overlaySnapshot,
+ presence.map((patch) => [patch.id, patch.presence] as const),
+ )
+ }
return data
}
diff --git a/src/web/src/lib/community/queue-transport.ts b/src/web/src/lib/community/queue-transport.ts
index 467811fbd..3d97c8368 100644
--- a/src/web/src/lib/community/queue-transport.ts
+++ b/src/web/src/lib/community/queue-transport.ts
@@ -65,7 +65,7 @@ export function createQueueTransport(queue: Queue<AlookQueueTask>): QueueTranspo
/**
* Dev-only. Local Cloudflare Queues simulation cannot bridge separate
- * `wrangler dev`/`next dev` processes (plans/minimal-wake-queue-unread-notice.md)
+ * `wrangler dev`/`next dev` processes
* — every cross-process Queue send from `next dev` lands nowhere. This
* transport instead calls the real `alook-queue-worker` process directly over
* HTTP (its `fetch()` dev entrypoint, see `src/queue-worker/src/index.ts`),
diff --git a/src/web/src/lib/community/reaction-operations.test.ts b/src/web/src/lib/community/reaction-operations.test.ts
index b02244302..948da95cf 100644
--- a/src/web/src/lib/community/reaction-operations.test.ts
+++ b/src/web/src/lib/community/reaction-operations.test.ts
@@ -198,7 +198,7 @@ describe("reaction operations", () => {
expect(result).toEqual({
ok: true,
value: [
- { emoji: "👍", actors: ["@Zed#0002", "Unknown user"], me: false },
+ { emoji: "👍", actors: ["@Zed#0002", "Deleted user"], me: false },
{ emoji: "🔥", actors: ["@Ana#0001"], me: true },
],
})
diff --git a/src/web/src/lib/community/reaction-operations.ts b/src/web/src/lib/community/reaction-operations.ts
index 5c0049f47..3e7ad4af5 100644
--- a/src/web/src/lib/community/reaction-operations.ts
+++ b/src/web/src/lib/community/reaction-operations.ts
@@ -111,7 +111,7 @@ export async function listReactionsForActor(
actor.userId,
actor.profile
? `@${formatHandle(actor.profile.name, actor.profile.discriminator)}`
- : "Unknown user",
+ : "Deleted user",
]))
const byEmoji = new Map<string, { actorIds: Set<string>; me: boolean }>()
for (const reaction of reactions) {
@@ -127,7 +127,7 @@ export async function listReactionsForActor(
.map(([emoji, group]) => ({
emoji,
actors: [...group.actorIds]
- .map((userId) => handles.get(userId) ?? "Unknown user")
+ .map((userId) => handles.get(userId) ?? "Deleted user")
.sort((a, b) => a === b ? 0 : a < b ? -1 : 1),
me: group.me,
})),
diff --git a/src/web/src/lib/community/structural-snapshot.test.ts b/src/web/src/lib/community/structural-snapshot.test.ts
deleted file mode 100644
index d210e2071..000000000
--- a/src/web/src/lib/community/structural-snapshot.test.ts
+++ /dev/null
@@ -1,406 +0,0 @@
-import { describe, expect, it } from "vitest"
-import { QueryClient } from "@tanstack/react-query"
-import { communityKeys } from "@/lib/query-keys"
-import {
- parseStructuralSnapshot,
- projectServerDetailTree,
- reduceStructuralSnapshot,
- STRUCTURAL_SNAPSHOT_CHILD_LIMIT,
- STRUCTURAL_SNAPSHOT_TTL_MS,
- structuralServerToCategories,
- structuralSnapshotDirectory,
- structuralSnapshotFolders,
- structuralSnapshotServers,
- type StructuralSnapshotV1,
- updateStructuralSnapshot,
-} from "./structural-snapshot"
-
-const NOW = 2_000_000_000_000
-
-function snapshot(): StructuralSnapshotV1 {
- return {
- schemaVersion: 1,
- accountId: "account-a",
- capturedAt: NOW,
- serverOrder: ["server-b", "server-a"],
- folders: [{ id: "folder-1", name: "Work", serverIds: ["server-a"] }],
- servers: [
- {
- id: "server-a",
- name: "Alpha",
- discriminator: "0001",
- icon: null,
- categories: [{ id: "category-1", name: "General", private: false }],
- channels: [
- { id: "channel-a", name: "chat", type: "text", categoryId: "category-1" },
- { id: "channel-b", name: "ideas", type: "forum", categoryId: null },
- ],
- childRouteHints: [{
- id: "child-1",
- name: "thread",
- type: "thread",
- parentChannelId: "channel-a",
- parentMessageId: "message-1",
- }],
- },
- {
- id: "server-b",
- name: "Beta",
- discriminator: "0002",
- icon: "https://example.com/icon.png",
- categories: [],
- channels: [],
- childRouteHints: [],
- },
- ],
- }
-}
-
-describe("parseStructuralSnapshot", () => {
- it("round-trips the exact v1 allowlist", () => {
- expect(parseStructuralSnapshot(snapshot(), "account-a", NOW)).toEqual(snapshot())
- })
-
- it.each([
- ["wrong account", { ...snapshot(), accountId: "account-b" }],
- ["wrong version", { ...snapshot(), schemaVersion: 2 }],
- ["expired", { ...snapshot(), capturedAt: NOW - STRUCTURAL_SNAPSHOT_TTL_MS - 1 }],
- ["future", { ...snapshot(), capturedAt: NOW + 1 }],
- ["unknown top-level field", { ...snapshot(), role: "owner" }],
- ])("rejects %s", (_label, value) => {
- expect(parseStructuralSnapshot(value, "account-a", NOW)).toBeNull()
- })
-
- it("rejects unknown nested authorization and runtime fields", () => {
- const value = snapshot() as StructuralSnapshotV1 & {
- servers: Array<StructuralSnapshotV1["servers"][number] & { ownerId?: string }>
- }
- value.servers[0] = { ...value.servers[0]!, ownerId: "owner-1" }
- expect(parseStructuralSnapshot(value, "account-a", NOW)).toBeNull()
-
- })
-
- it("rejects duplicate, dangling, temporary, and over-limit references", () => {
- const duplicate = snapshot()
- duplicate.serverOrder = ["server-a", "server-a"]
- expect(parseStructuralSnapshot(duplicate, "account-a", NOW)).toBeNull()
-
- const dangling = snapshot()
- dangling.servers[0]!.channels[0]!.categoryId = "missing"
- expect(parseStructuralSnapshot(dangling, "account-a", NOW)).toBeNull()
-
- const temporary = snapshot()
- temporary.servers[0]!.channels[0]!.id = "tmp_ch_1"
- expect(parseStructuralSnapshot(temporary, "account-a", NOW)).toBeNull()
-
- const oversized = snapshot()
- oversized.servers[0]!.childRouteHints = Array.from(
- { length: STRUCTURAL_SNAPSHOT_CHILD_LIMIT + 1 },
- (_, index) => ({
- id: `child-${index}`,
- name: `Thread ${index}`,
- type: "thread" as const,
- parentChannelId: "channel-a",
- parentMessageId: `message-${index}`,
- }),
- )
- expect(parseStructuralSnapshot(oversized, "account-a", NOW)).toBeNull()
- })
-
- it("rejects malformed and unsafe child-route hints", () => {
- const unknownField = snapshot() as unknown as {
- servers: Array<{ childRouteHints: Array<Record<string, unknown>> }>
- }
- unknownField.servers[0]!.childRouteHints[0]!.permission = "read"
- expect(parseStructuralSnapshot(unknownField, "account-a", NOW)).toBeNull()
-
- const unsafeParentMessage = snapshot()
- unsafeParentMessage.servers[0]!.childRouteHints[0]!.parentMessageId = ""
- expect(parseStructuralSnapshot(unsafeParentMessage, "account-a", NOW)).toBeNull()
- })
-
- it("preserves an empty folder as structural rail state", () => {
- const value = snapshot()
- value.folders = [{ id: "folder-empty", name: "Later", serverIds: [] }]
- expect(parseStructuralSnapshot(value, "account-a", NOW)?.folders).toEqual(value.folders)
-
- const next = reduceStructuralSnapshot(value, {
- type: "replaceFolders",
- folders: value.folders,
- }, NOW)!
- expect(next.folders).toEqual(value.folders)
- })
-
- it("accepts a bounded 100-server structural fixture without runtime data", () => {
- const servers = Array.from({ length: 100 }, (_, serverIndex) => {
- const channels = Array.from({ length: 10 }, (_, channelIndex) => ({
- id: `server-${serverIndex}-channel-${channelIndex}`,
- name: `Channel ${channelIndex}`,
- type: channelIndex % 2 === 0 ? "text" as const : "forum" as const,
- categoryId: `server-${serverIndex}-category`,
- }))
- return {
- id: `server-${serverIndex}`,
- name: `Server ${serverIndex}`,
- discriminator: String(serverIndex).padStart(4, "0"),
- icon: null,
- categories: [{
- id: `server-${serverIndex}-category`,
- name: "General",
- private: false,
- }],
- channels,
- childRouteHints: Array.from({ length: STRUCTURAL_SNAPSHOT_CHILD_LIMIT }, (_, childIndex) => ({
- id: `server-${serverIndex}-child-${childIndex}`,
- name: `Thread ${childIndex}`,
- type: "thread" as const,
- parentChannelId: channels[0]!.id,
- parentMessageId: `server-${serverIndex}-message-${childIndex}`,
- })),
- }
- })
- const value: StructuralSnapshotV1 = {
- schemaVersion: 1,
- accountId: "account-a",
- capturedAt: NOW,
- serverOrder: servers.map((server) => server.id),
- folders: [],
- servers,
- }
-
- const parsed = parseStructuralSnapshot(value, "account-a", NOW)
-
- expect(parsed?.servers).toHaveLength(100)
- expect(parsed?.servers.flatMap((server) => server.channels)).toHaveLength(1_000)
- expect(parsed?.servers.flatMap((server) => server.childRouteHints)).toHaveLength(3_200)
- expect(JSON.stringify(parsed).length).toBeLessThan(1_000_000)
- })
-})
-
-describe("reduceStructuralSnapshot", () => {
- it("authoritatively replaces server membership while preserving known trees", () => {
- const next = reduceStructuralSnapshot(snapshot(), {
- type: "replaceServers",
- accountId: "account-a",
- servers: [{ id: "server-a", name: "Renamed", discriminator: "0001", icon: null }],
- }, NOW + 1)!
- expect(next.serverOrder).toEqual(["server-a"])
- expect(next.servers[0]?.name).toBe("Renamed")
- expect(next.servers[0]?.channels.map((channel) => channel.id)).toEqual(["channel-a", "channel-b"])
- expect(next.folders).toEqual([{ id: "folder-1", name: "Work", serverIds: ["server-a"] }])
- })
-
- it("retains only child hints whose parent remains in a replaced server tree", () => {
- const next = reduceStructuralSnapshot(snapshot(), {
- type: "replaceServerTree",
- serverId: "server-a",
- categories: [{ id: "category-1", name: "General", private: false }],
- channels: [{ id: "channel-a", name: "chat", type: "text", categoryId: "category-1" }],
- }, NOW + 1)!
-
- expect(next.servers[0]?.childRouteHints.map((child) => child.id)).toEqual(["child-1"])
- })
-
- it("prunes a parent channel and every related child hint atomically", () => {
- const next = reduceStructuralSnapshot(snapshot(), {
- type: "removeChannel",
- serverId: "server-a",
- channelId: "channel-a",
- }, NOW + 1)!
- expect(next.servers[0]?.channels.map((channel) => channel.id)).toEqual(["channel-b"])
- expect(next.servers[0]?.childRouteHints).toEqual([])
- })
-
- it("bounds child hints by most-recent insertion", () => {
- let current = snapshot()
- current.servers[0]!.childRouteHints = []
- for (let index = 0; index < STRUCTURAL_SNAPSHOT_CHILD_LIMIT + 5; index += 1) {
- current = reduceStructuralSnapshot(current, {
- type: "upsertChildHint",
- serverId: "server-a",
- child: {
- id: `child-${index}`,
- name: `Thread ${index}`,
- type: "thread",
- parentChannelId: "channel-a",
- parentMessageId: `message-${index}`,
- },
- }, NOW + index)!
- }
- expect(current.servers[0]?.childRouteHints).toHaveLength(STRUCTURAL_SNAPSHOT_CHILD_LIMIT)
- expect(current.servers[0]?.childRouteHints[0]?.id).toBe(`child-${STRUCTURAL_SNAPSHOT_CHILD_LIMIT + 4}`)
- })
-
- it("reconciles every ordered tree and rail mutation through one reducer", () => {
- let current = snapshot()
- current = reduceStructuralSnapshot(current, {
- type: "replaceRail",
- serverOrder: ["server-a", "unknown", "server-a"],
- folders: [
- { id: "folder-a", name: "A", serverIds: ["server-a"] },
- { id: "folder-b", name: "B", serverIds: ["server-b"] },
- ],
- }, NOW + 1)!
- expect(current.serverOrder).toEqual(["server-a", "server-b"])
-
- current = reduceStructuralSnapshot(current, {
- type: "upsertCategory",
- serverId: "server-a",
- category: { id: "category-2", name: "Later", private: true },
- }, NOW + 2)!
- current = reduceStructuralSnapshot(current, {
- type: "patchCategory",
- serverId: "server-a",
- categoryId: "category-2",
- changes: { name: "First" },
- position: -5,
- }, NOW + 3)!
- current = reduceStructuralSnapshot(current, {
- type: "reorderCategories",
- serverId: "server-a",
- categoryIds: ["category-1", "missing"],
- }, NOW + 4)!
- expect(current.servers[0]?.categories.map((category) => category.id))
- .toEqual(["category-1", "category-2"])
-
- current = reduceStructuralSnapshot(current, {
- type: "upsertChannel",
- serverId: "server-a",
- channel: { id: "channel-c", name: "later", type: "text", categoryId: "category-2" },
- }, NOW + 5)!
- current = reduceStructuralSnapshot(current, {
- type: "patchChannel",
- serverId: "server-a",
- channelId: "channel-c",
- changes: { name: "renamed", type: "forum" },
- }, NOW + 6)!
- current = reduceStructuralSnapshot(current, {
- type: "reorderChannels",
- serverId: "server-a",
- channelIds: ["channel-c", "missing", "channel-a"],
- }, NOW + 7)!
- expect(current.servers[0]?.channels.map((channel) => channel.id))
- .toEqual(["channel-c", "channel-a", "channel-b"])
-
- current = reduceStructuralSnapshot(current, {
- type: "patchChildHint",
- serverId: "server-a",
- channelId: "child-1",
- name: "renamed child",
- }, NOW + 8)!
- expect(current.servers[0]?.childRouteHints[0]?.name).toBe("renamed child")
- current = reduceStructuralSnapshot(current, {
- type: "patchChildHint",
- serverId: "server-a",
- channelId: "child-1",
- }, NOW + 9)!
- expect(current.servers[0]?.childRouteHints[0]?.name).toBe("renamed child")
- current = reduceStructuralSnapshot(current, {
- type: "removeChildHint",
- serverId: "server-a",
- channelId: "child-1",
- }, NOW + 10)!
- expect(current.servers[0]?.childRouteHints).toEqual([])
-
- current = reduceStructuralSnapshot(current, {
- type: "removeCategory",
- serverId: "server-a",
- categoryId: "category-2",
- }, NOW + 11)!
- expect(current.servers[0]?.channels.find((channel) => channel.id === "channel-c")?.categoryId)
- .toBeNull()
-
- current = reduceStructuralSnapshot(current, {
- type: "removeServer",
- serverId: "server-a",
- }, NOW + 12)!
- expect(current.folders).toEqual([{ id: "folder-b", name: "B", serverIds: ["server-b"] }])
- expect(current.servers.map((server) => server.id)).toEqual(["server-b"])
-
- const defaultTimestamp = reduceStructuralSnapshot(current, {
- type: "replaceFolders",
- folders: [],
- })!
- expect(defaultTimestamp.capturedAt).toBeGreaterThanOrEqual(Date.now() - 1_000)
- })
-
- it("updates exactly one QueryClient owner", () => {
- const queryClient = new QueryClient()
- updateStructuralSnapshot(queryClient, {
- type: "replaceServers",
- accountId: "account-a",
- servers: [{ id: "server-a", name: "Alpha", discriminator: "0001", icon: null }],
- }, NOW)
- expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toEqual({
- schemaVersion: 1,
- accountId: "account-a",
- capturedAt: NOW,
- serverOrder: ["server-a"],
- folders: [],
- servers: [{
- id: "server-a",
- name: "Alpha",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [],
- childRouteHints: [],
- }],
- })
- })
-})
-
-describe("structural projections", () => {
- it("drops runtime fields and derives uncategorized channels", () => {
- const tree = projectServerDetailTree({
- categories: [
- {
- id: "category-1",
- name: "General",
- private: 1,
- creatorId: "creator-1",
- channels: [{
- id: "channel-a",
- name: "chat",
- type: "text",
- topic: "secret",
- unread: true,
- }],
- },
- {
- id: "__uncategorized__",
- name: "",
- channels: [{ id: "channel-b", name: "ideas", type: "forum" }],
- },
- {
- id: "tmp_cat_1",
- name: "Pending",
- pending: true,
- channels: [{ id: "tmp_ch_1", name: "Pending", type: "text", pending: true }],
- },
- ],
- })
- expect(tree).toEqual({
- categories: [{ id: "category-1", name: "General", private: true }],
- channels: [
- { id: "channel-a", name: "chat", type: "text", categoryId: "category-1" },
- { id: "channel-b", name: "ideas", type: "forum", categoryId: null },
- ],
- })
- const projected = structuralServerToCategories({
- ...snapshot().servers[0]!,
- ...tree,
- })
- expect(projected.map((category) => category.id)).toEqual(["category-1", "__uncategorized__"])
- })
-
- it("projects ordered rail, folder references, and top-level directory", () => {
- const value = snapshot()
- expect(structuralSnapshotServers(value).map((server) => server.id)).toEqual(["server-b", "server-a"])
- expect(structuralSnapshotFolders(value)[0]?.servers.map((server) => server.id)).toEqual(["server-a"])
- expect(structuralSnapshotDirectory(value)[0]?.channels.map((channel) => channel.id)).toEqual([
- "channel-a",
- "channel-b",
- ])
- })
-})
diff --git a/src/web/src/lib/community/structural-snapshot.ts b/src/web/src/lib/community/structural-snapshot.ts
deleted file mode 100644
index d409f82b0..000000000
--- a/src/web/src/lib/community/structural-snapshot.ts
+++ /dev/null
@@ -1,642 +0,0 @@
-import type { QueryClient } from "@tanstack/react-query"
-import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
-import { avatarInitial } from "@/lib/community/avatar"
-import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
-import type {
- Category,
- CommunityFolder,
- Server,
-} from "@/lib/community/models/navigation"
-import { communityKeys } from "@/lib/query-keys"
-
-const STRUCTURAL_SNAPSHOT_VERSION = 1 as const
-export const STRUCTURAL_SNAPSHOT_TTL_MS = 24 * 60 * 60 * 1000
-export const STRUCTURAL_SNAPSHOT_CHILD_LIMIT = 32
-
-export type StructuralCategoryV1 = {
- id: string
- name: string
- private: boolean
-}
-
-export type StructuralChannelV1 = {
- id: string
- name: string
- type: "text" | "forum"
- categoryId: string | null
-}
-
-type StructuralChildRouteHintV1 = {
- id: string
- name: string
- type: "thread"
- parentChannelId: string
- parentMessageId: string
-}
-
-export type StructuralServerV1 = {
- id: string
- name: string
- discriminator: string
- icon: string | null
- categories: StructuralCategoryV1[]
- channels: StructuralChannelV1[]
- childRouteHints: StructuralChildRouteHintV1[]
-}
-
-export type StructuralSnapshotV1 = {
- schemaVersion: 1
- accountId: string
- capturedAt: number
- serverOrder: string[]
- folders: Array<{
- id: string
- name: string
- serverIds: string[]
- }>
- servers: StructuralServerV1[]
-}
-
-export type StructuralSnapshotEvent =
- | {
- type: "replaceServers"
- accountId: string
- servers: Array<Pick<StructuralServerV1, "id" | "name" | "discriminator" | "icon">>
- }
- | {
- type: "replaceFolders"
- folders: Array<{ id: string; name: string; serverIds: string[] }>
- }
- | {
- type: "replaceServerTree"
- serverId: string
- categories: StructuralCategoryV1[]
- channels: StructuralChannelV1[]
- }
- | {
- type: "replaceRail"
- serverOrder: string[]
- folders: Array<{ id: string; name: string; serverIds: string[] }>
- }
- | {
- type: "patchServer"
- serverId: string
- changes: Partial<Pick<StructuralServerV1, "name" | "icon">>
- }
- | { type: "removeServer"; serverId: string }
- | {
- type: "upsertCategory"
- serverId: string
- category: StructuralCategoryV1
- position?: number
- }
- | {
- type: "patchCategory"
- serverId: string
- categoryId: string
- changes: Partial<Pick<StructuralCategoryV1, "name" | "private">>
- position?: number
- }
- | { type: "removeCategory"; serverId: string; categoryId: string }
- | {
- type: "reorderCategories"
- serverId: string
- categoryIds: string[]
- }
- | {
- type: "upsertChannel"
- serverId: string
- channel: StructuralChannelV1
- position?: number
- }
- | {
- type: "patchChannel"
- serverId: string
- channelId: string
- changes: Partial<Pick<StructuralChannelV1, "name" | "type" | "categoryId">>
- }
- | { type: "removeChannel"; serverId: string; channelId: string }
- | {
- type: "reorderChannels"
- serverId: string
- channelIds: string[]
- }
- | {
- type: "upsertChildHint"
- serverId: string
- child: StructuralChildRouteHintV1
- }
- | {
- type: "patchChildHint"
- serverId: string
- channelId: string
- name?: string
- }
- | { type: "removeChildHint"; serverId: string; channelId: string }
-
-type ServerDetailSource = {
- categories: Array<{
- id: string
- name: string
- private?: boolean | number
- pending?: boolean
- channels: Array<{
- id: string
- name: string
- type?: string
- pending?: boolean
- }>
- }>
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value)
-}
-
-function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
- const actual = Object.keys(value).sort()
- const expected = [...keys].sort()
- return actual.length === expected.length
- && actual.every((key, index) => key === expected[index])
-}
-
-function isSafeId(value: unknown): value is string {
- return typeof value === "string"
- && value.length > 0
- && !value.startsWith("tmp_")
- && !value.startsWith("temp_")
-}
-
-function isString(value: unknown): value is string {
- return typeof value === "string"
-}
-
-function unique(values: readonly string[]): boolean {
- return new Set(values).size === values.length
-}
-
-function parseCategory(value: unknown): StructuralCategoryV1 | null {
- if (!isRecord(value) || !hasExactKeys(value, ["id", "name", "private"])) return null
- if (!isSafeId(value.id) || !isString(value.name) || typeof value.private !== "boolean") return null
- return { id: value.id, name: value.name, private: value.private }
-}
-
-function parseChannel(value: unknown): StructuralChannelV1 | null {
- if (!isRecord(value) || !hasExactKeys(value, ["id", "name", "type", "categoryId"])) return null
- if (!isSafeId(value.id) || !isString(value.name)) return null
- if (value.type !== "text" && value.type !== "forum") return null
- if (value.categoryId !== null && !isSafeId(value.categoryId)) return null
- return {
- id: value.id,
- name: value.name,
- type: value.type,
- categoryId: value.categoryId,
- }
-}
-
-function parseChild(value: unknown): StructuralChildRouteHintV1 | null {
- if (!isRecord(value) || !hasExactKeys(value, [
- "id",
- "name",
- "type",
- "parentChannelId",
- "parentMessageId",
- ])) return null
- if (
- !isSafeId(value.id)
- || !isString(value.name)
- || value.type !== "thread"
- || !isSafeId(value.parentChannelId)
- || !isSafeId(value.parentMessageId)
- ) return null
- return {
- id: value.id,
- name: value.name,
- type: "thread",
- parentChannelId: value.parentChannelId,
- parentMessageId: value.parentMessageId,
- }
-}
-
-function parseServer(value: unknown): StructuralServerV1 | null {
- if (!isRecord(value) || !hasExactKeys(value, [
- "id",
- "name",
- "discriminator",
- "icon",
- "categories",
- "channels",
- "childRouteHints",
- ])) return null
- if (
- !isSafeId(value.id)
- || !isString(value.name)
- || !isString(value.discriminator)
- || (value.icon !== null && !isString(value.icon))
- || !Array.isArray(value.categories)
- || !Array.isArray(value.channels)
- || !Array.isArray(value.childRouteHints)
- || value.childRouteHints.length > STRUCTURAL_SNAPSHOT_CHILD_LIMIT
- ) return null
- const categories = value.categories.map(parseCategory)
- const channels = value.channels.map(parseChannel)
- const children = value.childRouteHints.map(parseChild)
- if (categories.some((row) => row === null)
- || channels.some((row) => row === null)
- || children.some((row) => row === null)) return null
- const parsedCategories = categories as StructuralCategoryV1[]
- const parsedChannels = channels as StructuralChannelV1[]
- const parsedChildren = children as StructuralChildRouteHintV1[]
- const categoryIds = parsedCategories.map((row) => row.id)
- const channelIds = parsedChannels.map((row) => row.id)
- const childIds = parsedChildren.map((row) => row.id)
- if (!unique(categoryIds) || !unique(channelIds) || !unique(childIds)) return null
- const categorySet = new Set(categoryIds)
- const channelSet = new Set(channelIds)
- if (parsedChannels.some((row) => row.categoryId !== null && !categorySet.has(row.categoryId))) return null
- if (parsedChildren.some((row) => !channelSet.has(row.parentChannelId))) return null
- if ([...channelIds, ...childIds].some((id, index, all) => all.indexOf(id) !== index)) return null
- return {
- id: value.id,
- name: value.name,
- discriminator: value.discriminator,
- icon: value.icon,
- categories: parsedCategories,
- channels: parsedChannels,
- childRouteHints: parsedChildren,
- }
-}
-
-export function parseStructuralSnapshot(
- value: unknown,
- accountId: string,
- now = Date.now(),
-): StructuralSnapshotV1 | null {
- if (!accountId || !isRecord(value) || !hasExactKeys(value, [
- "schemaVersion",
- "accountId",
- "capturedAt",
- "serverOrder",
- "folders",
- "servers",
- ])) return null
- if (
- value.schemaVersion !== STRUCTURAL_SNAPSHOT_VERSION
- || value.accountId !== accountId
- || typeof value.capturedAt !== "number"
- || !Number.isFinite(value.capturedAt)
- || value.capturedAt < 0
- || value.capturedAt > now
- || now - value.capturedAt > STRUCTURAL_SNAPSHOT_TTL_MS
- || !Array.isArray(value.serverOrder)
- || !Array.isArray(value.folders)
- || !Array.isArray(value.servers)
- ) return null
- if (!value.serverOrder.every(isSafeId) || !unique(value.serverOrder)) return null
- const serverOrder = value.serverOrder as string[]
- const servers = value.servers.map(parseServer)
- if (servers.some((server) => server === null)) return null
- const parsedServers = servers as StructuralServerV1[]
- const serverIds = parsedServers.map((server) => server.id)
- if (!unique(serverIds)
- || serverIds.length !== serverOrder.length
- || serverIds.some((id) => !serverOrder.includes(id))) return null
- const serverSet = new Set(serverIds)
- const claimed = new Set<string>()
- const folders: StructuralSnapshotV1["folders"] = []
- for (const valueFolder of value.folders) {
- if (!isRecord(valueFolder) || !hasExactKeys(valueFolder, ["id", "name", "serverIds"])) return null
- if (!isSafeId(valueFolder.id) || !isString(valueFolder.name) || !Array.isArray(valueFolder.serverIds)) return null
- if (!valueFolder.serverIds.every(isSafeId)
- || !unique(valueFolder.serverIds)
- || valueFolder.serverIds.some((id) => !serverSet.has(id) || claimed.has(id))) return null
- for (const id of valueFolder.serverIds) claimed.add(id)
- folders.push({ id: valueFolder.id, name: valueFolder.name, serverIds: [...valueFolder.serverIds] })
- }
- if (!unique(folders.map((folder) => folder.id))) return null
- return {
- schemaVersion: STRUCTURAL_SNAPSHOT_VERSION,
- accountId,
- capturedAt: value.capturedAt,
- serverOrder: [...serverOrder],
- folders,
- servers: parsedServers,
- }
-}
-
-function moveToPosition<T>(values: readonly T[], value: T, position?: number): T[] {
- const next = [...values]
- const index = position === undefined
- ? next.length
- : Math.max(0, Math.min(Math.trunc(position), next.length))
- next.splice(index, 0, value)
- return next
-}
-
-function orderByIds<T extends { id: string }>(values: readonly T[], ids: readonly string[]): T[] {
- const byId = new Map(values.map((value) => [value.id, value]))
- const ordered = ids.flatMap((id) => {
- const value = byId.get(id)
- if (!value) return []
- byId.delete(id)
- return [value]
- })
- return [...ordered, ...byId.values()]
-}
-
-function withServer(
- snapshot: StructuralSnapshotV1,
- serverId: string,
- update: (server: StructuralServerV1) => StructuralServerV1,
- now: number,
-): StructuralSnapshotV1 {
- let changed = false
- const servers = snapshot.servers.map((server) => {
- if (server.id !== serverId) return server
- const next = update(server)
- changed = changed || next !== server
- return next
- })
- return changed ? { ...snapshot, capturedAt: now, servers } : snapshot
-}
-
-function normalizedFolders(
- snapshot: StructuralSnapshotV1,
- folders: StructuralSnapshotV1["folders"],
-): StructuralSnapshotV1["folders"] {
- const serverIds = new Set(snapshot.serverOrder)
- const claimed = new Set<string>()
- const folderIds = new Set<string>()
- return folders.flatMap((folder) => {
- if (!isSafeId(folder.id) || !isString(folder.name) || folderIds.has(folder.id)) return []
- folderIds.add(folder.id)
- const ids = folder.serverIds.filter((id) => {
- if (!serverIds.has(id) || claimed.has(id)) return false
- claimed.add(id)
- return true
- })
- return [{ id: folder.id, name: folder.name, serverIds: ids }]
- })
-}
-
-export function reduceStructuralSnapshot(
- current: StructuralSnapshotV1 | undefined,
- event: StructuralSnapshotEvent,
- now = Date.now(),
-): StructuralSnapshotV1 | undefined {
- if (event.type === "replaceServers") {
- const previous = current?.accountId === event.accountId ? current : undefined
- const previousById = new Map(previous?.servers.map((server) => [server.id, server]) ?? [])
- const servers = event.servers
- .filter((server) => isSafeId(server.id))
- .filter((server, index, all) => all.findIndex((candidate) => candidate.id === server.id) === index)
- .map((server) => ({
- id: server.id,
- name: server.name,
- discriminator: server.discriminator,
- icon: server.icon,
- categories: previousById.get(server.id)?.categories ?? [],
- channels: previousById.get(server.id)?.channels ?? [],
- childRouteHints: previousById.get(server.id)?.childRouteHints ?? [],
- }))
- const snapshot: StructuralSnapshotV1 = {
- schemaVersion: STRUCTURAL_SNAPSHOT_VERSION,
- accountId: event.accountId,
- capturedAt: now,
- serverOrder: servers.map((server) => server.id),
- folders: [],
- servers,
- }
- snapshot.folders = normalizedFolders(snapshot, previous?.folders ?? [])
- return snapshot
- }
- if (!current) return current
- if (event.type === "replaceFolders") {
- return { ...current, capturedAt: now, folders: normalizedFolders(current, event.folders) }
- }
- if (event.type === "replaceRail") {
- const known = new Set(current.serverOrder)
- const serverOrder = event.serverOrder.filter(
- (id, index, values) => known.has(id) && values.indexOf(id) === index,
- )
- for (const id of current.serverOrder) if (!serverOrder.includes(id)) serverOrder.push(id)
- const next = { ...current, capturedAt: now, serverOrder }
- return { ...next, folders: normalizedFolders(next, event.folders) }
- }
- if (event.type === "removeServer") {
- if (!current.serverOrder.includes(event.serverId)) return current
- return {
- ...current,
- capturedAt: now,
- serverOrder: current.serverOrder.filter((id) => id !== event.serverId),
- folders: current.folders.flatMap((folder) => {
- const serverIds = folder.serverIds.filter((id) => id !== event.serverId)
- return serverIds.length > 0 ? [{ ...folder, serverIds }] : []
- }),
- servers: current.servers.filter((server) => server.id !== event.serverId),
- }
- }
- if (event.type === "patchServer") {
- return withServer(current, event.serverId, (server) => ({ ...server, ...event.changes }), now)
- }
- if (event.type === "replaceServerTree") {
- return withServer(current, event.serverId, (server) => ({
- ...server,
- categories: event.categories,
- channels: event.channels,
- childRouteHints: server.childRouteHints.filter((child) =>
- event.channels.some((channel) => channel.id === child.parentChannelId)),
- }), now)
- }
- if (event.type === "upsertCategory") {
- return withServer(current, event.serverId, (server) => {
- const without = server.categories.filter((category) => category.id !== event.category.id)
- return { ...server, categories: moveToPosition(without, event.category, event.position) }
- }, now)
- }
- if (event.type === "patchCategory") {
- return withServer(current, event.serverId, (server) => {
- const existing = server.categories.find((category) => category.id === event.categoryId)
- if (!existing) return server
- const category = { ...existing, ...event.changes }
- const categories = server.categories.filter((row) => row.id !== event.categoryId)
- return {
- ...server,
- categories: event.position === undefined
- ? server.categories.map((row) => row.id === event.categoryId ? category : row)
- : moveToPosition(categories, category, event.position),
- }
- }, now)
- }
- if (event.type === "removeCategory") {
- return withServer(current, event.serverId, (server) => ({
- ...server,
- categories: server.categories.filter((category) => category.id !== event.categoryId),
- channels: server.channels.map((channel) =>
- channel.categoryId === event.categoryId ? { ...channel, categoryId: null } : channel),
- }), now)
- }
- if (event.type === "reorderCategories") {
- return withServer(current, event.serverId, (server) => ({
- ...server,
- categories: orderByIds(server.categories, event.categoryIds),
- }), now)
- }
- if (event.type === "upsertChannel") {
- return withServer(current, event.serverId, (server) => {
- const without = server.channels.filter((channel) => channel.id !== event.channel.id)
- return { ...server, channels: moveToPosition(without, event.channel, event.position) }
- }, now)
- }
- if (event.type === "patchChannel") {
- return withServer(current, event.serverId, (server) => ({
- ...server,
- channels: server.channels.map((channel) =>
- channel.id === event.channelId ? { ...channel, ...event.changes } : channel),
- }), now)
- }
- if (event.type === "reorderChannels") {
- return withServer(current, event.serverId, (server) => ({
- ...server,
- channels: orderByIds(server.channels, event.channelIds),
- }), now)
- }
- if (event.type === "removeChannel") {
- return withServer(current, event.serverId, (server) => ({
- ...server,
- channels: server.channels.filter((channel) => channel.id !== event.channelId),
- childRouteHints: server.childRouteHints.filter((child) =>
- child.id !== event.channelId && child.parentChannelId !== event.channelId),
- }), now)
- }
- if (event.type === "upsertChildHint") {
- return withServer(current, event.serverId, (server) => {
- if (!server.channels.some((channel) => channel.id === event.child.parentChannelId)) return server
- const childRouteHints = [
- event.child,
- ...server.childRouteHints.filter((child) => child.id !== event.child.id),
- ].slice(0, STRUCTURAL_SNAPSHOT_CHILD_LIMIT)
- return { ...server, childRouteHints }
- }, now)
- }
- if (event.type === "patchChildHint") {
- return withServer(current, event.serverId, (server) => ({
- ...server,
- childRouteHints: server.childRouteHints.map((child) =>
- child.id === event.channelId && event.name !== undefined
- ? { ...child, name: event.name }
- : child),
- }), now)
- }
- return withServer(current, event.serverId, (server) => ({
- ...server,
- childRouteHints: server.childRouteHints.filter((child) => child.id !== event.channelId),
- }), now)
-}
-
-export function updateStructuralSnapshot(
- queryClient: QueryClient,
- event: StructuralSnapshotEvent,
- now = Date.now(),
-): void {
- queryClient.setQueryData<StructuralSnapshotV1 | undefined>(
- communityKeys.structuralSnapshot(),
- (current) => reduceStructuralSnapshot(current, event, now),
- )
-}
-
-export function projectServerDetailTree(detail: ServerDetailSource): {
- categories: StructuralCategoryV1[]
- channels: StructuralChannelV1[]
-} {
- const categories: StructuralCategoryV1[] = []
- const channels: StructuralChannelV1[] = []
- for (const category of detail.categories) {
- if (category.pending || !isSafeId(category.id)) continue
- const uncategorized = category.id === UNCATEGORIZED_CATEGORY_ID || category.name === ""
- if (!uncategorized) {
- categories.push({
- id: category.id,
- name: category.name,
- private: category.private === true || category.private === 1,
- })
- }
- for (const channel of category.channels) {
- if (channel.pending || !isSafeId(channel.id)) continue
- if (channel.type !== "text" && channel.type !== "forum") continue
- channels.push({
- id: channel.id,
- name: channel.name,
- type: channel.type,
- categoryId: uncategorized ? null : category.id,
- })
- }
- }
- return { categories, channels }
-}
-
-export function structuralServerToCategories(server: StructuralServerV1): Category[] {
- const categories: Category[] = server.categories.map((category) => ({
- id: category.id,
- name: category.name,
- private: category.private,
- channels: server.channels
- .filter((channel) => channel.categoryId === category.id)
- .map((channel) => ({ ...channel, active: false, unread: false })),
- }))
- const uncategorized = server.channels
- .filter((channel) => channel.categoryId === null)
- .map((channel) => ({ ...channel, active: false, unread: false }))
- if (uncategorized.length > 0) {
- categories.push({
- id: UNCATEGORIZED_CATEGORY_ID,
- name: "",
- private: false,
- channels: uncategorized,
- })
- }
- return categories
-}
-
-export function structuralSnapshotServers(snapshot: StructuralSnapshotV1 | null): Server[] {
- if (!snapshot) return []
- const byId = new Map(snapshot.servers.map((server) => [server.id, server]))
- return snapshot.serverOrder.flatMap((id) => {
- const server = byId.get(id)
- if (!server) return []
- return [{
- id: server.id,
- name: server.name,
- discriminator: server.discriminator,
- icon: server.icon,
- initial: avatarInitial(server.name),
- active: false,
- unread: false,
- mentions: 0,
- }]
- })
-}
-
-export function structuralSnapshotFolders(snapshot: StructuralSnapshotV1 | null): CommunityFolder[] {
- if (!snapshot) return []
- const byId = new Map(structuralSnapshotServers(snapshot).map((server) => [server.id, server]))
- return snapshot.folders.map((folder, position) => ({
- id: folder.id,
- name: folder.name,
- position,
- servers: folder.serverIds.flatMap((id) => {
- const server = byId.get(id)
- return server ? [{ id, name: server.name, initial: server.initial, icon: server.icon }] : []
- }),
- }))
-}
-
-export function structuralSnapshotDirectory(snapshot: StructuralSnapshotV1 | null): ChannelRefDirectory {
- if (!snapshot) return []
- return snapshot.servers.map((server) => ({
- id: server.id,
- name: server.name,
- discriminator: server.discriminator,
- channels: server.channels.map((channel) => ({ id: channel.id, name: channel.name })),
- }))
-}
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index f2fa385d8..cac3fd211 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -85,7 +85,6 @@ describe("community QA selectors", () => {
expect(tid.memberRow("member_1")).toBe("community-member-row-member_1")
expect(tid.composerFileInput).toBe("community-composer-file-input")
expect(tid.messageScroller).toBe("community-message-scroller")
- expect(tid.initialPositionAurora).toBe("community-initial-position-aurora")
expect(tid.reactionGroup("message_1")).toBe("community-reaction-group-message_1")
expect(tid.reactionChip("message_1", "🔥"))
.toBe("community-reaction-chip-message_1-%F0%9F%94%A5")
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 18bf63e98..ca3706116 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -11,7 +11,6 @@ export const tid = {
scrollToPresent: "community-scroll-to-present",
messageSelectionToolbar: "community-message-selection-toolbar",
messageScroller: "community-message-scroller",
- initialPositionAurora: "community-initial-position-aurora",
wsReconnectOverlay: "community-ws-reconnect-overlay",
wsRetry: "community-ws-retry",
initialFrame: "community-initial-frame",
diff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.ts
index c94ce30ea..69dc7b6d0 100644
--- a/src/web/src/lib/middleware/auth.test.ts
+++ b/src/web/src/lib/middleware/auth.test.ts
@@ -25,9 +25,10 @@ vi.mock("@alook/shared", () => ({
}));
const mockGetSession = vi.fn();
+const mockSignOut = vi.fn();
vi.mock("@/lib/auth", () => ({
- createAuth: vi.fn(() => ({
- api: { getSession: mockGetSession },
+ getAuth: vi.fn(() => ({
+ api: { getSession: mockGetSession, signOut: mockSignOut },
})),
}));
@@ -100,7 +101,7 @@ describe("withAuth middleware", () => {
});
it("rejects a crk_ runner-key bearer — a bot never authenticates as a human here (§5 red line)", async () => {
- // Privilege-escalation red line (plans/22 §5): the human-only community
+ // Privilege-escalation invariant: the human-only community
// surfaces (/bots/*, /daemon/*, human inbox, channel management) stay on
// withAuth, NOT withCommunityActor. A crk_ bearer is neither an al_ machine
// token nor a session, so it falls through to the session path and finds no
@@ -135,6 +136,31 @@ describe("withAuth middleware", () => {
expect(testHandler).toHaveBeenCalledOnce();
});
+ it("keeps concurrent cookie sessions request-local", async () => {
+ mockGetSession.mockImplementation(async ({ headers }: { headers: Headers }) => {
+ const id = headers.get("Cookie")?.split("=")[1] ?? "missing";
+ return {
+ headers: new Headers({ "Set-Cookie": `viewer=${id}; Path=/` }),
+ response: { user: { id, email: `${id}@example.com` } },
+ };
+ });
+
+ const [first, second] = await Promise.all([
+ wrapped(new NextRequest("http://localhost/api/test", {
+ headers: { Cookie: "viewer=user-a" },
+ })),
+ wrapped(new NextRequest("http://localhost/api/test", {
+ headers: { Cookie: "viewer=user-b" },
+ })),
+ ]);
+ const [firstBody, secondBody] = await Promise.all([first.json(), second.json()]);
+
+ expect(firstBody.ctx.userId).toBe("user-a");
+ expect(secondBody.ctx.userId).toBe("user-b");
+ expect(first.headers.get("Set-Cookie")).toContain("viewer=user-a");
+ expect(second.headers.get("Set-Cookie")).toContain("viewer=user-b");
+ });
+
it("rejects a session whose user carries isBot=true (guard reads it off the session user, no getUserInternal)", async () => {
mockGetSession.mockResolvedValue({
headers: new Headers(),
@@ -164,6 +190,7 @@ describe("withAuth middleware", () => {
expect(res.status).toBe(401);
expect((await res.json()).error).toBe("session no longer valid");
+ expect(mockSignOut).toHaveBeenCalledWith({ headers: req.headers });
expect(testHandler).not.toHaveBeenCalled();
});
diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.ts
index b7e935ef8..fd67fb9d0 100644
--- a/src/web/src/lib/middleware/auth.ts
+++ b/src/web/src/lib/middleware/auth.ts
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries } from "@alook/shared"
import { getDb, getPrimaryDb } from "@/lib/db"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
import { getKV, cacheKeys, bindCacheKV } from "@/lib/cache"
export interface AuthContext {
@@ -14,8 +14,7 @@ export interface AuthContext {
* The authenticated user's internal flags. Populated from the request-time
* session guard. `isBot` is always false in production (a bot session is
* rejected at 401 before the handler runs), but friend-graph routes assert
- * `ctx.user?.isBot` locally as belt-and-suspenders — see
- * plans/agent-friendship-approval-gate.md §Hardening.
+ * `ctx.user?.isBot` locally as belt-and-suspenders.
*/
user?: { isBot: boolean }
}
@@ -133,7 +132,7 @@ async function resolveSession(
req: NextRequest,
cloudflareEnv: Env,
): Promise<SessionResolution> {
- const auth = createAuth(cloudflareEnv)
+ const auth = getAuth(cloudflareEnv)
let sessionResult: { headers: Headers; response: Awaited<ReturnType<typeof auth.api.getSession>> } | null = null
let lastErr: unknown
diff --git a/src/web/src/lib/middleware/community-actor.test.ts b/src/web/src/lib/middleware/community-actor.test.ts
index 8ebaf05ee..42de41d58 100644
--- a/src/web/src/lib/middleware/community-actor.test.ts
+++ b/src/web/src/lib/middleware/community-actor.test.ts
@@ -66,11 +66,11 @@ describe("withCommunityActor", () => {
it("a crk_ bearer that fails to resolve returns the error response and NEVER falls through to human", async () => {
mockResolveBotActor.mockResolvedValue({
kind: "error",
- response: NextResponse.json({ error: "runner key revoked or unknown" }, { status: 401 }),
+ response: NextResponse.json({ error: "runner key revoked or unrecognized" }, { status: 401 }),
})
const res = await wrapped(bearer("Bearer crk_bad"))
expect(res.status).toBe(401)
- expect(await res.json()).toEqual({ error: "runner key revoked or unknown" })
+ expect(await res.json()).toEqual({ error: "runner key revoked or unrecognized" })
// The human path must not have run — handler saw no human actor.
expect(handler).not.toHaveBeenCalled()
})
diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.ts
index e25461b62..ef9379cdc 100644
--- a/src/web/src/lib/middleware/community-actor.ts
+++ b/src/web/src/lib/middleware/community-actor.ts
@@ -11,8 +11,7 @@ import { resolveBotActor } from "./community-agent-runner-auth"
* pre-existing wrappers (`withAuth` for humans, `withAgentRunnerAuth` for bots)
* behind one decorator so a route can serve both callers and branch on
* `actor.kind` for the few genuinely bot-specific semantics (channel-alignment
- * gate on send, invite owner-gate on join) — see
- * plans/22-community-unified-actor-route-unify.md.
+ * gate on send, invite owner-gate on join).
*
* Discriminated on `kind` (NOT a flat `isBot` boolean): the semantic branches
* read `actor.kind === "bot"` and, in that arm, `ownerUserId`/`machineId` are
diff --git a/src/web/src/lib/middleware/community-agent-runner-auth.ts b/src/web/src/lib/middleware/community-agent-runner-auth.ts
index 477017f97..d05d1b240 100644
--- a/src/web/src/lib/middleware/community-agent-runner-auth.ts
+++ b/src/web/src/lib/middleware/community-agent-runner-auth.ts
@@ -8,8 +8,8 @@ const log = createLogger({ service: "community-agent-runner-auth" })
* The bot identity resolved from a `crk_` runner key — the BOT's own user id,
* its OWNER's user id, and the machine it's bound to. Consumed by the unified
* `withCommunityActor` (see community-actor.ts). The legacy `withAgentRunnerAuth`
- * wrapper and the `/api/community/agent/*` route tree it guarded were deleted in
- * plans/22 §9 phase 5 once every bot verb moved onto the unified actor;
+ * wrapper and the `/api/community/agent/*` route tree it guarded were deleted
+ * once every bot verb moved onto the unified actor;
* `resolveBotActor` is the surviving, shared crk_ validator.
*/
export interface ResolvedBotActor {
@@ -102,7 +102,7 @@ export async function resolveBotActor(
if (!rowLookup.ok) return { kind: "error", response: rowLookup.response }
const row = rowLookup.value
if (!row) {
- return { kind: "error", response: NextResponse.json({ error: "runner key revoked or unknown" }, { status: 401 }) }
+ return { kind: "error", response: NextResponse.json({ error: "runner key revoked or unrecognized" }, { status: 401 }) }
}
const botLookup = await lookupOr503("getUserInternal", () =>
diff --git a/src/web/src/lib/middleware/community-daemon-auth.test.ts b/src/web/src/lib/middleware/community-daemon-auth.test.ts
index 75fb3882e..43098d699 100644
--- a/src/web/src/lib/middleware/community-daemon-auth.test.ts
+++ b/src/web/src/lib/middleware/community-daemon-auth.test.ts
@@ -53,7 +53,7 @@ describe("withCommunityDaemonAuth", () => {
})
const res = await wrapped(req)
expect(res.status).toBe(401)
- expect(await res.json()).toEqual({ error: "credential revoked or unknown" })
+ expect(await res.json()).toEqual({ error: "credential revoked or unrecognized" })
})
it("passes { userId, machineId, credentialId } to the handler on valid credential", async () => {
diff --git a/src/web/src/lib/middleware/community-daemon-auth.ts b/src/web/src/lib/middleware/community-daemon-auth.ts
index 76df45f6e..f8d39ba1d 100644
--- a/src/web/src/lib/middleware/community-daemon-auth.ts
+++ b/src/web/src/lib/middleware/community-daemon-auth.ts
@@ -53,7 +53,7 @@ export function withCommunityDaemonAuth(handler: CommunityDaemonAuthenticatedHan
{ route: "community/daemon-auth:credential" }
)
if (!active) {
- return NextResponse.json({ error: "credential revoked or unknown" }, { status: 401 })
+ return NextResponse.json({ error: "credential revoked or unrecognized" }, { status: 401 })
}
return handler(req, {
diff --git a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts b/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts
index d55d12396..2e1d1fc20 100644
--- a/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts
+++ b/src/web/src/lib/native-oauth-authenticated-cleanup.test.ts
@@ -189,12 +189,14 @@ describe("cleanupAuthenticatedNativeOauthResidue", () => {
it("mounts only behind both authenticated layout gates", () => {
const appLayout = readFileSync(new URL("../app/(app)/layout.tsx", import.meta.url), "utf8")
const communityLayout = readFileSync(new URL("../app/c/layout.tsx", import.meta.url), "utf8")
+ const communityClient = readFileSync(new URL("../app/c/community-layout-client.tsx", import.meta.url), "utf8")
expect(appLayout.indexOf("if (!session) redirect")).toBeLessThan(
appLayout.indexOf("<AuthenticatedNativeOauthCleanup />"),
)
- expect(communityLayout.indexOf("if (isPending || !session)")).toBeLessThan(
- communityLayout.indexOf("<AuthenticatedNativeOauthCleanup />"),
+ expect(communityLayout).toContain("await getSession()")
+ expect(communityClient.indexOf("if (!currentUser)")).toBeLessThan(
+ communityClient.indexOf("<AuthenticatedNativeOauthCleanup />"),
)
})
})
diff --git a/src/web/src/lib/perf/perf-gate.ts b/src/web/src/lib/perf/perf-gate.ts
index ffb86ea90..30021cb50 100644
--- a/src/web/src/lib/perf/perf-gate.ts
+++ b/src/web/src/lib/perf/perf-gate.ts
@@ -1,7 +1,7 @@
/**
* Single source of truth for whether local perf instrumentation is armed.
*
- * Double-gated on purpose (see plans/community-switch-perf-diagnosis.md):
+ * Double-gated on purpose:
* - `NEXT_PUBLIC_PERF_TRACE === "1"` — opt-in flag, off by default.
* - `NODE_ENV !== "production"` — a hard backstop so a stray flag in a prod
* env can never arm the instrument or pull `react-scan` into a live build.
diff --git a/src/web/src/lib/perf/react-scan-install.ts b/src/web/src/lib/perf/react-scan-install.ts
index 3f4f9fb8b..646206d20 100644
--- a/src/web/src/lib/perf/react-scan-install.ts
+++ b/src/web/src/lib/perf/react-scan-install.ts
@@ -4,8 +4,8 @@ import { pushPerfEvent, type PerfEventRecord, type PerfFiberRecord } from "./per
import type { LiteEvent, LiteFiberSummary, LiteHandle } from "react-scan/lite"
/**
- * Local render instrumentation install. Diagnosis-only (see
- * plans/community-switch-perf-diagnosis.md) — NEVER runs in a real build.
+ * Local render instrumentation install. Diagnosis-only; it never runs in a
+ * real build.
*
* Must run before react-dom installs its DevTools global hook, so this is
* imported from `instrumentation-client.ts` (Next's pre-hydration client
diff --git a/src/web/src/lib/perf/switch-mark.ts b/src/web/src/lib/perf/switch-mark.ts
index 22121154d..2febb6251 100644
--- a/src/web/src/lib/perf/switch-mark.ts
+++ b/src/web/src/lib/perf/switch-mark.ts
@@ -4,7 +4,7 @@ import type { PerfSwitchMark } from "./perf-globals"
/**
* Record a `t=0` anchor at a server/channel switch click site. The Playwright
* perf spec correlates the following network + render events against this mark
- * to compute perceived latency (see plans/community-switch-perf-diagnosis.md).
+ * to compute perceived latency.
*
* Guarded no-op when the perf gate is off, so the two hot-path call sites
* (`setActiveChannel`, `onRailServerNavigate`) add zero cost in real builds.
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 23740c020..1f1670851 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -60,7 +60,9 @@ describe("communityKeys", () => {
it("recognizes only real server-detail keys and server-id segments", () => {
expect(isCommunityServerIdSegment("server-1")).toBe(true)
+ expect(isCommunityServerIdSegment("__real_nanoid")).toBe(true)
expect(isCommunityServerDetailQueryKey(communityKeys.server("server-1"))).toBe(true)
+ expect(isCommunityServerDetailQueryKey(communityKeys.server("__real_nanoid"))).toBe(true)
for (const queryKey of [
communityKeys.channelRefDirectory(),
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 54fc5a7b2..282ec99ff 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -15,11 +15,13 @@
*/
export const communityKeys = {
all: ["community"] as const,
+ communityDb: (accountId: string) =>
+ [...communityKeys.all, "db", accountId] as const,
+ communityDbCollection: (accountId: string, collection: string) =>
+ [...communityKeys.communityDb(accountId), collection] as const,
// ── Servers ──────────────────────────────────────────────────────────────
servers: () => [...communityKeys.all, "servers"] as const,
- structuralSnapshot: () =>
- [...communityKeys.all, "structural-snapshot"] as const,
channelRefDirectory: () =>
[...communityKeys.servers(), "channel-ref-directory"] as const,
server: (serverId: string) =>
@@ -103,6 +105,8 @@ export const communityKeys = {
[...communityKeys.all, "dm", dmId, "read-state-snapshot"] as const,
accountReadStateSnapshot: () =>
[...communityKeys.all, "read-state-snapshot"] as const,
+ accountAttention: () =>
+ [...communityKeys.all, "attention"] as const,
// Single hydrated message (opener block, deep-link previews).
message: (messageId: string) =>
@@ -166,6 +170,8 @@ export const communityKeys = {
const reservedServerIdSegments = new Set<string>([
communityKeys.channelRefDirectory()[2],
+ "__none__",
+ "__pending__",
])
export type CommunityServerDetailQueryKey = ReturnType<typeof communityKeys.server>
@@ -173,7 +179,6 @@ export type CommunityServerDetailQueryKey = ReturnType<typeof communityKeys.serv
export function isCommunityServerIdSegment(value: unknown): value is string {
return typeof value === "string"
&& value.length > 0
- && !value.startsWith("__")
&& !reservedServerIdSegments.has(value)
}
diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.ts
index b82e7b728..e3b4c685c 100644
--- a/src/web/src/lib/query-persister.test.ts
+++ b/src/web/src/lib/query-persister.test.ts
@@ -7,25 +7,34 @@ import { communityKeys } from "@/lib/query-keys"
import {
clearPersistedCache,
createIdbPersister,
- isTrustedMessagesPageZero,
+ MAX_PERSISTED_MESSAGES_PER_SCOPE,
+ MAX_PERSISTED_MESSAGE_SCOPES,
shouldPersistQuery,
shouldPersistQueryKey,
} from "@/lib/query-persister"
-import type { MessagesPage } from "@/lib/community/models/message"
// ── shouldPersistQueryKey ─────────────────────────────────────────────────
describe("shouldPersistQueryKey", () => {
- it("persists channel message queries", () => {
- expect(shouldPersistQueryKey(communityKeys.channelMessages("ch_1"))).toBe(true)
+ it("does not persist channel transport message queries", () => {
+ expect(shouldPersistQueryKey(communityKeys.channelMessages("ch_1"))).toBe(false)
})
- it("persists DM message queries", () => {
- expect(shouldPersistQueryKey(communityKeys.dmMessages("dm_1"))).toBe(true)
+ it("does not persist DM transport message queries", () => {
+ expect(shouldPersistQueryKey(communityKeys.dmMessages("dm_1"))).toBe(false)
})
- it("persists the single structural snapshot query", () => {
- expect(shouldPersistQueryKey(communityKeys.structuralSnapshot())).toBe(true)
+ it("persists account-scoped canonical collections", () => {
+ expect(shouldPersistQueryKey(
+ communityKeys.communityDbCollection("u_1", "channels"),
+ )).toBe(true)
+ })
+
+ it("does not persist raw warm-shell transport queries", () => {
+ expect(shouldPersistQueryKey(communityKeys.servers())).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.folders())).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.dms())).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.server("srv_1"))).toBe(false)
})
it("does NOT persist channel read-state snapshot (refetched on every mount)", () => {
@@ -40,16 +49,27 @@ describe("shouldPersistQueryKey", () => {
).toBe(false)
})
- it("does NOT persist server list, presence, members, or machines", () => {
- expect(shouldPersistQueryKey(communityKeys.servers())).toBe(false)
+ it("does NOT persist presence, members, sentinels, or unrelated account data", () => {
expect(shouldPersistQueryKey(communityKeys.presence("srv_1"))).toBe(false)
expect(shouldPersistQueryKey(communityKeys.members("srv_1"))).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.server("__none__"))).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.server("__pending__"))).toBe(false)
expect(shouldPersistQueryKey(communityKeys.machines())).toBe(false)
expect(shouldPersistQueryKey(communityKeys.friends())).toBe(false)
- expect(shouldPersistQueryKey(communityKeys.dms())).toBe(false)
expect(shouldPersistQueryKey(communityKeys.inbox())).toBe(false)
})
+ it("does not restore transient transport state on reload", () => {
+ expect(shouldPersistQueryKey(communityKeys.forumSidebarThreads("srv_1"))).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.channelMeta("srv_1", "thread_1"))).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.message("opener_1"))).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.channelRefDirectory())).toBe(false)
+ expect(shouldPersistQueryKey(communityKeys.presence("srv_1"))).toBe(false)
+ expect(shouldPersistQueryKey(
+ communityKeys.communityDbCollection("u_1", "channels"),
+ )).toBe(true)
+ })
+
it("does NOT persist pins/threads/forum tags (message-related but ephemeral)", () => {
expect(shouldPersistQueryKey(communityKeys.pins("ch_1"))).toBe(false)
expect(shouldPersistQueryKey(communityKeys.threads("ch_1"))).toBe(false)
@@ -64,17 +84,84 @@ describe("shouldPersistQueryKey", () => {
// ── createIdbPersister: serialize scrubbing ───────────────────────────────
-function makePage(messages: Array<Partial<MessagesPage["messages"][number]>>): MessagesPage {
+const validServer = {
+ id: "srv_1",
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ ownerId: "owner_1",
+ initial: "S",
+ active: false,
+ unread: false,
+ mentions: 0,
+ isOwner: true,
+ icon: null,
+ official: false,
+ unreadSources: [{ channelId: "ch_1", lastUnreadSeq: 1 }],
+ mentionSources: [{ channelId: "ch_1", count: 1, lastSeq: 1 }],
+}
+
+const validFolder = {
+ id: "folder_1",
+ name: "Folder",
+ position: 0,
+ servers: [{ id: "srv_1", name: "Server", initial: "S", icon: null }],
+}
+
+const validDm = {
+ id: "dm_1",
+ userId: "peer_1",
+ name: "Peer",
+ discriminator: "0002",
+ avatar: "P",
+ avatarVersion: 1,
+ status: "offline",
+ preview: "hello",
+ unread: false,
+ lastUnreadSeq: 1,
+}
+
+function validServerDetail(id = "srv_1") {
return {
- messages: messages as MessagesPage["messages"],
- hasMore: false,
- latestSeq: 0,
+ id,
+ name: "Server",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ official: false,
+ ownerId: "owner_1",
+ categories: [{
+ id: "cat_1",
+ name: "Channels",
+ private: false,
+ channels: [{
+ id: "ch_1",
+ name: "general",
+ active: false,
+ unread: false,
+ muted: false,
+ type: "text",
+ tags: ["general"],
+ creatorId: null,
+ pending: false,
+ }],
+ creatorId: null,
+ pending: false,
+ }],
+ forumUnreadState: {
+ ch_forum: { baseUnread: false, childIds: ["thread_1"] },
+ },
+ unreadSources: [{
+ channelId: "ch_1",
+ lastUnreadSeq: 1,
+ lastAttentionSeq: null,
+ }],
}
}
async function readPersistedBlob(userId: string | null): Promise<PersistedClient> {
const raw = await get<string>(
- `alook:qc:v1:${userId ?? "anon"}:client`,
+ `alook:qc:v2:${userId ?? "anon"}:client`,
)
if (!raw) throw new Error("no persisted blob")
return JSON.parse(raw) as PersistedClient
@@ -86,15 +173,19 @@ describe("createIdbPersister — serialize filter", () => {
await clearPersistedCache(null)
})
- it("strips temp_* rows from persisted channel message pages", async () => {
+ it("drops channel message pages instead of duplicating canonical messages", async () => {
const qc = new QueryClient()
qc.setQueryData(communityKeys.channelMessages("ch_1"), {
pages: [
- makePage([
- { id: "m_real_1", content: "keep", createdAt: "2026-07-01T00:00:00.000Z" },
- { id: "temp_abc", content: "drop", createdAt: "2026-07-01T00:00:01.000Z" },
- { id: "m_real_2", content: "keep", createdAt: "2026-07-01T00:00:02.000Z" },
- ]),
+ {
+ messages: [
+ { id: "m_real_1", content: "keep", createdAt: "2026-07-01T00:00:00.000Z" },
+ { id: "temp_abc", content: "drop", createdAt: "2026-07-01T00:00:01.000Z" },
+ { id: "m_real_2", content: "keep", createdAt: "2026-07-01T00:00:02.000Z" },
+ ],
+ hasMore: false,
+ latestSeq: 0,
+ },
],
pageParams: [{ mode: "newest" }],
})
@@ -116,27 +207,26 @@ describe("createIdbPersister — serialize filter", () => {
})
const blob = await readPersistedBlob("u_1")
- const q = blob.clientState.queries[0]
- const data = q.state.data as { pages: MessagesPage[] }
- expect(data.pages[0].messages.map((m) => m.id)).toEqual([
- "m_real_1",
- "m_real_2",
- ])
+ expect(blob.clientState.queries).toEqual([])
})
- it("strips failed:true rows from persisted DM message pages", async () => {
+ it("drops DM message pages instead of duplicating canonical messages", async () => {
const qc = new QueryClient()
qc.setQueryData(communityKeys.dmMessages("dm_1"), {
pages: [
- makePage([
- { id: "m_ok", content: "keep", createdAt: "2026-07-01T00:00:00.000Z" },
- {
- id: "m_bad",
- content: "drop",
- createdAt: "2026-07-01T00:00:01.000Z",
- failed: true,
- },
- ]),
+ {
+ messages: [
+ { id: "m_ok", content: "keep", createdAt: "2026-07-01T00:00:00.000Z" },
+ {
+ id: "m_bad",
+ content: "drop",
+ createdAt: "2026-07-01T00:00:01.000Z",
+ failed: true,
+ },
+ ],
+ hasMore: false,
+ latestSeq: 0,
+ },
],
pageParams: [{ mode: "newest" }],
})
@@ -158,230 +248,374 @@ describe("createIdbPersister — serialize filter", () => {
})
const blob = await readPersistedBlob("u_1")
- const q = blob.clientState.queries[0]
- const data = q.state.data as { pages: MessagesPage[] }
- expect(data.pages[0].messages.map((m) => m.id)).toEqual(["m_ok"])
+ expect(blob.clientState.queries).toEqual([])
})
- it("drops message queries whose pages[0] is a since-mode envelope (no hasMore flag on tail)", async () => {
+ it("drops valid raw shell queries and server details", async () => {
const qc = new QueryClient()
- // Simulate a since-mode envelope: only `hasMoreNewer` / `newerCursor` /
- // `latestSeq` — no `hasMore`, no `hasMoreOlder`. If we persisted this,
- // the next mount would compute `hasMoreOlder ?? hasMore ?? false === false`
- // and silently claim there's no more history.
- qc.setQueryData(communityKeys.channelMessages("ch_since"), {
- pages: [
- {
- messages: [
- { id: "m_1", content: "x", createdAt: "2026-07-01T00:00:00.000Z" },
- ],
- hasMoreNewer: true,
- newerCursor: "cur_new",
- latestSeq: 42,
- },
- ],
- pageParams: [{ mode: "since", since: "cur_since" }],
+ qc.setQueryData(communityKeys.servers(), { servers: [validServer] }, { updatedAt: 1 })
+ qc.setQueryData(communityKeys.folders(), { folders: [validFolder] }, { updatedAt: 2 })
+ qc.setQueryData(communityKeys.dms(), { conversations: [validDm] }, { updatedAt: 3 })
+ const detailKeys = Array.from(
+ { length: 2 },
+ (_, index) => communityKeys.server(`srv_${index}`),
+ )
+ detailKeys.forEach((key, index) => {
+ qc.setQueryData(key, validServerDetail(key[2]), { updatedAt: index + 10 })
})
-
- const persister = createIdbPersister("u_1")
- await persister.persistClient({
+ const queryKeys = [
+ communityKeys.servers(),
+ communityKeys.folders(),
+ communityKeys.dms(),
+ ...detailKeys,
+ ]
+
+ await createIdbPersister("u_1").persistClient({
timestamp: Date.now(),
buster: "v1",
clientState: {
mutations: [],
- queries: [
- {
- queryKey: communityKeys.channelMessages("ch_since"),
- queryHash: JSON.stringify(communityKeys.channelMessages("ch_since")),
- state: qc.getQueryState(communityKeys.channelMessages("ch_since"))!,
- },
- ],
+ queries: queryKeys.map((queryKey) => ({
+ queryKey,
+ queryHash: JSON.stringify(queryKey),
+ state: qc.getQueryState(queryKey)!,
+ })),
},
})
const blob = await readPersistedBlob("u_1")
- // The whole query was dropped by scrubDehydratedClient — nothing to
- // rehydrate, so the next mount refetches from scratch (self-healing).
- expect(blob.clientState.queries).toHaveLength(0)
+ expect(blob.clientState.queries.map((query) => query.queryKey)).toEqual([])
})
- it("keeps message queries whose pages[0] is anchor-mode with tail attached (hasMoreNewer=false)", async () => {
+ it("windows canonical server trees, message tails, and referenced profiles", async () => {
const qc = new QueryClient()
- qc.setQueryData(communityKeys.channelMessages("ch_anchor"), {
- pages: [
- {
- messages: [
- { id: "m_1", content: "x", createdAt: "2026-07-01T00:00:00.000Z" },
- ],
- hasMoreOlder: true,
- olderCursor: "cur_older",
- hasMoreNewer: false,
- latestSeq: 42,
- },
- ],
- pageParams: [{ mode: "anchor", anchor: "m_1" }],
+ const detailKeys = Array.from({ length: 7 }, (_, index) => communityKeys.server(`srv_${index}`))
+ detailKeys.forEach((key, index) => {
+ qc.setQueryData(key, validServerDetail(key[2]), { updatedAt: index + 1 })
})
-
- const persister = createIdbPersister("u_1")
- await persister.persistClient({
+ const dmChannels = Array.from({ length: MAX_PERSISTED_MESSAGE_SCOPES + 2 }, (_, index) => ({
+ id: `dm_${index}`,
+ serverId: null,
+ categoryId: null,
+ name: "",
+ type: "dm" as const,
+ parentChannelId: null,
+ parentMessageId: null,
+ creatorId: null,
+ position: 0,
+ archived: false,
+ muted: false,
+ unread: false,
+ tags: [],
+ pending: false,
+ lastMessageAt: null,
+ }))
+ const serverChannels = Array.from({ length: 7 }, (_, index) => ({
+ ...dmChannels[0],
+ id: `ch_${index}`,
+ serverId: `srv_${index}`,
+ type: "text" as const,
+ }))
+ const messages = [...dmChannels.flatMap((channel, scopeIndex) => (
+ Array.from({ length: MAX_PERSISTED_MESSAGES_PER_SCOPE + 1 }, (_, messageIndex) => ({
+ id: `${channel.id}:m_${messageIndex}`,
+ channelId: channel.id,
+ type: "chat" as const,
+ seq: messageIndex,
+ createdAt: `2026-09-${String(scopeIndex + 1).padStart(2, "0")}T00:00:00.000Z`,
+ authorId: `author_${scopeIndex}`,
+ ...(scopeIndex === MAX_PERSISTED_MESSAGE_SCOPES + 1
+ && messageIndex === MAX_PERSISTED_MESSAGES_PER_SCOPE ? {
+ approval: {
+ otherProfile: { id: "approval_other" },
+ botProfile: { id: "approval_bot" },
+ waitingOnProfile: { id: "approval_waiting" },
+ },
+ replyTo: { authorId: "reply_author" },
+ thread: { participants: [{ id: "thread_participant" }] },
+ } : {}),
+ }))
+ )), {
+ id: "orphan-message",
+ channelId: "not-retained",
+ type: "chat" as const,
+ seq: 1,
+ createdAt: "2026-09-25T00:00:00.000Z",
+ authorId: "orphan-author",
+ }]
+ messages.push(
+ {
+ id: "dm_0:tie_a",
+ channelId: "dm_0",
+ type: "chat",
+ seq: 100,
+ createdAt: "2026-09-30T00:00:00.000Z",
+ authorId: "author_0",
+ },
+ {
+ id: "dm_0:tie_b",
+ channelId: "dm_0",
+ type: "chat",
+ seq: 100,
+ createdAt: "2026-09-30T00:00:00.000Z",
+ authorId: "author_0",
+ },
+ )
+ const collectionData = {
+ servers: Array.from({ length: 7 }, (_, index) => ({
+ id: `srv_${index}`,
+ name: `Server ${index}`,
+ discriminator: "0001",
+ description: "",
+ ownerId: `owner_${index}`,
+ icon: null,
+ official: false,
+ isOwner: false,
+ unread: false,
+ mentions: 0,
+ })),
+ channels: [...dmChannels, ...serverChannels],
+ categories: Array.from({ length: 7 }, (_, index) => ({
+ id: `cat_${index}`,
+ serverId: `srv_${index}`,
+ name: "Channels",
+ position: 0,
+ private: false,
+ pending: false,
+ })),
+ messages,
+ profiles: [
+ ...Array.from({ length: MAX_PERSISTED_MESSAGE_SCOPES + 2 }, (_, index) => ({
+ userId: `author_${index}`,
+ name: `Author ${index}`,
+ discriminator: "0001",
+ avatar: "A",
+ avatarVersion: 0,
+ })),
+ ...Array.from({ length: 7 }, (_, index) => ({
+ userId: `owner_${index}`,
+ name: `Owner ${index}`,
+ discriminator: "0001",
+ avatar: "O",
+ avatarVersion: 0,
+ })),
+ ...[
+ "approval_other", "approval_bot", "approval_waiting", "reply_author",
+ "thread_participant", "dm_peer", "roster_only", "notify_only",
+ ].map(
+ (userId) => ({
+ userId,
+ name: userId,
+ discriminator: "0001",
+ avatar: "P",
+ avatarVersion: 0,
+ }),
+ ),
+ { userId: "u_1", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 0 },
+ { userId: "orphan", name: "Orphan", discriminator: "0001", avatar: "O", avatarVersion: 0 },
+ ],
+ serverMemberships: [
+ { id: "srv_6:u_1", serverId: "srv_6", userId: "u_1", role: "member", viewer: true },
+ { id: "srv_6:roster_only", serverId: "srv_6", userId: "roster_only", role: "member", viewer: false },
+ ],
+ channelMemberships: [
+ { id: "dm_0:u_1:access", channelId: "dm_0", userId: "u_1", relation: "access" },
+ { id: "dm_0:dm_peer:access", channelId: "dm_0", userId: "dm_peer", relation: "access" },
+ { id: "dm_0:notify_only:notify", channelId: "dm_0", userId: "notify_only", relation: "notify" },
+ { id: "ch_6:u_1:access", channelId: "ch_6", userId: "u_1", relation: "access" },
+ { id: "ch_6:u_1:notify", channelId: "ch_6", userId: "u_1", relation: "notify" },
+ { id: "ch_6:roster_only:access", channelId: "ch_6", userId: "roster_only", relation: "access" },
+ ],
+ readStates: [
+ { channelId: "ch_0", lastReadMessageId: "old", lastReadAt: "2026-09-01T00:00:00.000Z", lastReadSeq: 1 },
+ { channelId: "dm_0", lastReadMessageId: "dm", lastReadAt: "2026-09-02T00:00:00.000Z", lastReadSeq: 2 },
+ ],
+ readStateClock: [{ id: "account", revision: 9 }],
+ }
+ for (const [name, data] of Object.entries(collectionData)) {
+ qc.setQueryData(communityKeys.communityDbCollection("u_1", name), data)
+ }
+ const wrongAccountKey = communityKeys.communityDbCollection("other", "channels")
+ const unknownCollectionKey = communityKeys.communityDbCollection("u_1", "unknown")
+ const malformedCollectionKey = communityKeys.communityDbCollection("u_1", "folders")
+ qc.setQueryData(wrongAccountKey, dmChannels)
+ qc.setQueryData(unknownCollectionKey, [])
+ qc.setQueryData(malformedCollectionKey, [{ id: "malformed" }])
+ qc.setQueryData(communityKeys.servers(), null)
+ const keys = [
+ ...detailKeys,
+ ...Object.keys(collectionData).map((name) => communityKeys.communityDbCollection("u_1", name)),
+ wrongAccountKey,
+ unknownCollectionKey,
+ malformedCollectionKey,
+ communityKeys.servers(),
+ ]
+ await createIdbPersister("u_1").persistClient({
timestamp: Date.now(),
- buster: "v1",
+ buster: "v2",
clientState: {
mutations: [],
- queries: [
- {
- queryKey: communityKeys.channelMessages("ch_anchor"),
- queryHash: JSON.stringify(communityKeys.channelMessages("ch_anchor")),
- state: qc.getQueryState(communityKeys.channelMessages("ch_anchor"))!,
- },
- ],
+ queries: keys.map((queryKey) => ({
+ queryKey,
+ queryHash: JSON.stringify(queryKey),
+ state: qc.getQueryState(queryKey)!,
+ })),
},
})
const blob = await readPersistedBlob("u_1")
- expect(blob.clientState.queries).toHaveLength(1)
- })
-
- it("keeps message queries whose pages[0] is legacy newest-mode (hasMore defined, no anchor flags)", async () => {
+ const collection = (name: string) => blob.clientState.queries.find((query) => (
+ query.queryKey[1] === "db" && query.queryKey[3] === name
+ ))?.state.data as unknown[]
+ const persistedMessages = collection("messages") as typeof messages
+ expect(new Set(persistedMessages.map((message) => message.channelId)).size)
+ .toBe(MAX_PERSISTED_MESSAGE_SCOPES)
+ expect(persistedMessages).toHaveLength(
+ MAX_PERSISTED_MESSAGE_SCOPES * MAX_PERSISTED_MESSAGES_PER_SCOPE,
+ )
+ expect(persistedMessages.filter((message) => message.id.startsWith("dm_0:tie_"))
+ .map((message) => message.id)).toEqual(["dm_0:tie_b", "dm_0:tie_a"])
+ expect(Math.min(...persistedMessages.map((message) => message.seq))).toBe(1)
+ expect((collection("categories") as Array<{ serverId: string }>).map((row) => row.serverId))
+ .toEqual(["srv_0", "srv_1", "srv_2", "srv_3", "srv_4", "srv_5", "srv_6"])
+ expect((collection("servers") as Array<{ id: string; position?: number }>).map((row) => ({
+ id: row.id,
+ position: row.position,
+ }))).toEqual(Array.from({ length: 7 }, (_, index) => ({
+ id: `srv_${index}`,
+ position: undefined,
+ })))
+ expect((collection("channels") as Array<{ serverId: string | null }>).filter(
+ (row) => row.serverId !== null,
+ ).map((row) => row.serverId)).toEqual([
+ "srv_0", "srv_1", "srv_2", "srv_3", "srv_4", "srv_5", "srv_6",
+ ])
+ const profileIds = new Set((collection("profiles") as Array<{ userId: string }>).map(
+ (row) => row.userId,
+ ))
+ expect(profileIds.has("orphan")).toBe(false)
+ expect(profileIds.has("u_1")).toBe(true)
+ expect([...profileIds]).toEqual(expect.arrayContaining([
+ "owner_0",
+ "owner_6",
+ "approval_other",
+ "approval_bot",
+ "approval_waiting",
+ "reply_author",
+ "thread_participant",
+ "dm_peer",
+ ]))
+ expect(profileIds.has("roster_only")).toBe(false)
+ expect(profileIds.has("notify_only")).toBe(false)
+ expect(collection("serverMemberships")).toEqual([
+ expect.objectContaining({ userId: "u_1", viewer: true }),
+ ])
+ expect(collection("channelMemberships")).toEqual(expect.arrayContaining([
+ expect.objectContaining({ channelId: "dm_0", userId: "u_1", relation: "access" }),
+ expect.objectContaining({ channelId: "dm_0", userId: "dm_peer", relation: "access" }),
+ expect.objectContaining({ channelId: "ch_6", userId: "u_1", relation: "access" }),
+ expect.objectContaining({ channelId: "ch_6", userId: "u_1", relation: "notify" }),
+ ]))
+ expect(collection("channelMemberships")).toHaveLength(4)
+ expect((collection("readStates") as Array<{ channelId: string }>).map((row) => row.channelId))
+ .toEqual(["ch_0", "dm_0"])
+ expect(collection("readStateClock")).toEqual([{ id: "account", revision: 9 }])
+ expect(blob.clientState.queries.some((query) => (
+ query.queryKey[1] === "channel" || query.queryKey[1] === "dm"
+ ))).toBe(false)
+ })
+
+ it("drops malformed shell payloads during deserialize scrub", async () => {
const qc = new QueryClient()
- qc.setQueryData(communityKeys.channelMessages("ch_legacy"), {
- pages: [
- makePage([
- { id: "m_1", content: "x", createdAt: "2026-07-01T00:00:00.000Z" },
- ]),
- ],
- pageParams: [{ mode: "newest" }],
- })
-
- const persister = createIdbPersister("u_1")
- await persister.persistClient({
+ qc.setQueryData(communityKeys.servers(), { nope: [] })
+ qc.setQueryData(communityKeys.server("srv_1"), { id: "other", categories: [] })
+ const injected: PersistedClient = {
timestamp: Date.now(),
buster: "v1",
clientState: {
mutations: [],
- queries: [
- {
- queryKey: communityKeys.channelMessages("ch_legacy"),
- queryHash: JSON.stringify(communityKeys.channelMessages("ch_legacy")),
- state: qc.getQueryState(communityKeys.channelMessages("ch_legacy"))!,
- },
- ],
+ queries: [communityKeys.servers(), communityKeys.server("srv_1")].map((queryKey) => ({
+ queryKey,
+ queryHash: JSON.stringify(queryKey),
+ state: qc.getQueryState(queryKey)!,
+ })),
},
- })
-
- const blob = await readPersistedBlob("u_1")
- expect(blob.clientState.queries).toHaveLength(1)
- })
-})
-
-// ── isTrustedMessagesPageZero + shouldPersistQuery invariants ────────────
-
-describe("isTrustedMessagesPageZero", () => {
- it("trusts legacy newest-mode envelopes (hasMore defined, no anchor flags)", () => {
- expect(
- isTrustedMessagesPageZero({ messages: [], hasMore: false, latestSeq: 0 }),
- ).toBe(true)
- expect(
- isTrustedMessagesPageZero({ messages: [], hasMore: true, latestSeq: 0 }),
- ).toBe(true)
- })
-
- it("trusts anchor-mode envelopes with the tail attached (hasMoreNewer=false)", () => {
- expect(
- isTrustedMessagesPageZero({
- messages: [],
- hasMoreOlder: true,
- hasMoreNewer: false,
- latestSeq: 0,
- }),
- ).toBe(true)
- })
-
- it("rejects since-mode envelopes (no hasMore flag on tail)", () => {
- expect(
- isTrustedMessagesPageZero({
- messages: [],
- hasMoreNewer: true,
- newerCursor: "c",
- latestSeq: 0,
- }),
- ).toBe(false)
- })
-
- it("rejects a tail-attached page that carries NO older-side signal", () => {
- // hasMoreNewer===false alone is not enough — without an older-side signal
- // the next mount computes `hasMoreOlder ?? hasMore ?? false === false` and
- // scroll-up dies. This is the exact shape the DM-history bug rehydrated.
- expect(
- isTrustedMessagesPageZero({
- messages: [],
- hasMoreNewer: false,
- newerCursor: undefined,
- latestSeq: 0,
- }),
- ).toBe(false)
- })
-
- it("trusts a since page once it carries the older-side signal (post-fix shape)", () => {
- // buildSinceResponse now emits hasMoreOlder + olderCursor, so even a since
- // delta that lands as the standalone tail can be paged back through.
- expect(
- isTrustedMessagesPageZero({
- messages: [],
- hasMoreNewer: false,
- hasMoreOlder: true,
- olderCursor: "cur_older",
- latestSeq: 0,
- }),
- ).toBe(true)
- })
-
- it("rejects anchor-mode envelopes that still have newer history above (hasMoreNewer=true)", () => {
- expect(
- isTrustedMessagesPageZero({
- messages: [],
- hasMoreOlder: false,
- hasMoreNewer: true,
- latestSeq: 0,
- }),
- ).toBe(false)
- })
+ }
+ await set("alook:qc:v2:u_1:client", JSON.stringify(injected))
+ expect((await createIdbPersister("u_1").restoreClient())?.clientState.queries).toEqual([])
+ })
+
+ it.each([
+ [
+ "server list nested unread source",
+ communityKeys.servers(),
+ { servers: [{ ...validServer, unreadSources: [null] }] },
+ ],
+ [
+ "folder nested server",
+ communityKeys.folders(),
+ { folders: [{ ...validFolder, servers: [null] }] },
+ ],
+ [
+ "DM nested identity",
+ communityKeys.dms(),
+ { conversations: [{ ...validDm, avatarVersion: "old-schema" }] },
+ ],
+ [
+ "server detail category",
+ communityKeys.server("srv_bad"),
+ { ...validServerDetail("srv_bad"), categories: [null] },
+ ],
+ [
+ "server detail nested channel",
+ communityKeys.server("srv_bad"),
+ {
+ ...validServerDetail("srv_bad"),
+ categories: [{
+ ...validServerDetail("srv_bad").categories[0],
+ channels: [null],
+ }],
+ },
+ ],
+ [
+ "server detail nested forum unread state",
+ communityKeys.server("srv_bad"),
+ {
+ ...validServerDetail("srv_bad"),
+ forumUnreadState: { ch_forum: { baseUnread: false, childIds: [null] } },
+ },
+ ],
+ ])("drops a malformed %s query as one unit during restore", async (_label, queryKey, data) => {
+ const qc = new QueryClient()
+ qc.setQueryData(queryKey, data)
+ const injected: PersistedClient = {
+ timestamp: Date.now(),
+ buster: "v1",
+ clientState: {
+ mutations: [],
+ queries: [{
+ queryKey,
+ queryHash: JSON.stringify(queryKey),
+ state: qc.getQueryState(queryKey)!,
+ }],
+ },
+ }
+ await set("alook:qc:v2:u_1:client", JSON.stringify(injected))
- it("rejects undefined pages", () => {
- expect(isTrustedMessagesPageZero(undefined)).toBe(false)
+ expect((await createIdbPersister("u_1").restoreClient())?.clientState.queries).toEqual([])
})
})
describe("shouldPersistQuery", () => {
- it("returns true for a message query with a trusted page[0]", () => {
+ it("persists only canonical collection keys regardless of data", () => {
expect(
- shouldPersistQuery(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [], hasMore: false, latestSeq: 0 }],
- pageParams: [],
- }),
+ shouldPersistQuery(
+ communityKeys.communityDbCollection("u_1", "channels"),
+ undefined,
+ ),
).toBe(true)
- })
-
- it("returns false for a message query with an untrusted page[0]", () => {
- expect(
- shouldPersistQuery(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [], hasMoreNewer: true, newerCursor: "c", latestSeq: 0 }],
- pageParams: [],
- }),
- ).toBe(false)
- })
-
- it("returns false for message queries with empty pages", () => {
- expect(
- shouldPersistQuery(communityKeys.channelMessages("ch_1"), {
- pages: [],
- pageParams: [],
- }),
- ).toBe(false)
- })
-
- it("returns false for keys outside the allowlist regardless of data", () => {
- expect(shouldPersistQuery(communityKeys.servers(), undefined)).toBe(false)
+ expect(shouldPersistQuery(communityKeys.servers(), { servers: [] })).toBe(false)
+ expect(shouldPersistQuery(communityKeys.channelMessages("ch_1"), undefined)).toBe(false)
expect(
shouldPersistQuery(communityKeys.channelReadStateSnapshot("ch_1"), {
lastReadMessageId: "m_1",
@@ -437,7 +671,7 @@ describe("createIdbPersister — user scoping", () => {
await clearPersistedCache("u_alice")
// Alice's blob is gone but Bob's is untouched.
- expect(await get(`alook:qc:v1:u_alice:client`)).toBeUndefined()
+ expect(await get(`alook:qc:v2:u_alice:client`)).toBeUndefined()
const bobBlob = await readPersistedBlob("u_bob")
expect(bobBlob.timestamp).toBe(2)
})
@@ -452,7 +686,7 @@ describe("createIdbPersister — user scoping", () => {
await persister.removeClient()
- expect(await get("alook:qc:v1:u_remove:client")).toBeUndefined()
+ expect(await get("alook:qc:v2:u_remove:client")).toBeUndefined()
})
it("blocks a delayed writer created before clear", async () => {
@@ -463,88 +697,6 @@ describe("createIdbPersister — user scoping", () => {
buster: "v1",
clientState: { mutations: [], queries: [] },
})
- expect(await get(`alook:qc:v1:u_alice:client`)).toBeUndefined()
- })
-})
-
-describe("createIdbPersister — structural snapshot boundary", () => {
- beforeEach(async () => {
- await clearPersistedCache("u_structural")
- await clearPersistedCache(null)
- })
-
- function structuralData(accountId: string) {
- return {
- schemaVersion: 1 as const,
- accountId,
- capturedAt: Date.now(),
- serverOrder: ["server-1"],
- folders: [],
- servers: [{
- id: "server-1",
- name: "Server",
- discriminator: "0001",
- icon: null,
- categories: [],
- channels: [{ id: "channel-1", name: "chat", type: "text" as const, categoryId: null }],
- childRouteHints: [],
- }],
- }
- }
-
- function clientWithStructuralData(data: unknown): PersistedClient {
- const qc = new QueryClient()
- qc.setQueryData(communityKeys.structuralSnapshot(), data)
- return {
- timestamp: Date.now(),
- buster: "v1",
- clientState: {
- mutations: [],
- queries: [{
- queryKey: communityKeys.structuralSnapshot(),
- queryHash: JSON.stringify(communityKeys.structuralSnapshot()),
- state: qc.getQueryState(communityKeys.structuralSnapshot())!,
- }],
- },
- }
- }
-
- it("keeps a strict same-account snapshot", async () => {
- const persister = createIdbPersister("u_structural")
- const data = structuralData("u_structural")
- await persister.persistClient(clientWithStructuralData(data))
- const blob = await readPersistedBlob("u_structural")
- expect(blob.clientState.queries).toHaveLength(1)
- expect(blob.clientState.queries[0]?.state.data).toEqual(data)
- })
-
- it("drops wrong-account, anonymous, and unknown-field snapshots", async () => {
- const wrongAccount = createIdbPersister("u_structural")
- await wrongAccount.persistClient(clientWithStructuralData(structuralData("someone-else")))
- expect((await readPersistedBlob("u_structural")).clientState.queries).toHaveLength(0)
-
- const unknownField = structuralData("u_structural") as ReturnType<typeof structuralData> & { role?: string }
- unknownField.role = "owner"
- await wrongAccount.persistClient(clientWithStructuralData(unknownField))
- expect((await readPersistedBlob("u_structural")).clientState.queries).toHaveLength(0)
-
- const anonymous = createIdbPersister(null)
- await anonymous.persistClient(clientWithStructuralData(structuralData("u_structural")))
- expect((await readPersistedBlob(null)).clientState.queries).toHaveLength(0)
- })
-
- it("reapplies the allowlist and account schema to a directly restored blob", async () => {
- const injected = clientWithStructuralData(structuralData("someone-else"))
- const unrelated = new QueryClient()
- unrelated.setQueryData(communityKeys.servers(), { servers: [] })
- injected.clientState.queries.push({
- queryKey: communityKeys.servers(),
- queryHash: JSON.stringify(communityKeys.servers()),
- state: unrelated.getQueryState(communityKeys.servers())!,
- })
- await set("alook:qc:v1:u_structural:client", JSON.stringify(injected))
-
- const restored = await createIdbPersister("u_structural").restoreClient()
- expect(restored?.clientState.queries).toEqual([])
+ expect(await get(`alook:qc:v2:u_alice:client`)).toBeUndefined()
})
})
diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.ts
index 1db020c94..6a2f6d4c2 100644
--- a/src/web/src/lib/query-persister.ts
+++ b/src/web/src/lib/query-persister.ts
@@ -4,17 +4,17 @@ import type {
Persister,
} from "@tanstack/react-query-persist-client"
import { del, get, set } from "idb-keyval"
-import type { MessagesPage, Msg } from "@/lib/community/models/message"
import {
- parseStructuralSnapshot,
-} from "@/lib/community/structural-snapshot"
+ communityCollectionSchemas,
+ type CommunityCollectionName,
+} from "@/lib/community-db/schema"
/**
* IDB namespace root. Bumping the tail segment (`v1` → `v2`) invalidates every
* cached payload — use it as the escape hatch when the persisted query shape
* changes in a way the runtime can't reconcile against fresh server data.
*/
-const IDB_PREFIX = "alook:qc:v1"
+const IDB_PREFIX = "alook:qc:v2"
/**
* Buster tag paired with `PersistedClient`. TanStack throws away restored
@@ -22,15 +22,15 @@ const IDB_PREFIX = "alook:qc:v1"
* shape of a specific query needs to be reset without touching the IDB
* namespace.
*/
-export const PERSIST_BUSTER = "v1"
+export const PERSIST_BUSTER = "v2"
/** Persister max-age; queries older than this are discarded on restore. */
export const PERSIST_MAX_AGE_MS = 24 * 60 * 60 * 1000
/**
- * Only these query-key kinds are persisted. Everything else refetches on mount
- * — presence, live server list, member rosters, etc. are cheap and should
- * always reflect the live server.
+ * Only canonical TanStack DB collection snapshots are persisted. Transport
+ * queries are deliberately session-only: restoring both their raw payloads
+ * and the canonical collections creates two clocks for the same server facts.
*
* Note: read-state snapshots were previously persisted but were removed to
* kill a self-inflicted staleness bug — a hydrated snapshot with a stale
@@ -38,162 +38,195 @@ export const PERSIST_MAX_AGE_MS = 24 * 60 * 60 * 1000
* since scrolled off. The snapshot hooks now refetch on every mount, so
* persisting them is a strict downside (bytes on disk + risk of drift).
*/
-const PERSISTED_KINDS = new Set<string>([
- "channelMessages",
- "dmMessages",
- "structuralSnapshot",
-])
+export const MAX_PERSISTED_MESSAGE_SCOPES = 20
+export const MAX_PERSISTED_MESSAGES_PER_SCOPE = 50
+const MAX_PERSISTED_ATTENTION_ITEMS = 200
-// Query keys start with `["community", <kind>, ...]` — the first segment is
-// the namespace, the second segment is a discriminator (`"channel"`, `"dm"`,
-// `"servers"`, …), and for message queries the third+ segments carry the id
-// and the literal `"messages"` / `"read-state-snapshot"` tail. See
-// `src/web/src/lib/query-keys.ts`.
-function keyKindFor(queryKey: readonly unknown[]): string | null {
- if (!Array.isArray(queryKey) || queryKey.length < 2) return null
- if (queryKey[0] !== "community") return null
- const second = queryKey[1]
- if (second === "structural-snapshot" && queryKey.length === 2) {
- return "structuralSnapshot"
- }
- // Message queries: ["community", "channel", <id>, "messages"] or
- // ["community", "dm", <id>, "messages"].
- if (second === "channel" || second === "dm") {
- const tail = queryKey[queryKey.length - 1]
- if (tail === "messages") {
- return second === "channel" ? "channelMessages" : "dmMessages"
- }
- if (tail === "read-state-snapshot") {
- return second === "channel"
- ? "channelReadStateSnapshot"
- : "dmReadStateSnapshot"
- }
- }
- return null
+function isCommunityDbCollectionKey(queryKey: readonly unknown[]): boolean {
+ return (
+ queryKey[0] === "community"
+ && queryKey[1] === "db"
+ && queryKey.length === 4
+ && typeof queryKey[2] === "string"
+ && typeof queryKey[3] === "string"
+ )
}
export function shouldPersistQueryKey(queryKey: readonly unknown[]): boolean {
- const kind = keyKindFor(queryKey)
- return kind !== null && PERSISTED_KINDS.has(kind)
-}
-
-/**
- * Trust rule for the first page of a persisted message stream.
- *
- * Persistence is only safe when the cached window represents "we know we have
- * the newest tail." A since-mode or older-only envelope has no `hasMore` flag
- * on `pages[0]`, so the tail-of-history read (`oldestPage.hasMoreOlder ??
- * oldestPage.hasMore ?? false`) collapses to `false` on the next mount and
- * the UI silently loses history until a manual cache clear.
- *
- * Trusted shapes:
- * - Legacy newest-mode: `hasMore !== undefined && hasMoreOlder === undefined
- * && hasMoreNewer === undefined`. This is the pre-anchor cache shape.
- * - Anchor-mode with the tail attached: `hasMoreNewer === false`. Guarantees
- * the client has loaded everything up to the current latestSeq, so the
- * window on disk is a real newest-side window we can safely hand to the
- * next mount.
- */
-export function isTrustedMessagesPageZero(page: MessagesPage | undefined): boolean {
- if (!page) return false
- const isLegacyNewest =
- page.hasMore !== undefined &&
- page.hasMoreOlder === undefined &&
- page.hasMoreNewer === undefined
- if (isLegacyNewest) return true
- // Defense-in-depth (paired with buildSinceResponse now emitting an older-side
- // signal): a page is only a trustworthy standalone tail if the NEXT mount can
- // read back through it. `hasMoreNewer === false` alone isn't enough — a since
- // page carried that yet lacked any older signal, so rehydrating it as the
- // sole page stranded scroll-up (the bug this guards). Require an older-side
- // signal (`hasMoreOlder`/`hasMore` present) so a page that can't self-report
- // its older edge never survives to disk, whatever produced it.
- if (
- page.hasMoreNewer === false &&
- (page.hasMoreOlder !== undefined || page.hasMore !== undefined)
- ) {
- return true
- }
- return false
+ return isCommunityDbCollectionKey(queryKey)
}
-/**
- * Query-level filter used by both `shouldDehydrateQuery` (write side) and
- * `scrubDehydratedClient` (read side of the same walk). Non-message queries
- * fall through to `shouldPersistQueryKey`; message queries additionally check
- * `pages[0]` shape so a stale/mid-history cache never survives to the next
- * mount.
- */
export function shouldPersistQuery(
queryKey: readonly unknown[],
- data: unknown,
+ _data: unknown,
): boolean {
- if (!shouldPersistQueryKey(queryKey)) return false
- const kind = keyKindFor(queryKey)
- if (kind !== "channelMessages" && kind !== "dmMessages") return true
- const pages = (data as { pages?: MessagesPage[] } | undefined)?.pages
- if (!Array.isArray(pages) || pages.length === 0) return false
- return isTrustedMessagesPageZero(pages[0])
+ return shouldPersistQueryKey(queryKey)
}
/**
- * Optimistic rows carry an id that starts with `temp_` until the server
- * assigns a real id. Persisting them would surface ghost rows on reload — the
- * outgoing POST may never have committed, and if it did, the WS layer will
- * re-deliver the real message with the canonical id. Also strips `failed:
- * true` rows since they only exist to prompt a retry that no longer makes
- * sense once the tab has been closed.
- */
-function scrubMessage(m: Msg): boolean {
- if (typeof m.id === "string" && m.id.startsWith("temp_")) return false
- if (m.failed === true) return false
- return true
-}
-
-function scrubPage(page: MessagesPage): MessagesPage {
- const messages = page.messages.filter(scrubMessage)
- if (messages.length === page.messages.length) return page
- return { ...page, messages }
-}
-
-/**
- * Walk the dehydrated client and:
- * 1. Drop optimistic / failed message rows from each page (temp_/failed rows
- * would surface as ghosts on the next mount — see `scrubMessage`).
- * 2. Drop the whole query when its trimmed `pages[0]` no longer represents a
- * trusted newest-tail cache. TanStack's dehydrate step already ran the
- * `shouldDehydrateQuery` predicate against the *pre-scrub* data; if
- * scrubbing changed the shape (or the shape was borderline to begin with),
- * re-run the invariant here so nothing untrustworthy hits disk.
- *
- * Mutates a shallow copy — the live QueryClient cache is untouched. Called
- * from the persister's `serialize` hook, so the filter is applied every time
- * TanStack throttles a save.
+ * Retain the bounded canonical read closure without mutating the live cache.
*/
function scrubDehydratedClient(
client: PersistedClient,
userId: string | null,
- now = Date.now(),
): PersistedClient {
const queries: typeof client.clientState.queries = []
+ const canonical = new Map<CommunityCollectionName, unknown[]>()
for (const q of client.clientState.queries) {
- const kind = keyKindFor(q.queryKey)
- if (kind === "structuralSnapshot") {
- if (!userId) continue
- const snapshot = parseStructuralSnapshot(q.state.data, userId, now)
- if (!snapshot) continue
- queries.push({ ...q, state: { ...q.state, data: snapshot } })
+ if (isCommunityDbCollectionKey(q.queryKey)) {
+ if (!userId || q.queryKey[2] !== userId) continue
+ const collectionName = q.queryKey[3] as CommunityCollectionName
+ const schema = communityCollectionSchemas[collectionName]
+ if (!schema) continue
+ const parsed = schema.array().safeParse(q.state.data)
+ if (!parsed.success) continue
+ canonical.set(collectionName, parsed.data)
continue
}
- if (kind !== "channelMessages" && kind !== "dmMessages") continue
- const data = q.state.data as
- | { pages: MessagesPage[]; pageParams: unknown[] }
- | undefined
- if (!data || !Array.isArray(data.pages)) continue
- const pages = data.pages.map(scrubPage)
- const nextData = { ...data, pages }
- if (!shouldPersistQuery(q.queryKey, nextData)) continue
- queries.push({ ...q, state: { ...q.state, data: nextData } })
+ }
+
+ const retainedServerIds = new Set(
+ ((canonical.get("servers") ?? []) as Array<{ id: string }>).map((row) => row.id),
+ )
+
+ const channels = (canonical.get("channels") ?? []) as Array<{
+ id: string
+ serverId?: string | null
+ type: "text" | "forum" | "thread" | "dm"
+ }>
+ const attentionScopes = (canonical.get("attentionScopes") ?? []) as Array<{
+ scopeId: string
+ channelId: string
+ }>
+ const retainedAttentionItems = ((canonical.get("attentionItems") ?? []) as Array<{
+ id: string
+ kind: "mention" | "reply" | "friend_request" | "pending"
+ messageId?: string | null
+ actorUserId: string
+ createdAt: string
+ }>).slice()
+ const retainedMessageAttention = retainedAttentionItems
+ .filter((item) => item.kind !== "friend_request")
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))
+ .slice(0, MAX_PERSISTED_ATTENTION_ITEMS)
+ const retainedFriendAttention = retainedAttentionItems
+ .filter((item) => item.kind === "friend_request")
+ retainedAttentionItems.splice(
+ 0,
+ retainedAttentionItems.length,
+ ...retainedMessageAttention,
+ ...retainedFriendAttention,
+ )
+ const attentionChannelIds = new Set(attentionScopes.map((row) => row.channelId))
+ const retainedChannels = channels.filter((row) => (
+ attentionChannelIds.has(row.id)
+ || row.serverId === null
+ || row.serverId === undefined
+ || retainedServerIds.has(row.serverId)
+ ))
+ const retainedChannelIds = new Set(retainedChannels.map((row) => row.id))
+ const retainedDmIds = new Set(
+ retainedChannels.filter((row) => row.type === "dm").map((row) => row.id),
+ )
+ const allMessages = (canonical.get("messages") ?? []) as Array<{
+ id: string
+ channelId: string
+ seq?: number
+ createdAt?: string
+ authorId?: string
+ replyTo?: { authorId?: string }
+ thread?: { participants?: Array<{ id: string }> }
+ }>
+ const messagesByScope = new Map<string, typeof allMessages>()
+ for (const message of allMessages) {
+ if (!retainedChannelIds.has(message.channelId)) continue
+ const rows = messagesByScope.get(message.channelId) ?? []
+ rows.push(message)
+ messagesByScope.set(message.channelId, rows)
+ }
+ const compareMessagesNewest = (a: typeof allMessages[number], b: typeof allMessages[number]) => (
+ (b.seq ?? -1) - (a.seq ?? -1)
+ || String(b.createdAt ?? "").localeCompare(String(a.createdAt ?? ""))
+ || b.id.localeCompare(a.id)
+ )
+ const attentionMessageIds = new Set(retainedAttentionItems.flatMap((row) => (
+ row.messageId ? [row.messageId] : []
+ )))
+ const retainedMessages = [...messagesByScope.values()]
+ .map((rows) => rows.slice().sort(compareMessagesNewest))
+ .sort((a, b) => compareMessagesNewest(a[0]!, b[0]!))
+ .slice(0, MAX_PERSISTED_MESSAGE_SCOPES)
+ .flatMap((rows) => rows.slice(0, MAX_PERSISTED_MESSAGES_PER_SCOPE))
+ const retainedMessageIds = new Set(retainedMessages.map((row) => row.id))
+ for (const message of allMessages) {
+ if (attentionMessageIds.has(message.id) && !retainedMessageIds.has(message.id)) {
+ retainedMessages.push(message)
+ retainedMessageIds.add(message.id)
+ }
+ }
+ const retainedMessageChannelIds = new Set(retainedMessages.map((row) => row.channelId))
+ const durableChannelIds = new Set([...retainedChannelIds, ...retainedMessageChannelIds])
+ const serverMemberships = (canonical.get("serverMemberships") ?? []) as Array<{
+ serverId: string
+ userId: string
+ viewer: boolean
+ }>
+ const retainedServerMemberships = serverMemberships.filter((row) => row.viewer)
+ const channelMemberships = (canonical.get("channelMemberships") ?? []) as Array<{
+ channelId: string
+ userId: string
+ relation: "access" | "notify"
+ }>
+ const retainedChannelMemberships = channelMemberships.filter((row) => (
+ durableChannelIds.has(row.channelId)
+ && (
+ row.userId === userId
+ || row.relation === "access" && retainedDmIds.has(row.channelId)
+ )
+ ))
+ const referencedProfileIds = new Set<string>(userId ? [userId] : [])
+ for (const server of (canonical.get("servers") ?? []) as Array<{ ownerId: string }>) {
+ if (server.ownerId) referencedProfileIds.add(server.ownerId)
+ }
+ for (const membership of retainedServerMemberships) referencedProfileIds.add(membership.userId)
+ for (const membership of retainedChannelMemberships) referencedProfileIds.add(membership.userId)
+ for (const message of retainedMessages) {
+ if (message.authorId) referencedProfileIds.add(message.authorId)
+ if (message.replyTo?.authorId) referencedProfileIds.add(message.replyTo.authorId)
+ for (const participant of message.thread?.participants ?? []) {
+ referencedProfileIds.add(participant.id)
+ }
+ for (const profile of [
+ (message as { approval?: { otherProfile?: { id?: string } } }).approval?.otherProfile,
+ (message as { approval?: { botProfile?: { id?: string } } }).approval?.botProfile,
+ (message as { approval?: { waitingOnProfile?: { id?: string } } }).approval?.waitingOnProfile,
+ ]) {
+ if (profile?.id) referencedProfileIds.add(profile.id)
+ }
+ }
+ for (const item of retainedAttentionItems) referencedProfileIds.add(item.actorUserId)
+
+ const windowed: Partial<Record<CommunityCollectionName, unknown[]>> = {
+ ...Object.fromEntries(canonical),
+ categories: ((canonical.get("categories") ?? []) as Array<{ serverId: string }>).filter(
+ (row) => retainedServerIds.has(row.serverId),
+ ),
+ channels: retainedChannels,
+ serverMemberships: retainedServerMemberships,
+ channelMemberships: retainedChannelMemberships,
+ messages: retainedMessages,
+ attentionScopes,
+ attentionItems: retainedAttentionItems,
+ profiles: ((canonical.get("profiles") ?? []) as Array<{ userId: string }>).filter(
+ (row) => referencedProfileIds.has(row.userId),
+ ),
+ }
+ for (const q of client.clientState.queries) {
+ if (!isCommunityDbCollectionKey(q.queryKey)) continue
+ if (!userId || q.queryKey[2] !== userId) continue
+ const collectionName = q.queryKey[3] as CommunityCollectionName
+ const data = windowed[collectionName]
+ if (data) queries.push({ ...q, state: { ...q.state, data } })
}
return {
...client,
@@ -254,8 +287,8 @@ function runPersistOperation<T>(key: string, operation: () => Promise<T>): Promi
* Create an async-storage persister scoped to a specific user id.
*
* Every read/write is namespaced by `userId` so signing in as a different
- * account never surfaces the previous user's cached rows. `serialize` scrubs
- * `temp_*` and `failed: true` rows before they hit disk (see `scrubMessage`).
+ * account never surfaces the previous user's cached rows. `serialize` retains
+ * only the bounded canonical read closure before it reaches disk.
*/
export function createIdbPersister(userId: string | null): Persister {
const key = blobKeyFor(userId)
diff --git a/src/web/src/lib/session.test.ts b/src/web/src/lib/session.test.ts
index cda17c22f..ea6d2a1aa 100644
--- a/src/web/src/lib/session.test.ts
+++ b/src/web/src/lib/session.test.ts
@@ -4,19 +4,21 @@ vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(async () => ({ env: {} })),
}));
-vi.mock("next/headers", () => ({
- headers: vi.fn(async () => new Headers()),
-}));
+const mockHeaders = vi.hoisted(() => vi.fn(async () => new Headers()));
+vi.mock("next/headers", () => ({ headers: mockHeaders }));
const mockGetSession = vi.fn();
vi.mock("@/lib/auth", () => ({
- createAuth: vi.fn(() => ({ api: { getSession: mockGetSession } })),
+ getAuth: vi.fn(() => ({ api: { getSession: mockGetSession } })),
}));
import { getSession, requireSession } from "./session";
describe("session", () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockHeaders.mockResolvedValue(new Headers());
+ });
it("getSession returns the resolved session", async () => {
const session = { user: { id: "u1", email: "[email protected]" } };
@@ -29,6 +31,21 @@ describe("session", () => {
await expect(getSession()).resolves.toBeNull();
});
+ it("resolves concurrent users independently through the shared auth instance", async () => {
+ mockHeaders
+ .mockResolvedValueOnce(new Headers({ Cookie: "viewer=user-a" }))
+ .mockResolvedValueOnce(new Headers({ Cookie: "viewer=user-b" }));
+ mockGetSession.mockImplementation(async ({ headers }: { headers: Headers }) => ({
+ user: { id: headers.get("Cookie")?.split("=")[1] },
+ }));
+
+ const [first, second] = await Promise.all([getSession(), getSession()]);
+
+ expect(first?.user.id).toBe("user-a");
+ expect(second?.user.id).toBe("user-b");
+ expect(mockGetSession).toHaveBeenCalledTimes(2);
+ });
+
it("requireSession returns the session when present", async () => {
const session = { user: { id: "u1", email: "[email protected]" } };
mockGetSession.mockResolvedValue(session);
diff --git a/src/web/src/lib/session.ts b/src/web/src/lib/session.ts
index bb3248494..235308e1a 100644
--- a/src/web/src/lib/session.ts
+++ b/src/web/src/lib/session.ts
@@ -1,10 +1,10 @@
import { headers } from "next/headers"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
export async function getSession() {
const { env } = await getCloudflareContext({ async: true })
- const auth = createAuth(env as Env)
+ const auth = getAuth(env as Env)
return auth.api.getSession({ headers: await headers() })
}
diff --git a/src/web/src/middleware.test.ts b/src/web/src/middleware.test.ts
index 857b37985..ebf67c181 100644
--- a/src/web/src/middleware.test.ts
+++ b/src/web/src/middleware.test.ts
@@ -7,7 +7,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetSession = vi.fn();
vi.mock("@/lib/auth", () => ({
- createAuth: vi.fn(() => ({ api: { getSession: mockGetSession } })),
+ getAuth: vi.fn(() => ({ api: { getSession: mockGetSession } })),
}));
import { middleware } from "./middleware";
diff --git a/src/web/src/middleware.ts b/src/web/src/middleware.ts
index 51d6d8df3..f5c56280e 100644
--- a/src/web/src/middleware.ts
+++ b/src/web/src/middleware.ts
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createAuth } from "@/lib/auth"
+import { getAuth } from "@/lib/auth"
import { isSafeRedirectPath } from "@/lib/safe-redirect"
const AUTH_REQUIRED_PREFIXES = ["/invite/", "/w/", "/workspaces", "/dashboard", "/c/"]
@@ -31,7 +31,7 @@ export async function middleware(request: NextRequest) {
if (needsAuth) {
const { env } = await getCloudflareContext({ async: true })
- const auth = createAuth(env as Env)
+ const auth = getAuth(env as Env)
const result = await auth.api.getSession({
headers: request.headers,
returnHeaders: true,
@@ -55,7 +55,7 @@ export async function middleware(request: NextRequest) {
if (pathname === "/sign-in" || pathname === "/sign-up") {
const { env } = await getCloudflareContext({ async: true })
- const auth = createAuth(env as Env)
+ const auth = getAuth(env as Env)
const result = await auth.api.getSession({
headers: request.headers,
returnHeaders: true,
diff --git a/src/web/src/stores/community/index.test.ts b/src/web/src/stores/community/index.test.ts
index ac7a54b7a..87a8de8cc 100644
--- a/src/web/src/stores/community/index.test.ts
+++ b/src/web/src/stores/community/index.test.ts
@@ -47,6 +47,56 @@ describe("useCommunityStore", () => {
})
})
+ it("does not notify for semantically equal effect-facing writes", () => {
+ const listener = vi.fn()
+ const unsubscribe = useCommunityStore.subscribe(listener)
+ const store = useCommunityStore.getState()
+
+ store.setCurrentServerId("s1")
+ listener.mockClear()
+ store.setCurrentServerId("s1")
+ expect(listener).not.toHaveBeenCalled()
+
+ store.setCurrentChannelMeta({
+ name: "post",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ })
+ listener.mockClear()
+ store.setCurrentChannelMeta({
+ name: "post",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ })
+ expect(listener).not.toHaveBeenCalled()
+
+ store.setPendingMachineTokenId("token-1")
+ listener.mockClear()
+ store.setPendingMachineTokenId("token-1")
+ expect(listener).not.toHaveBeenCalled()
+
+ store.setPendingReply({
+ channelId: "channel-1",
+ target: { id: "message-1", authorName: "Alice", text: "hello" },
+ })
+ listener.mockClear()
+ store.setPendingReply({
+ channelId: "channel-1",
+ target: { id: "message-1", authorName: "Alice", text: "hello" },
+ })
+ expect(listener).not.toHaveBeenCalled()
+
+ const previewImage = vi.fn()
+ store.registerUiHandlers({ previewImage })
+ listener.mockClear()
+ store.registerUiHandlers({ previewImage })
+ expect(listener).not.toHaveBeenCalled()
+
+ unsubscribe()
+ })
+
it("subscribe / unsubscribe mutate the subscription slot", () => {
useCommunityStore.getState().subscribe({ channelId: "c1" })
expect(useCommunityStore.getState().subscription).toEqual({ channelId: "c1" })
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index 9bc0edd34..0262b3e91 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -120,6 +120,31 @@ type PendingReply = {
target: { id: string; authorName: string; text: string }
}
+function sameCurrentChannelMeta(
+ left: CurrentChannelMeta | null,
+ right: CurrentChannelMeta | null,
+): boolean {
+ return left === right || (
+ left !== null &&
+ right !== null &&
+ left.name === right.name &&
+ left.parentChannelId === right.parentChannelId &&
+ (left.parentMessageId ?? null) === (right.parentMessageId ?? null) &&
+ (left.creatorId ?? null) === (right.creatorId ?? null)
+ )
+}
+
+function samePendingReply(left: PendingReply | null, right: PendingReply | null): boolean {
+ return left === right || (
+ left !== null &&
+ right !== null &&
+ left.channelId === right.channelId &&
+ left.target.id === right.target.id &&
+ left.target.authorName === right.target.authorName &&
+ left.target.text === right.target.text
+ )
+}
+
type Timer = ReturnType<typeof setTimeout>
export type CommunityStoreState = {
@@ -208,14 +233,20 @@ const initialState = (): Pick<
export const useCommunityStore = create<CommunityStoreState>((set, get) => ({
...initialState(),
- setCurrentServerId: (id) => set({ currentServerId: id }),
+ setCurrentServerId: (id) => {
+ if (get().currentServerId === id) return
+ set({ currentServerId: id })
+ },
setCurrentChannelId: (id) => {
if (get().currentChannelId === id) return // no-op on identical value
set({ currentChannelId: id })
},
- setCurrentChannelMeta: (meta) => set({ currentChannelMeta: meta }),
+ setCurrentChannelMeta: (meta) => {
+ if (sameCurrentChannelMeta(get().currentChannelMeta, meta)) return
+ set({ currentChannelMeta: meta })
+ },
subscribe: (target) => {
// Bail if the target is the same as the currently focused subscription.
@@ -266,13 +297,25 @@ export const useCommunityStore = create<CommunityStoreState>((set, get) => ({
set({ subscription: {}, secondaryChannelOwner: null })
},
- setPendingMachineTokenId: (tokenId) =>
- set({ pendingMachineTokenId: tokenId }),
+ setPendingMachineTokenId: (tokenId) => {
+ if (get().pendingMachineTokenId === tokenId) return
+ set({ pendingMachineTokenId: tokenId })
+ },
- setPendingReply: (reply) => set({ pendingReply: reply }),
+ setPendingReply: (reply) => {
+ if (samePendingReply(get().pendingReply, reply)) return
+ set({ pendingReply: reply })
+ },
- registerUiHandlers: (handlers) =>
- set({ uiHandlers: { ...get().uiHandlers, ...handlers } }),
+ registerUiHandlers: (handlers) => {
+ const current = get().uiHandlers
+ const entries = Object.entries(handlers) as Array<[
+ keyof CommunityUiHandlers,
+ CommunityUiHandlers[keyof CommunityUiHandlers],
+ ]>
+ if (entries.every(([key, handler]) => current[key] === handler)) return
+ set({ uiHandlers: { ...current, ...handlers } })
+ },
reset: () => {
const { typingTimers, reactionTimers } = get()
diff --git a/src/web/src/stores/community/profile-preview.dom.test.ts b/src/web/src/stores/community/profile-preview.dom.test.ts
index 09ea43a20..95e3e234b 100644
--- a/src/web/src/stores/community/profile-preview.dom.test.ts
+++ b/src/web/src/stores/community/profile-preview.dom.test.ts
@@ -1,20 +1,16 @@
import { createElement } from "react"
-import { afterEach, describe, expect, it } from "vitest"
+import { describe, expect, it } from "vitest"
import { render } from "@/test/react-dom-harness"
import type { CommunityProfile } from "@/lib/community/models/people"
import { CommunityPreviewProfileOwner } from "./profile-preview"
-import {
- useCommunityProfile,
- useCommunityWsStore,
- useProfilesByUserId,
-} from "./ws"
+import { useCommunityPreviewProfiles } from "./profile-preview"
function ProfileProbe({ userId }: { userId: string }) {
- const profile = useCommunityProfile(userId)
- const profiles = useProfilesByUserId()
+ const profiles = useCommunityPreviewProfiles()
+ const profile = profiles?.get(userId)
return createElement("output", {
"data-profile-name": profile?.name,
- "data-map-name": profiles.get(userId)?.name,
+ "data-map-name": profiles?.get(userId)?.name,
})
}
@@ -28,36 +24,23 @@ function renderProbe(userId: string, previewProfiles?: ReadonlyMap<string, Commu
return rendered.container.querySelector("output")!
}
-afterEach(() => {
- useCommunityWsStore.getState().reset()
-})
-
describe("CommunityPreviewProfileOwner", () => {
- it("owns profile reads inside its subtree without mutating the live store", () => {
- const liveProfile = { id: "shared", name: "Live name" }
- const liveProfiles = new Map([[liveProfile.id, liveProfile]])
- useCommunityWsStore.setState({ profilesByUserId: liveProfiles })
+ it("owns profile reads inside its subtree", () => {
const previewProfiles = new Map([["shared", { id: "shared", name: "Preview name" }]])
const owned = renderProbe("shared", previewProfiles)
expect(owned).toHaveAttribute("data-profile-name", "Preview name")
expect(owned).toHaveAttribute("data-map-name", "Preview name")
- expect(useCommunityWsStore.getState().profilesByUserId).toBe(liveProfiles)
- expect(useCommunityWsStore.getState().profilesByUserId.get("shared")?.name).toBe("Live name")
})
- it("does not leak live identities into an incomplete preview owner", () => {
- useCommunityWsStore.setState({
- profilesByUserId: new Map([["live-only", { id: "live-only", name: "Live only" }]]),
- })
-
+ it("does not leak profiles outside the preview owner", () => {
const owned = renderProbe("live-only", new Map())
const live = renderProbe("live-only")
expect(owned).not.toHaveAttribute("data-profile-name")
expect(owned).not.toHaveAttribute("data-map-name")
- expect(live).toHaveAttribute("data-profile-name", "Live only")
- expect(live).toHaveAttribute("data-map-name", "Live only")
+ expect(live).not.toHaveAttribute("data-profile-name")
+ expect(live).not.toHaveAttribute("data-map-name")
})
})
diff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.ts
index 1a29251dd..14bd50456 100644
--- a/src/web/src/stores/community/ws.test.ts
+++ b/src/web/src/stores/community/ws.test.ts
@@ -14,7 +14,7 @@ beforeEach(() => {
function activate(viewerId = "viewer") {
useCommunityWsStore.getState().activateProfileAccount(viewerId)
- return useCommunityWsStore.getState().beginProfileSnapshot()
+ return useCommunityWsStore.getState().beginPresenceSnapshot()
}
describe("useCommunityWsStore", () => {
@@ -31,170 +31,43 @@ describe("useCommunityWsStore", () => {
expect(calls).toEqual(["retry"])
})
- it("fails closed until websocket authentication and advances access epochs", () => {
+ it("tracks websocket authentication without treating transport loss as revocation", () => {
+ expect(useCommunityWsStore.getState()).toMatchObject({ accessConnected: false, accessEpoch: 0 })
+ useCommunityWsStore.getState().markAccessDisconnected()
expect(useCommunityWsStore.getState()).toMatchObject({ accessConnected: false, accessEpoch: 0 })
useCommunityWsStore.getState().markAccessConnected()
useCommunityWsStore.getState().markAccessDisconnected()
- expect(useCommunityWsStore.getState()).toMatchObject({ accessConnected: false, accessEpoch: 1 })
- })
-
- it("seeds eligible groups and preserves groups patched after request start", () => {
- const initial = activate()
- useCommunityWsStore.getState().seedProfiles(initial, [{
- id: "u1",
- identityAbout: { name: "API old", aboutMe: "api bio" },
- status: { statusEmoji: "🌱", statusText: "api" },
- presence: "offline",
- }])
-
- const request = useCommunityWsStore.getState().beginProfileSnapshot()
- useCommunityWsStore.getState().patchProfiles(request, [{
- id: "u1",
- identityAbout: { name: "WS new", aboutMe: undefined },
- presence: "online",
- }])
- useCommunityWsStore.getState().seedProfiles(request, [{
- id: "u1",
- identityAbout: { name: "late API", aboutMe: "late bio" },
- status: { statusEmoji: "🎧", statusText: "late status" },
- presence: "offline",
- }])
-
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
- name: "WS new",
- aboutMe: undefined,
- statusEmoji: "🎧",
- statusText: "late status",
- presence: "online",
- })
- })
-
- it("advances authoritative group revisions even when values are equal", () => {
- const initial = activate()
- useCommunityWsStore.getState().seedProfiles(initial, [{
- id: "u1",
- status: { statusEmoji: null, statusText: null },
- }])
- const request = useCommunityWsStore.getState().beginProfileSnapshot()
- useCommunityWsStore.getState().patchProfiles(request, [{
- id: "u1",
- status: { statusEmoji: null, statusText: null },
- }])
- const afterPatch = useCommunityWsStore.getState()
- expect(afterPatch.profileRevision).toBe(request.revision + 1)
-
- afterPatch.seedProfiles(request, [{
- id: "u1",
- status: { statusEmoji: "stale", statusText: "stale" },
- }])
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
- statusEmoji: null,
- statusText: null,
- })
- })
-
- it("conditionally commits a successful mutation ahead of an older API seed", () => {
- const oldGet = activate()
- const mutation = useCommunityWsStore.getState().beginProfileSnapshot()
-
- useCommunityWsStore.getState().commitProfiles(mutation, [{
- id: "u1",
- identityAbout: { name: "Local mutation" },
- }])
- expect(useCommunityWsStore.getState().profileRevision).toBe(1)
-
- useCommunityWsStore.getState().seedProfiles(oldGet, [{
- id: "u1",
- identityAbout: { name: "Old GET" },
- }])
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")?.name)
- .toBe("Local mutation")
+ useCommunityWsStore.getState().markAccessDisconnected()
+ expect(useCommunityWsStore.getState()).toMatchObject({ accessConnected: false, accessEpoch: 0 })
})
- it("does not let a mutation response overwrite a newer WS group patch", () => {
- const mutation = activate()
- const profiles = useCommunityWsStore.getState()
- profiles.patchProfiles(profiles.beginProfileSnapshot(), [{
- id: "u1",
- identityAbout: { name: "Newer WS" },
- }])
-
- profiles.commitProfiles(mutation, [{
- id: "u1",
- identityAbout: { name: "Mutation response" },
- }])
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")?.name)
- .toBe("Newer WS")
- expect(useCommunityWsStore.getState().profileRevision).toBe(1)
+ it("keeps only presence in the websocket overlay", () => {
+ activate()
+ useCommunityWsStore.getState().setPresence("u1", "online")
+ expect(useCommunityWsStore.getState().presenceByUserId).toEqual(
+ new Map([["u1", "online"]]),
+ )
+ expect(useCommunityWsStore.getState()).not.toHaveProperty("profilesByUserId")
})
- it("compares avatar versions independently without advancing group revision", () => {
- const snapshot = activate()
- const store = useCommunityWsStore.getState()
- store.patchProfiles(snapshot, [{
- id: "u1",
- avatar: { avatar: "/a?v=2", avatarVersion: 2 },
- }])
- expect(useCommunityWsStore.getState().profileRevision).toBe(0)
-
- store.patchProfiles(snapshot, [{
- id: "u1",
- avatar: { avatar: "/stale?v=1", avatarVersion: 1 },
- }, {
- id: "u1",
- avatar: { avatar: "/conflict?v=2", avatarVersion: 2 },
- }])
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
- avatar: "/a?v=2",
- avatarVersion: 2,
- })
-
- store.seedProfiles(snapshot, [{
- id: "u1",
- avatar: { avatar: "/a?v=3", avatarVersion: 3 },
- }])
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
- avatar: "/a?v=3",
- avatarVersion: 3,
- })
+ it("preserves a live presence delta over an older HTTP seed", () => {
+ const request = activate()
+ useCommunityWsStore.getState().setPresence("u1", "online")
+ useCommunityWsStore.getState().seedPresence(request, [["u1", "offline"]])
+ expect(useCommunityWsStore.getState().presenceByUserId.get("u1")).toBe("online")
})
- it("rejects late work after viewer switch and prevents reset ABA", () => {
+ it("rejects a presence seed after viewer switch or reset", () => {
const oldSnapshot = activate("viewer-a")
useCommunityWsStore.getState().activateProfileAccount("viewer-b")
- expect(useCommunityWsStore.getState().seedProfiles(oldSnapshot, [{
- id: "u1",
- identityAbout: { name: "wrong viewer" },
- }])).toBe(false)
-
- const beforeReset = useCommunityWsStore.getState().beginProfileSnapshot()
+ expect(useCommunityWsStore.getState().seedPresence(oldSnapshot, [["u1", "online"]]))
+ .toBe(false)
+ const beforeReset = useCommunityWsStore.getState().beginPresenceSnapshot()
useCommunityWsStore.getState().reset()
useCommunityWsStore.getState().activateProfileAccount("viewer-b")
- expect(useCommunityWsStore.getState().patchProfiles(beforeReset, [{
- id: "u1",
- identityAbout: { name: "ABA" },
- }])).toBe(false)
- expect(useCommunityWsStore.getState().profilesByUserId.size).toBe(0)
- })
-
- it("applies multiple same-user groups in one authoritative batch", () => {
- const snapshot = activate()
- useCommunityWsStore.getState().patchProfiles(snapshot, [{
- id: "u1",
- identityAbout: { name: "Alice" },
- }, {
- id: "u1",
- status: { statusEmoji: "🎧", statusText: "Focus" },
- presence: "online",
- }])
- expect(useCommunityWsStore.getState().profilesByUserId.get("u1")).toMatchObject({
- name: "Alice",
- statusEmoji: "🎧",
- statusText: "Focus",
- presence: "online",
- })
- expect(useCommunityWsStore.getState().profileRevisionsByUserId.get("u1"))
- .toEqual({ identityAbout: 1, status: 1, presence: 1 })
+ expect(useCommunityWsStore.getState().seedPresence(beforeReset, [["u1", "online"]]))
+ .toBe(false)
+ expect(useCommunityWsStore.getState().presenceByUserId.size).toBe(0)
})
it("deduplicates seen messages and trims the oldest ids", () => {
diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.ts
index 8bd506f34..8d46360a2 100644
--- a/src/web/src/stores/community/ws.ts
+++ b/src/web/src/stores/community/ws.ts
@@ -2,21 +2,14 @@
import { create } from "zustand"
import type { CommunityBotAuditEvent } from "@alook/shared"
-import type {
- CommunityProfile,
- CommunityProfilePatch,
- CommunityProfileSnapshot,
-} from "@/lib/community/models/people"
-import { useCommunityPreviewProfiles } from "@/stores/community/profile-preview"
/**
* Zustand store for community WS-live-patched state.
*
* Owned exclusively by the WS handler (`hooks/community/use-community-ws.ts`)
- * after Step 4 lands; consumers read via the selector hooks below. Kept
- * separate from `useCommunityStore` so subscription re-renders only fire on
- * the axis that changed — a presence tick doesn't re-render a component that
- * only cares about the current channel id.
+ * Durable profile fields live in the canonical TanStack DB collection. This
+ * store retains only the WS generation guards and transient overlays such as
+ * presence, so a presence tick does not rewrite the persisted profile row.
*
* Loop-breaker rules (short version — full rulebook lives in `./index.ts`):
* - Setters no-op on identical projected values. Zustand notifies every
@@ -59,8 +52,12 @@ export type BotAuditEventEntry = {
createdAt: string
}
-type ProfileRevisions = { identityAbout: number; status: number; presence: number }
-type ProfileWriteMode = "seed" | "patch" | "commit"
+export type CommunityPresence = "online" | "offline"
+export type CommunityPresenceSnapshot = {
+ viewerId: string | null
+ accountEpoch: number
+ revision: number
+}
export type CommunityWsConnectionStatus = "connected" | "reconnecting" | "failed"
const NOOP_RECONNECT = () => undefined
@@ -88,9 +85,9 @@ export type CommunityWsStoreState = {
reconnectNow: () => void
profileViewerId: string | null
profileAccountEpoch: number
- profileRevision: number
- profilesByUserId: Map<string, CommunityProfile>
- profileRevisionsByUserId: Map<string, ProfileRevisions>
+ presenceRevision: number
+ presenceByUserId: Map<string, CommunityPresence>
+ presenceRevisionsByUserId: Map<string, number>
seenMessageIds: Set<string>
seenDeliveryOperations: Map<string, DeliveryOperationState>
/**
@@ -101,19 +98,12 @@ export type CommunityWsStoreState = {
botAuditEvents: Map<string, BotAuditEventEntry[]>
activateProfileAccount: (viewerId: string | null) => number
- beginProfileSnapshot: () => CommunityProfileSnapshot
- seedProfiles: (
- snapshot: CommunityProfileSnapshot,
- patches: readonly CommunityProfilePatch[],
- ) => boolean
- commitProfiles: (
- snapshot: CommunityProfileSnapshot,
- patches: readonly CommunityProfilePatch[],
- ) => boolean
- patchProfiles: (
- snapshot: Pick<CommunityProfileSnapshot, "viewerId" | "accountEpoch">,
- patches: readonly CommunityProfilePatch[],
+ beginPresenceSnapshot: () => CommunityPresenceSnapshot
+ seedPresence: (
+ snapshot: CommunityPresenceSnapshot,
+ patches: ReadonlyMap<string, CommunityPresence> | readonly [string, CommunityPresence][],
) => boolean
+ setPresence: (userId: string, presence: CommunityPresence) => boolean
hasSeenMessage: (id: string) => boolean
markSeenMessage: (id: string) => void
observeDeliveryOperation: (
@@ -131,8 +121,8 @@ export type CommunityWsStoreState = {
const initialState = (): Pick<
CommunityWsStoreState,
- "profileViewerId" | "profileAccountEpoch" | "profileRevision"
- | "profilesByUserId" | "profileRevisionsByUserId"
+ "profileViewerId" | "profileAccountEpoch" | "presenceRevision"
+ | "presenceByUserId" | "presenceRevisionsByUserId"
| "seenMessageIds" | "seenDeliveryOperations" | "botAuditEvents"
| "accessEpoch" | "accessConnected" | "channelAccessScopes" | "revokedServerIds"
| "connectionStatus" | "reconnectNow"
@@ -145,47 +135,19 @@ const initialState = (): Pick<
reconnectNow: NOOP_RECONNECT,
profileViewerId: null,
profileAccountEpoch: 0,
- profileRevision: 0,
- profilesByUserId: new Map(),
- profileRevisionsByUserId: new Map(),
+ presenceRevision: 0,
+ presenceByUserId: new Map(),
+ presenceRevisionsByUserId: new Map(),
seenMessageIds: new Set(),
seenDeliveryOperations: new Map(),
botAuditEvents: new Map(),
})
-const ZERO_REVISIONS: ProfileRevisions = { identityAbout: 0, status: 0, presence: 0 }
-
-function mergeIdentityAbout(
- profile: CommunityProfile,
- patch: CommunityProfilePatch["identityAbout"],
-) {
- if (!patch) return profile
- return { ...profile, ...patch }
-}
-
-function mergeAvatar(profile: CommunityProfile, patch: CommunityProfilePatch["avatar"]) {
- if (!patch || !Number.isSafeInteger(patch.avatarVersion) || patch.avatarVersion < 0) {
- return profile
- }
- if (profile.avatarVersion !== undefined && patch.avatarVersion <= profile.avatarVersion) {
- return profile
- }
- return { ...profile, ...patch }
-}
-
-function profileChanged(previous: CommunityProfile, next: CommunityProfile) {
- const keys = new Set([...Object.keys(previous), ...Object.keys(next)])
- for (const key of keys) {
- if (previous[key as keyof CommunityProfile] !== next[key as keyof CommunityProfile]) return true
- }
- return false
-}
-
export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {
- const writeProfiles = (
- snapshot: CommunityProfileSnapshot,
- patches: readonly CommunityProfilePatch[],
- mode: ProfileWriteMode,
+ const writePresence = (
+ snapshot: CommunityPresenceSnapshot,
+ patches: ReadonlyMap<string, CommunityPresence> | readonly [string, CommunityPresence][],
+ guardSnapshot: boolean,
) => {
const state = get()
if (
@@ -193,50 +155,26 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {
|| snapshot.viewerId !== state.profileViewerId
|| snapshot.accountEpoch !== state.profileAccountEpoch
) return false
- const revision = state.profileRevision + 1
- const guardsRevision = mode !== "patch"
- const advancesRevisionForGroups = mode !== "seed"
- let profiles: Map<string, CommunityProfile> | null = null
- let revisions: Map<string, ProfileRevisions> | null = null
- let advancesRevision = false
- for (const patch of patches) {
- const previous = (profiles ?? state.profilesByUserId).get(patch.id) ?? { id: patch.id }
- const previousRevisions = (revisions ?? state.profileRevisionsByUserId)
- .get(patch.id) ?? ZERO_REVISIONS
- let next = previous
- const identityAbout = patch.identityAbout !== undefined
- && (!guardsRevision || previousRevisions.identityAbout <= snapshot.revision)
- const status = patch.status !== undefined
- && (!guardsRevision || previousRevisions.status <= snapshot.revision)
- const presence = patch.presence !== undefined
- && (!guardsRevision || previousRevisions.presence <= snapshot.revision)
- if (identityAbout) next = mergeIdentityAbout(next, patch.identityAbout)
- next = mergeAvatar(next, patch.avatar)
- if (status) next = { ...next, ...patch.status }
- if (presence) next = { ...next, presence: patch.presence }
- if (profileChanged(previous, next)) {
- profiles ??= new Map(state.profilesByUserId)
- profiles.set(patch.id, next)
+ const entries = patches instanceof Map ? patches.entries() : patches
+ const revision = state.presenceRevision + 1
+ let presenceByUserId: Map<string, CommunityPresence> | null = null
+ let revisions: Map<string, number> | null = null
+ for (const [userId, presence] of entries) {
+ const previousRevision = state.presenceRevisionsByUserId.get(userId) ?? 0
+ if (guardSnapshot && previousRevision > snapshot.revision) continue
+ if ((presenceByUserId ?? state.presenceByUserId).get(userId) !== presence) {
+ presenceByUserId ??= new Map(state.presenceByUserId)
+ presenceByUserId.set(userId, presence)
}
- if (advancesRevisionForGroups && (identityAbout || status || presence)) {
- advancesRevision = true
- revisions ??= new Map(state.profileRevisionsByUserId)
- revisions.set(patch.id, {
- identityAbout: identityAbout ? revision : previousRevisions.identityAbout,
- status: status ? revision : previousRevisions.status,
- presence: presence ? revision : previousRevisions.presence,
- })
+ if (!guardSnapshot) {
+ revisions ??= new Map(state.presenceRevisionsByUserId)
+ revisions.set(userId, revision)
}
}
- if (profiles || advancesRevision) {
- set({
- ...(profiles ? { profilesByUserId: profiles } : {}),
- ...(advancesRevision ? {
- profileRevision: revision,
- profileRevisionsByUserId: revisions!,
- } : {}),
- })
- }
+ if (presenceByUserId || revisions) set({
+ ...(presenceByUserId ? { presenceByUserId } : {}),
+ ...(revisions ? { presenceRevision: revision, presenceRevisionsByUserId: revisions } : {}),
+ })
return true
}
@@ -252,25 +190,29 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {
profileAccountEpoch,
accessEpoch: state.accessEpoch + 1,
channelAccessScopes: new Map(),
- revokedServerIds: new Set(), profileRevision: 0,
- profilesByUserId: new Map(),
- profileRevisionsByUserId: new Map(),
+ revokedServerIds: new Set(),
+ presenceRevision: 0,
+ presenceByUserId: new Map(),
+ presenceRevisionsByUserId: new Map(),
})
return profileAccountEpoch
},
- beginProfileSnapshot: () => ({
+ beginPresenceSnapshot: () => ({
viewerId: get().profileViewerId,
accountEpoch: get().profileAccountEpoch,
- revision: get().profileRevision,
+ revision: get().presenceRevision,
}),
- seedProfiles: (snapshot, patches) => writeProfiles(snapshot, patches, "seed"),
- commitProfiles: (snapshot, patches) => writeProfiles(snapshot, patches, "commit"),
- patchProfiles: (snapshot, patches) => writeProfiles(
- { ...snapshot, revision: get().profileRevision },
- patches,
- "patch",
+ seedPresence: (snapshot, patches) => writePresence(snapshot, patches, true),
+ setPresence: (userId, presence) => writePresence(
+ {
+ viewerId: get().profileViewerId,
+ accountEpoch: get().profileAccountEpoch,
+ revision: get().presenceRevision,
+ },
+ [[userId, presence]],
+ false,
),
hasSeenMessage: (id) => get().seenMessageIds.has(id),
@@ -384,10 +326,11 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {
|| (parent && state.channelAccessScopes.get(parent)?.revoked))
},
- markAccessDisconnected: () => set((state) => ({
- accessEpoch: state.accessEpoch + 1,
- accessConnected: false,
- })),
+ markAccessDisconnected: () => {
+ const state = get()
+ if (!state.accessConnected) return
+ set({ accessConnected: false })
+ },
markAccessConnected: () => set({ accessConnected: true }),
@@ -419,28 +362,6 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => {
}
})
-// ── Selectors ────────────────────────────────────────────────────────────────
-
-export function useCommunityProfile(userId: string | null | undefined) {
- const previewProfiles = useCommunityPreviewProfiles()
- const liveProfile = useCommunityWsStore((state) =>
- previewProfiles || !userId
- ? undefined
- : state.profilesByUserId.get(userId),
- )
- return previewProfiles && userId
- ? previewProfiles.get(userId)
- : liveProfile
-}
-
-export function useProfilesByUserId(): ReadonlyMap<string, CommunityProfile> {
- const previewProfiles = useCommunityPreviewProfiles()
- const liveProfiles = useCommunityWsStore((state) =>
- previewProfiles ? null : state.profilesByUserId,
- )
- return previewProfiles ?? liveProfiles!
-}
-
const EMPTY_AUDIT_EVENTS: BotAuditEventEntry[] = []
/**
diff --git a/src/web/src/test/architecture/community-bot-avatar-cleanup-boundary.test.ts b/src/web/src/test/architecture/community-bot-avatar-cleanup-boundary.test.ts
index f40d6d1b3..a848583dc 100644
--- a/src/web/src/test/architecture/community-bot-avatar-cleanup-boundary.test.ts
+++ b/src/web/src/test/architecture/community-bot-avatar-cleanup-boundary.test.ts
@@ -57,7 +57,7 @@ describe("bot and machine-cascade avatar cleanup C2 boundary", () => {
it("keeps the human self-avatar branch on Better Auth and user storage", () => {
const meAvatar = source("src/web/src/app/api/community/users/me/avatar/route.ts")
expect(meAvatar).toContain("handleUserAvatarUpload(req, ctx.env, userId)")
- expect(meAvatar).toContain("const auth = createAuth(ctx.env)")
+ expect(meAvatar).toContain("const auth = getAuth(ctx.env)")
expect(meAvatar).toContain("auth.api.updateUser")
expect(meAvatar).toContain("userAvatarUrl(userId)")
})
diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.ts
index 2db49a381..93db975c4 100644
--- a/src/web/src/test/e2e-ui/04-dm.spec.ts
+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts
@@ -39,7 +39,10 @@ test.describe.serial("direct messages", () => {
}
})
- const notificationRefresh = notificationResponsesFinished(bob.page, notificationPaths.filter((path) => path.includes("/inbox/")))
+ const notificationRefresh = notificationResponsesFinished(
+ bob.page,
+ notificationPaths.filter((path) => path.endsWith("/attention")),
+ )
const dmId = await seedDm("alice", userId("bob"))
const body = `first inbox DM ${Date.now()}`
const messageId = await seedDmMessage("alice", dmId, body)
@@ -47,6 +50,8 @@ test.describe.serial("direct messages", () => {
event.type === "community:unread.bump" && event.channelId === dmId && event.userId === userId("bob"))).toBe(true)
await notificationRefresh
await expect.poll(() => dmsGets).toBe(1)
+ releaseCanonical()
+ await canonicalSettled
const routeHistory: string[] = []
const recordRoute = (frame: Frame) => {
if (frame === bob.page.mainFrame()) routeHistory.push(new URL(frame.url()).pathname)
diff --git a/src/web/src/test/e2e-ui/13-mentions.spec.ts b/src/web/src/test/e2e-ui/13-mentions.spec.ts
index e7dd3a485..fc985e3c6 100644
--- a/src/web/src/test/e2e-ui/13-mentions.spec.ts
+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts
@@ -14,8 +14,7 @@ import {
// as `@Name#dddd`, which lets a name with spaces render as one pill AND makes a
// same-name mention resolve to the EXACT person on click (regression for the
// sanitize allowlist case-mismatch that stripped the discriminator — bugfix
-// 4044fd6c). A hand-typed bare `@name` is not a mention. See
-// plans/mandatory-mention-discriminator.md.
+// 4044fd6c). A hand-typed bare `@name` is not a mention.
//
// Fixture: Bob and Carol are both renamed "John Doe" (spaced name), each keeping
// its own auto-assigned discriminator — so the same journey exercises the
diff --git a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts
index 9d476fbc9..682f1392a 100644
--- a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts
+++ b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts
@@ -16,7 +16,7 @@ import {
// avatars, and DM presence stability. Covers the batch that made forum posts
// notify only their participants (like threads), moved tag editing onto each
// post card, showed participant AvatarGroups, and fixed the DM presence flicker
-// on refresh. See plans/community-machine-fixes-2026-07.md.
+// on refresh.
test.describe.serial("forum post tags + participant avatars", () => {
let serverId: string
diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts
index 30d056fe2..552ff4738 100644
--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts
+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts
@@ -29,8 +29,7 @@ import {
//
// Fixture: alice (owner) + bob + carol all join the server. The public channel
// sees everyone; the private channel's audience is alice+bob ONLY — carol is
-// the negative probe (present in public, absent in private). See
-// plans/e2e-mention-scope.md.
+// the negative probe: present in public, absent in private.
test.describe.serial("mentions — candidate scope", () => {
let serverId: string
let publicChannelId: string
@@ -76,9 +75,8 @@ test.describe.serial("mentions — candidate scope", () => {
// Open the @-popup in the current composer and return the option locators. The
// popup keys each row (members AND @everyone) off its item id — a member
// row id is the server-member row id (identical in server + channel lists), a
- // virtual row id is the literal "everyone". (@here was removed —
- // plans/remove-here-mention.md; `here` is exposed here only to assert its
- // ABSENCE.)
+ // virtual row id is the literal "everyone". `here` is exposed here only to
+ // assert that the removed @here row stays absent.
async function openMentionPopup(page: Page, root: Page | Locator = page) {
const editable = composerEditable(page, root)
await editable.click()
@@ -111,7 +109,7 @@ test.describe.serial("mentions — candidate scope", () => {
await expect(opt.bob).toBeVisible({ timeout: 15_000 })
await expect(opt.carol).toBeVisible({ timeout: 15_000 })
await expect(opt.everyone).toBeVisible()
- // @here was removed — its popup row must not appear (plans/remove-here-mention.md).
+ // @here was removed, so its popup row must not appear.
await expect(opt.here).toHaveCount(0)
// Self (alice) is filtered out of the popup at the composer — keyed by her
// server-member row id (the same id the popup options use), not her userId.
@@ -139,7 +137,7 @@ test.describe.serial("mentions — candidate scope", () => {
const opt = await openMentionPopup(page)
await expect(opt.bob).toBeVisible({ timeout: 15_000 })
await expect(opt.everyone).toBeVisible()
- // @here was removed — its popup row must not appear (plans/remove-here-mention.md).
+ // @here was removed, so its popup row must not appear.
await expect(opt.here).toHaveCount(0)
// Carol is a server member but NOT in this private channel's audience.
await expect(opt.carol).toHaveCount(0)
diff --git a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts
index a62abf4e1..d2b2f54fa 100644
--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts
+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts
@@ -175,7 +175,6 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
successfulResponses.push(response.url())
}
})
-
const initialCombined = page.waitForResponse((response) =>
response.ok() && isSidebarRequest(response.url(), serverId),
)
@@ -402,12 +401,24 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
expect(await participantUserIds(page, ordinaryThreadId)).not.toContain(userId("bob"))
})
- test("sidebar top-level and child navigation reuse the warm flat base", async ({ asUser }) => {
+ test("sidebar top-level and child navigation reuse the warm flat base", async ({ asUser }, testInfo) => {
const { page } = await asUser("alice")
const requests: string[] = []
+ const successfulResponses: string[] = []
+ const failedThreadMessages: string[] = []
page.on("request", (request) => {
if (request.method() === "GET") requests.push(request.url())
})
+ page.on("response", (response) => {
+ if (response.request().method() === "GET" && response.ok()) {
+ successfulResponses.push(response.url())
+ }
+ })
+ page.on("requestfailed", (request) => {
+ if (isChannelMessagesRequest(request.url(), threadId)) {
+ failedThreadMessages.push(request.failure()?.errorText ?? "unknown")
+ }
+ })
const initialCombined = page.waitForResponse((response) =>
response.ok() && isSidebarRequest(response.url(), serverId),
@@ -426,12 +437,62 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
expect(requests.filter((url) => isSidebarRequest(url, serverId))).toHaveLength(0)
requests.length = 0
+ successfulResponses.length = 0
+ let releaseRetained!: () => void
+ let retainedStarted!: () => void
+ const retainedGate = new Promise<void>((resolve) => { releaseRetained = resolve })
+ const retainedRequestStarted = new Promise<void>((resolve) => { retainedStarted = resolve })
+ await page.route("**/api/community/servers/*/channels?*", async (route) => {
+ const url = route.request().url()
+ if (
+ isSidebarRequest(url, serverId)
+ && new URL(url).searchParams.get("retainId") === threadId
+ ) {
+ retainedStarted()
+ await retainedGate
+ }
+ await route.continue()
+ })
+ const clickStartedAt = Date.now()
await page.getByTestId(tid.forumSidebarThread(threadId)).click()
await expect.poll(() => new URL(page.url()).pathname).toBe(
`/c/channels/${serverId}/${threadId}`,
)
- await expect(childPanel(page).getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })
- expect(requests.filter((url) => isSidebarRequest(url, serverId))).toHaveLength(0)
+ await retainedRequestStarted
+ await expect(childPanel(page).getByRole("heading", { name: forumTitle }))
+ .toBeVisible({ timeout: 1_000 })
+ const warmVisibleMs = Date.now() - clickStartedAt
+ releaseRetained()
+ await expect.poll(() => successfulResponses.filter((url) => (
+ isSidebarRequest(url, serverId)
+ && new URL(url).searchParams.get("retainId") === threadId
+ )).length).toBe(1)
+ const retainedSuccessMs = Date.now() - clickStartedAt
+ await page.waitForTimeout(1_200)
+ expect(requests.filter((url) => (
+ isSidebarRequest(url, serverId)
+ && new URL(url).searchParams.get("retainId") === threadId
+ ))).toHaveLength(1)
+ const threadMessageRequests = requests.filter((url) => (
+ isChannelMessagesRequest(url, threadId)
+ ))
+ const successfulThreadMessages = successfulResponses.filter((url) => (
+ isChannelMessagesRequest(url, threadId)
+ ))
+ expect(successfulThreadMessages).toHaveLength(1)
+ await testInfo.attach("warm-forum-route-performance", {
+ body: JSON.stringify({
+ warmVisibleMs,
+ retainedSuccessMs,
+ retainedRequests: 1,
+ threadMessageAttempts: threadMessageRequests.length,
+ threadMessageUrls: threadMessageRequests,
+ threadMessageFailures: failedThreadMessages,
+ threadMessageSuccesses: successfulThreadMessages.length,
+ }),
+ contentType: "application/json",
+ })
+ await page.unroute("**/api/community/servers/*/channels?*")
await page.goBack()
await expect.poll(() => new URL(page.url()).pathname).toBe(
diff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts
index c696d9073..a768729f6 100644
--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts
+++ b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts
@@ -1,4 +1,4 @@
-import type { Locator, Page, TestInfo, WebSocketRoute } from "@playwright/test"
+import type { Page, WebSocketRoute } from "@playwright/test"
import { test, expect } from "./_fixtures/community-fixture"
import {
composerEditable,
@@ -6,101 +6,10 @@ import {
} from "./_fixtures/actions"
import { seedChannel, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
+import "./community-cache-first-warm-reload.journey"
const USER_WS_AUTH_CONSUMED_ATTRIBUTE = "data-e2e-user-ws-auth-consumed"
-type AppEdgeEvidence = {
- token: string
- ariaHidden: string | null
- pointerEvents: string
- focusableCount: number
- appBackground: string
- surfaceBackground: string
- surface: { top: number; bottom: number; height: number }
- top: { top: number; bottom: number; height: number; backgroundImage: string }
- bottom: { top: number; bottom: number; height: number; backgroundImage: string }
- rootOverflowX: number
- rootOverflowY: number
-}
-
-async function appEdgeEvidence(surface: Locator): Promise<AppEdgeEvidence> {
- return surface.evaluate((element) => {
- const fade = element.querySelector<HTMLElement>('[data-slot="app-edge-fade"]')
- const top = fade?.querySelector<HTMLElement>('[data-app-edge="top"]')
- const bottom = fade?.querySelector<HTMLElement>('[data-app-edge="bottom"]')
- if (!fade || !top || !bottom) throw new Error("missing app edge fade")
- const probe = document.createElement("div")
- probe.style.background = "var(--app-bg)"
- probe.style.position = "fixed"
- probe.style.visibility = "hidden"
- document.body.appendChild(probe)
- const appBackground = getComputedStyle(probe).backgroundColor
- probe.remove()
- const surfaceRect = element.getBoundingClientRect()
- const topRect = top.getBoundingClientRect()
- const bottomRect = bottom.getBoundingClientRect()
- const root = document.documentElement
- return {
- token: getComputedStyle(root).getPropertyValue("--app-edge-fade-size").trim(),
- ariaHidden: fade.getAttribute("aria-hidden"),
- pointerEvents: getComputedStyle(fade).pointerEvents,
- focusableCount: fade.querySelectorAll("button, a, input, select, textarea, [tabindex]").length,
- appBackground,
- surfaceBackground: getComputedStyle(element).backgroundColor,
- surface: { top: surfaceRect.top, bottom: surfaceRect.bottom, height: surfaceRect.height },
- top: {
- top: topRect.top,
- bottom: topRect.bottom,
- height: topRect.height,
- backgroundImage: getComputedStyle(top).backgroundImage,
- },
- bottom: {
- top: bottomRect.top,
- bottom: bottomRect.bottom,
- height: bottomRect.height,
- backgroundImage: getComputedStyle(bottom).backgroundImage,
- },
- rootOverflowX: root.scrollWidth - root.clientWidth,
- rootOverflowY: root.scrollHeight - root.clientHeight,
- }
- })
-}
-
-function expectAppEdgeEvidence(evidence: AppEdgeEvidence) {
- expect(evidence.token).toBe("60px")
- expect(evidence.ariaHidden).toBe("true")
- expect(evidence.pointerEvents).toBe("none")
- expect(evidence.focusableCount).toBe(0)
- expect(evidence.top.height).toBeCloseTo(60, 1)
- expect(evidence.bottom.height).toBeCloseTo(60, 1)
- expect(evidence.top.top).toBeCloseTo(evidence.surface.top, 1)
- expect(evidence.top.bottom).toBeCloseTo(evidence.surface.top + 60, 1)
- expect(evidence.bottom.top).toBeCloseTo(evidence.surface.bottom - 60, 1)
- expect(evidence.bottom.bottom).toBeCloseTo(evidence.surface.bottom, 1)
- expect(evidence.top.backgroundImage).toContain("linear-gradient")
- expect(evidence.bottom.backgroundImage).toContain("linear-gradient")
- expect(evidence.top.backgroundImage).toContain(evidence.appBackground)
- expect(evidence.bottom.backgroundImage).toContain(evidence.appBackground)
- expect(evidence.rootOverflowX).toBe(0)
- expect(evidence.rootOverflowY).toBe(0)
-}
-
-async function attachEvidence(
- testInfo: TestInfo,
- page: Page,
- name: string,
- evidence: unknown,
-) {
- await testInfo.attach(`${name}.json`, {
- body: Buffer.from(JSON.stringify(evidence, null, 2)),
- contentType: "application/json",
- })
- await testInfo.attach(`${name}.png`, {
- body: await page.screenshot(),
- contentType: "image/png",
- })
-}
-
async function installUserWsAuthConsumedBarrier(page: Page) {
await page.addInitScript(({ attribute }) => {
const NativeWebSocket = window.WebSocket
@@ -113,8 +22,6 @@ async function installUserWsAuthConsumedBarrier(page: Page) {
try {
const message = JSON.parse(event.data) as { type?: string }
if (message.type !== "auth.ok") return
- // The next task runs after the current message event has finished
- // dispatching to the application's WebSocket listener.
setTimeout(() => {
document.documentElement.setAttribute(attribute, "true")
}, 0)
@@ -152,19 +59,18 @@ test("slow auth and an initial retry never block a cold Community page", async (
try {
await alice.page.goto(`/c/channels/${serverId}/${channelId}`)
const composer = composerEditable(alice.page)
- const overlay = alice.page.getByTestId(tid.wsReconnectOverlay)
await expect(composer).toBeVisible({ timeout: 30_000 })
await expect.poll(() => tokenRequests).toBeGreaterThan(0)
await alice.page.waitForTimeout(1_600)
- await expect(overlay).toHaveCount(0)
+ await expect(alice.page.getByTestId(tid.wsReconnectOverlay)).toHaveCount(0)
+ await expect.poll(() => composer.evaluate((element) => element.closest("[inert]") !== null))
+ .toBe(false)
await composer.fill("Cold start stays usable")
await expect(composer).toContainText("Cold start stays usable")
holdTokens = false
releaseTokens()
await expect.poll(() => socketAttempts, { timeout: 20_000 }).toBeGreaterThan(1)
- await alice.page.waitForTimeout(1_600)
- await expect(overlay).toHaveCount(0)
await expect(composer).toContainText("Cold start stays usable")
} finally {
holdTokens = false
@@ -172,66 +78,10 @@ test("slow auth and an initial retry never block a cold Community page", async (
}
})
-test("app edge fade keeps the unresolved main surface native-aligned across theme, size, and motion", async ({ asUser }, testInfo) => {
- test.setTimeout(90_000)
- const suffix = Date.now().toString(36)
- const serverId = await seedServer("alice", `Edge fade ${suffix}`)
- const channelId = await seedChannel("alice", serverId, `edge-fade-${suffix}`)
- const alice = await asUser("alice")
-
- let releaseServerDetail!: () => void
- const serverDetailGate = new Promise<void>((resolve) => {
- releaseServerDetail = resolve
- })
- const detailPattern = new RegExp(`/api/community/servers/${serverId}/(?:categories|channels|unreads)(?:\\?|$)`)
- await alice.page.route(detailPattern, async (route) => {
- await serverDetailGate
- await route.continue()
- })
-
- try {
- await alice.page.setViewportSize({ width: 1280, height: 900 })
- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)
- const unresolved = alice.page.locator("[data-community-unresolved-main]").first()
- await expect(unresolved).toBeVisible({ timeout: 10_000 })
- const matrix = [
- { name: "skeleton-1280-light-motion", width: 1280, height: 900, colorScheme: "light", reducedMotion: "no-preference" },
- { name: "skeleton-390-dark-motion", width: 390, height: 844, colorScheme: "dark", reducedMotion: "no-preference" },
- { name: "skeleton-1280-dark-reduced", width: 1280, height: 900, colorScheme: "dark", reducedMotion: "reduce" },
- { name: "skeleton-390-light-reduced", width: 390, height: 844, colorScheme: "light", reducedMotion: "reduce" },
- ] as const
-
- for (const entry of matrix) {
- await alice.page.emulateMedia({
- colorScheme: entry.colorScheme,
- reducedMotion: entry.reducedMotion,
- })
- await alice.page.setViewportSize({ width: entry.width, height: entry.height })
- await expect.poll(() => alice.page.evaluate(() => document.documentElement.classList.contains("dark")))
- .toBe(entry.colorScheme === "dark")
- const edge = await appEdgeEvidence(unresolved)
- expectAppEdgeEvidence(edge)
- expect(edge.surfaceBackground).toBe(edge.appBackground)
- await expect(unresolved.getByRole("heading", { name: "Connecting…" })).toBeVisible()
- await expect(unresolved.locator('[data-slot="skeleton"]')).toHaveCount(0)
- await expect(unresolved.getByRole("dialog")).toHaveCount(0)
- const waiting = await unresolved.evaluate((element) => ({
- animationName: getComputedStyle(element).animationName,
- textAnimation: getComputedStyle(element.querySelector(".community-ws-connecting-letter")!).animationName,
- }))
- expect(waiting.animationName).toBe("none")
- expect(waiting.textAnimation === "none").toBe(entry.reducedMotion === "reduce")
- await attachEvidence(testInfo, alice.page, entry.name, { edge, waiting, entry })
- }
- } finally {
- releaseServerDetail()
- }
-})
-
-test("app edge fade keeps a real WebSocket outage native-aligned and Retry restores it", async ({ asUser }, testInfo) => {
+test("a real WebSocket outage keeps cached content interactive and Retry reconnects", async ({ asUser }) => {
test.setTimeout(120_000)
- const serverId = await seedServer("alice", `Reconnect overlay ${Date.now()}`)
- const channelId = await seedChannel("alice", serverId, "reconnect-overlay")
+ const serverId = await seedServer("alice", `Reconnect status ${Date.now()}`)
+ const channelId = await seedChannel("alice", serverId, "reconnect-status")
const alice = await asUser("alice")
let authenticatedConnections = 0
alice.page.on("websocket", (socket) => {
@@ -246,171 +96,52 @@ test("app edge fade keeps a real WebSocket outage native-aligned and Retry resto
aliceWs = ws
ws.connectToServer()
})
- await alice.page.emulateMedia({ reducedMotion: "reduce", colorScheme: "dark" })
await alice.page.setViewportSize({ width: 390, height: 844 })
await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)
const composer = composerEditable(alice.page)
await expect(composer).toBeVisible()
- await expect(alice.page.getByTestId(tid.wsReconnectOverlay)).toHaveCount(0)
try {
await alice.context.setOffline(true)
expect(aliceWs).not.toBeNull()
- await aliceWs!.close({ code: 1012, reason: "reconnect overlay e2e outage" })
+ await aliceWs!.close({ code: 1012, reason: "non-blocking reconnect e2e outage" })
- const overlay = alice.page.getByTestId(tid.wsReconnectOverlay)
- await expect(overlay).toBeVisible({ timeout: 10_000 })
- await expect(overlay).toHaveAttribute("data-ws-status", "reconnecting")
- await expect(overlay).toBeFocused()
- await expect(overlay.getByRole("status")).toContainText("Connecting…")
- const reconnectingEdge = await appEdgeEvidence(overlay)
- expectAppEdgeEvidence(reconnectingEdge)
- expect(reconnectingEdge.surfaceBackground).not.toBe(reconnectingEdge.appBackground)
- const reconnectingEvidence = await overlay.evaluate((element) => {
- const rect = element.getBoundingClientRect()
- const content = element.previousElementSibling as HTMLElement | null
- const connectingMotion = element.querySelector<HTMLElement>("[data-connecting-motion]")
- const connectingLetter = element.querySelector<HTMLElement>(".community-ws-connecting-letter")
- const connectingStyle = connectingMotion ? getComputedStyle(connectingMotion) : null
- const loaderStyle = getComputedStyle(element.querySelector<HTMLElement>("[data-slot='text-loader']")!)
- const label = element.querySelector<HTMLElement>(".community-ws-connecting-text")!
- const artwork = connectingMotion!.firstElementChild!.getBoundingClientRect()
- const text = label.getBoundingClientRect()
- return {
- ariaHidden: content?.getAttribute("aria-hidden"),
- inert: content?.hasAttribute("inert"),
- iconAnimationName: connectingStyle?.animationName,
- letterAnimationName: connectingLetter ? getComputedStyle(connectingLetter).animationName : null,
- svgCount: connectingMotion?.querySelectorAll("svg").length,
- artworkWidth: artwork.width,
- artworkHeight: artwork.height,
- labelWidth: text.width,
- verticalGap: text.top - artwork.bottom,
- rowGap: loaderStyle.rowGap,
- fontFamily: getComputedStyle(label).fontFamily,
- flexDirection: loaderStyle.flexDirection,
- loaderDisplay: loaderStyle.display,
- loaderElement: connectingMotion?.tagName.toLowerCase(),
- rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
- viewport: { width: innerWidth, height: innerHeight },
- }
- })
- expect(reconnectingEvidence).toMatchObject({
- ariaHidden: "true",
- inert: true,
- iconAnimationName: "none",
- letterAnimationName: "none",
- svgCount: 5,
- rowGap: "8px",
- flexDirection: "column",
- loaderDisplay: "flex",
- loaderElement: "div",
- rect: { x: 0, y: 0, width: 390, height: 844 },
- viewport: { width: 390, height: 844 },
- })
- expect(reconnectingEvidence.artworkWidth).toBeCloseTo(172.8, 1)
- expect(reconnectingEvidence.artworkHeight).toBeCloseTo(172.8, 1)
- expect(reconnectingEvidence.verticalGap).toBeCloseTo(-6.4, 1)
- expect(reconnectingEvidence.fontFamily).not.toMatch(/mono/i)
- expect(reconnectingEvidence.artworkWidth * 660 / 1080).toBeGreaterThan(reconnectingEvidence.labelWidth)
- const artwork = overlay.locator("[data-connecting-motion]")
- const staticMarkup = await artwork.innerHTML()
- await alice.page.waitForTimeout(120)
- expect(await artwork.innerHTML()).toBe(staticMarkup)
- await alice.page.emulateMedia({ reducedMotion: "no-preference" })
- await expect.poll(() => artwork.innerHTML()).not.toBe(staticMarkup)
- await alice.page.waitForTimeout(2600)
- await alice.page.screenshot({ path: testInfo.outputPath("390-logo.png") })
- await alice.page.setViewportSize({ width: 1280, height: 900 })
- expect((await artwork.locator("span").first().boundingBox())!.width).toBe(192)
- await alice.page.screenshot({ path: testInfo.outputPath("1280-logo.png") })
- await expect.poll(() => artwork.locator("div").evaluateAll((elements) => elements.some((element) => (element as HTMLElement).style.clipPath.startsWith("inset(-300px")))).toBe(true)
- await alice.page.screenshot({ path: testInfo.outputPath("1280-bots.png") })
- await alice.page.setViewportSize({ width: 390, height: 844 })
- await alice.page.screenshot({ path: testInfo.outputPath("390-bots.png") })
- await alice.page.emulateMedia({ reducedMotion: "reduce" })
- await expect.poll(() => artwork.innerHTML()).toBe(staticMarkup)
- await expect.poll(() => composer.evaluate((element) =>
- element.closest("[inert]") !== null,
- )).toBe(true)
- await alice.page.keyboard.press("Tab")
- expect(await alice.page.evaluate(() =>
- document.activeElement?.closest("[inert]") !== null,
- )).toBe(false)
- const mobileReconnectPath = testInfo.outputPath("390-dark-reconnecting-reduced-motion.png")
- await alice.page.screenshot({ path: mobileReconnectPath })
- await testInfo.attach("390-dark-reconnecting-reduced-motion.png", {
- path: mobileReconnectPath,
- contentType: "image/png",
- })
- await testInfo.attach("390-dark-reconnecting-reduced-motion-edge.json", {
- body: Buffer.from(JSON.stringify(reconnectingEdge, null, 2)),
- contentType: "application/json",
- })
-
- await alice.page.setViewportSize({ width: 1280, height: 900 })
- expect(await overlay.boundingBox()).toMatchObject({ x: 0, y: 0, width: 1280, height: 900 })
- const desktopReconnectPath = testInfo.outputPath("1280-dark-reconnecting-reduced-motion.png")
- await alice.page.screenshot({ path: desktopReconnectPath })
- await testInfo.attach("1280-dark-reconnecting-reduced-motion.png", {
- path: desktopReconnectPath,
- contentType: "image/png",
- })
-
- await alice.page.emulateMedia({ reducedMotion: "reduce", colorScheme: "light" })
- await expect.poll(() => alice.page.evaluate(() => document.documentElement.classList.contains("dark")))
+ await alice.page.waitForTimeout(1_600)
+ await expect(alice.page.getByTestId(tid.wsReconnectOverlay)).toHaveCount(0)
+ await expect(composer).toBeVisible()
+ await expect.poll(() => composer.evaluate((element) => element.closest("[inert]") !== null))
.toBe(false)
- const desktopLightReconnectPath = testInfo.outputPath("1280-light-reconnecting-reduced-motion.png")
- await alice.page.screenshot({ path: desktopLightReconnectPath })
- await testInfo.attach("1280-light-reconnecting-reduced-motion.png", {
- path: desktopLightReconnectPath,
- contentType: "image/png",
- })
-
- await alice.page.setViewportSize({ width: 390, height: 844 })
- const mobileLightReconnectPath = testInfo.outputPath("390-light-reconnecting-reduced-motion.png")
- await alice.page.screenshot({ path: mobileLightReconnectPath })
- await testInfo.attach("390-light-reconnecting-reduced-motion.png", {
- path: mobileLightReconnectPath,
- contentType: "image/png",
- })
+ await composer.focus()
+ await expect(composer).toBeFocused()
+ const status = alice.page.getByTestId(tid.wsReconnectOverlay)
const retry = alice.page.getByTestId(tid.wsRetry)
await expect(retry).toBeVisible({ timeout: 40_000 })
- await expect(overlay).toHaveAttribute("data-ws-status", "failed")
- await expect(overlay.getByRole("alert")).toContainText("Connection lost")
- const failedEdge = await appEdgeEvidence(overlay)
- expectAppEdgeEvidence(failedEdge)
- await testInfo.attach("failed-edge.json", {
- body: Buffer.from(JSON.stringify(failedEdge, null, 2)),
- contentType: "application/json",
- })
+ await expect(status).toHaveAttribute("data-ws-status", "failed")
+ await expect(status).not.toHaveAttribute("aria-modal")
+ await expect(status).toContainText("Cached content is still available.")
+ const rect = await status.boundingBox()
+ expect(rect).not.toBeNull()
+ expect(rect!.width).toBeLessThan(390)
+ expect(rect!.height).toBeLessThan(844)
expect((await retry.boundingBox())!.height).toBeGreaterThanOrEqual(44)
- await alice.page.setViewportSize({ width: 1280, height: 900 })
- const desktopRect = await overlay.boundingBox()
- expect(desktopRect).toMatchObject({ x: 0, y: 0, width: 1280, height: 900 })
- expect((await retry.boundingBox())!.height).toBeGreaterThanOrEqual(40)
- await testInfo.attach("1280-failed-retry.png", {
- body: await alice.page.screenshot(),
- contentType: "image/png",
- })
-
await alice.context.setOffline(false)
- await retry.click()
- await expect(overlay).toHaveCount(0, { timeout: 20_000 })
+ await retry.focus()
+ await expect(retry).toBeFocused()
+ await alice.page.keyboard.press("Enter")
+ await expect(status).toHaveCount(0, { timeout: 20_000 })
await expect(composer).toBeVisible()
- await expect.poll(() => composer.evaluate((element) =>
- element.closest("[inert]") !== null,
- )).toBe(false)
- expect(authenticatedConnections).toBeGreaterThanOrEqual(2)
- await testInfo.attach("ws-recovery-evidence", { body: JSON.stringify({ authenticatedConnections, status: "connected", overlayRemoved: true }), contentType: "application/json" })
+ await expect.poll(() => composer.evaluate((element) => element.closest("[inert]") !== null))
+ .toBe(false)
+ await expect.poll(() => authenticatedConnections, { timeout: 20_000 })
+ .toBeGreaterThanOrEqual(2)
} finally {
- await alice.context.setOffline(false)
+ await alice.context.setOffline(false).catch(() => {})
}
})
-test("an active onboarding form yields focus priority during outage, then resumes", async ({ browser }, testInfo) => {
+test("an active onboarding form keeps focus priority during a reconnect", async ({ browser }) => {
test.setTimeout(90_000)
const context = await browser.newContext({ viewport: { width: 390, height: 844 } })
const page = await context.newPage()
@@ -433,72 +164,36 @@ test("an active onboarding form yields focus priority during outage, then resume
)
await page.getByRole("button", { name: "Sign in", exact: true }).click()
await page.waitForURL("**/c/me", { waitUntil: "commit" })
- await expect.poll(async () => {
- const cookies = await page.context().cookies()
- return cookies.some((cookie) => cookie.name === "is_new_signup")
- }).toBe(false)
-
- const onboarding = page.getByTestId(tid.onboardingHarnessDialog)
- await page.waitForTimeout(250)
- await expect(page).toHaveURL(/\/c\/me$/)
- await expect(onboarding).toHaveCount(0)
-
await page.goto("/c/me/machines")
- const startOnboarding = page.getByTestId(tid.onboardingStart)
- await expect(startOnboarding).toBeVisible()
- await startOnboarding.click()
+ await page.getByTestId(tid.onboardingStart).click()
+ const onboarding = page.getByTestId(tid.onboardingHarnessDialog)
await expect(onboarding).toBeVisible()
- await expect(onboarding.getByRole("heading", { name: "Which harness do you already use?" })).toBeVisible()
await expect(page.locator("html")).toHaveAttribute(
USER_WS_AUTH_CONSUMED_ATTRIBUTE,
"true",
{ timeout: 20_000 },
)
+ const onboardingAction = onboarding.getByRole("radio", { name: "Claude Code" })
+ await onboardingAction.focus()
blockUserWs = true
expect(userWs).not.toBeNull()
await userWs!.close({ code: 1012, reason: "active onboarding reconnect e2e outage" })
- const overlay = page.getByTestId(tid.wsReconnectOverlay)
- await expect(overlay).toBeVisible({ timeout: 10_000 })
- await expect(overlay).toBeFocused()
- const stacking = await page.evaluate((overlayId) => {
- const reconnect = document.querySelector<HTMLElement>(`[data-testid='${overlayId}']`)
- const dialog = document.querySelector<HTMLElement>("[role='dialog']")
- if (!reconnect || !dialog) throw new Error("stacking targets are missing")
- const reconnectRect = reconnect.getBoundingClientRect()
- const topAtCenter = document.elementFromPoint(
- reconnectRect.left + reconnectRect.width / 2,
- reconnectRect.top + reconnectRect.height / 2,
- )
- return {
- reconnect: Number.parseInt(getComputedStyle(reconnect).zIndex, 10),
- dialog: Number.parseInt(getComputedStyle(dialog).zIndex, 10),
- topBelongsToReconnect: reconnect.contains(topAtCenter),
- }
- }, tid.wsReconnectOverlay)
- expect(stacking.reconnect).toBeGreaterThanOrEqual(stacking.dialog)
- expect(stacking.topBelongsToReconnect).toBe(true)
-
- await expect(overlay).toBeFocused()
- await page.keyboard.press("Tab")
- expect(await page.evaluate((overlayId) => {
- const reconnect = document.querySelector(`[data-testid='${overlayId}']`)
- return reconnect?.contains(document.activeElement) ?? false
- }, tid.wsReconnectOverlay)).toBe(true)
- await testInfo.attach("390-active-onboarding-reconnecting.png", {
- body: await page.screenshot(),
- contentType: "image/png",
- })
+ await page.waitForTimeout(1_600)
+ const failedStatus = page.getByTestId(tid.wsReconnectOverlay)
+ if (await failedStatus.count()) {
+ await expect(failedStatus).toHaveAttribute("data-ws-status", "failed")
+ await expect(failedStatus).not.toHaveAttribute("aria-modal")
+ }
+ await expect(onboarding).toBeVisible()
+ await expect(onboardingAction).toBeFocused()
+ expect(await onboarding.evaluate((element) => element.closest("[inert]") !== null)).toBe(false)
blockUserWs = false
- await expect(overlay).toHaveCount(0, { timeout: 20_000 })
await expect(onboarding).toBeVisible()
- await expect(onboarding.getByRole("heading", { name: "Which harness do you already use?" })).toBeVisible()
} finally {
- if (!page.isClosed()) {
- blockUserWs = false
- await context.close()
- }
+ blockUserWs = false
+ await context.close().catch(() => {})
}
})
diff --git a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts
index fe5046134..4b95c1652 100644
--- a/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts
+++ b/src/web/src/test/e2e-ui/25-composer-accessory-rail-occupancy.spec.ts
@@ -15,12 +15,20 @@ test.afterAll(async () => {
expect(restorations.map((result) => result.status)).toEqual(["fulfilled", "fulfilled"])
})
-async function sendExactMessage(sender: Page, text: string) {
+async function sendExactMessage(sender: Page, receiver: Page, text: string) {
const editable = composerEditable(sender)
await editable.click()
await sender.keyboard.press("ControlOrMeta+A")
await sender.keyboard.press("Backspace")
+ const responsePromise = sender.waitForResponse((response) => (
+ response.request().method() === "POST"
+ && /\/api\/community\/channels\/[^/]+\/messages$/.test(new URL(response.url()).pathname)
+ ))
await sendMessage(sender, text)
+ const response = await responsePromise
+ expect(response.status()).toBe(201)
+ const payload = await response.json() as { message: { id: string } }
+ await expect(receiver.getByTestId(tid.message(payload.message.id))).toBeVisible()
}
type Rect = {
@@ -483,6 +491,7 @@ test("composer accessory rail reallocates every occupied slot without overflow",
await sendExactMessage(
bob.page,
+ alice.page,
`long typing clear ${Date.now()}`,
)
await expect(alice.page.getByTestId(tid.typingIndicator)).toHaveCount(0)
@@ -538,10 +547,12 @@ test("composer accessory rail reallocates every occupied slot without overflow",
await sendExactMessage(
bob.page,
+ alice.page,
`multiple typing clear ${Date.now()}`,
)
await sendExactMessage(
carol.page,
+ alice.page,
`short typing clear ${Date.now()}`,
)
await expect(alice.page.getByTestId(tid.typingIndicator)).toHaveCount(0)
@@ -569,6 +580,7 @@ test("composer accessory rail reallocates every occupied slot without overflow",
await sendExactMessage(
bob.page,
+ alice.page,
`theme typing clear ${Date.now()}`,
)
await expect(alice.page.getByTestId(tid.typingIndicator)).toHaveCount(0)
diff --git a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
index cae8df47d..ceacc7c57 100644
--- a/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
+++ b/src/web/src/test/e2e-ui/28-community-delete-media-cleanup.spec.ts
@@ -175,7 +175,11 @@ test("existing channel/server deletes converge UI, WS, pending rows, linked medi
expect(await status("alice", `/api/community/channels/${deleteLanding?.[2]}`)).toBe(200)
await expect(alice.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)
await expect(alice.page.getByTestId(tid.channelRow(serverChannelId))).toHaveCount(0)
- await expect(alice.page.getByTestId(tid.composerInput)).toHaveCount(0)
+ // The cache-first destination may already mount its own composer. Pin the
+ // actual regression: no composer from the deleted channel may survive.
+ await expect(alice.page.locator(
+ `[data-placeholder="Message /delete-server-${stamp}"]`,
+ )).toHaveCount(0)
await expect(bob.page.getByTestId(tid.serverIcon(serverId))).toHaveCount(0)
await expect.poll(() => aliceDeletes.frames.filter((frame) => (
frame.type === "community:server.delete" && frame.serverId === serverId
diff --git a/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts b/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts
index bfa1d431f..b68e6b8e8 100644
--- a/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts
+++ b/src/web/src/test/e2e-ui/28-thread-realtime-audiences.spec.ts
@@ -36,7 +36,7 @@ for (const parentType of ["text", "forum"] as const) {
await expect.poll(() => trace.events.some((event) => event.type === "community:message.create" && event.message.id === firstId)).toBe(true)
await bob.page.waitForTimeout(750)
expect(trace.events.filter((event) => (event.type === "community:unread.bump" || event.type === "community:mention.create") && event.channelId === childId)).toEqual([])
- expect(trace.requests.filter((path) => path.startsWith("/api/community/users/me/inbox/") || path === "/api/community/users/me/dms" || path === `/api/community/channels/${childId}/read`)).toEqual([])
+ expect(trace.requests.filter((path) => path === "/api/community/users/me/attention" || path === "/api/community/users/me/dms" || path === `/api/community/channels/${childId}/read`)).toEqual([])
await bob.page.goto(`/c/channels/${serverId}/${childId}`)
await expect(bob.page.getByTestId(tid.message(firstId))).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
index 042b79ba1..ea5da4903 100644
--- a/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
+++ b/src/web/src/test/e2e-ui/32-mobile-ws-foreground-validation.spec.ts
@@ -92,19 +92,6 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
if (dispatch) document.dispatchEvent(new Event("visibilitychange"))
},
})
- const originalDateNow = Date.now.bind(Date)
- Object.defineProperty(window, "__alookQaAdvanceWallClock", {
- configurable: true,
- value: (offsetMs: number) => {
- Date.now = () => originalDateNow() + offsetMs
- },
- })
- Object.defineProperty(window, "__alookQaRestoreWallClock", {
- configurable: true,
- value: () => {
- Date.now = originalDateNow
- },
- })
})
const setVisibility = async (state: "hidden" | "visible", dispatch = true) => {
await alice.page.evaluate(({ next, shouldDispatch }) => {
@@ -128,13 +115,23 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
window.dispatchEvent(new Event("online"))
}, persisted)
}
- const runSentinelIntervals = async () => alice.page.evaluate((delay) => {
+ const runSentinelIntervals = async (wallClockOffsetMs = 0) => alice.page.evaluate(({ delay, offsetMs }) => {
const run = (window as Window & {
__alookQaRunIntervals?: (intervalDelay: number) => number
}).__alookQaRunIntervals
if (!run) throw new Error("QA interval runner missing")
- return run(delay)
- }, WS_FOREGROUND_SENTINEL_INTERVAL_MS)
+ const originalDateNow = Date.now
+ const before = originalDateNow()
+ try {
+ Date.now = () => originalDateNow() + offsetMs
+ return {
+ count: run(delay),
+ observedClockShift: Date.now() - before,
+ }
+ } finally {
+ Date.now = originalDateNow
+ }
+ }, { delay: WS_FOREGROUND_SENTINEL_INTERVAL_MS, offsetMs: wallClockOffsetMs })
const wsOverlay = alice.page.getByTestId(tid.wsReconnectOverlay)
const initialPageShowFrameCount = proxy.connectionFrames.length
@@ -233,12 +230,8 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await alice.page.waitForTimeout(WS_CONNECTION_VALIDATION_TIMEOUT_MS - 1_000)
await expect(wsOverlay).toHaveCount(0)
- await expect(wsOverlay).toHaveAttribute(
- "data-ws-status",
- "reconnecting",
- { timeout: 5_000 },
- )
await expect.poll(() => proxy.connectionCount()).toBe(failedConnectionBaseline + 1)
+ await expect(wsOverlay).toHaveCount(0)
await expect.poll(() => tokenRequests).toBe(failedTokenBaseline + 1)
await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
await dispatchDuplicateResumeSignals()
@@ -265,7 +258,7 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
const sentinelOrdinaryStart = proxy.connectionFrames.length
const sentinelConnectionBaseline = proxy.connectionCount()
const sentinelTokenBaseline = tokenRequests
- expect(await runSentinelIntervals()).toBeGreaterThanOrEqual(1)
+ expect((await runSentinelIntervals()).count).toBeGreaterThanOrEqual(1)
await alice.page.waitForTimeout(250)
expect(proxy.connectionCount()).toBe(sentinelConnectionBaseline)
expect(tokenRequests).toBe(sentinelTokenBaseline)
@@ -276,36 +269,21 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
dropValidationPong = true
holdReplacementAuth = true
const sentinelRecoveryStart = proxy.connectionFrames.length
- const observedClockShift = await alice.page.evaluate((offsetMs) => {
- const before = Date.now()
- const advance = (window as Window & {
- __alookQaAdvanceWallClock?: (offset: number) => void
- }).__alookQaAdvanceWallClock
- if (!advance) throw new Error("QA wall-clock advancer missing")
- advance(offsetMs)
- return Date.now() - before
- }, WS_FOREGROUND_SUSPENSION_GAP_MS + 5_000)
+ const sentinelTick = await runSentinelIntervals(WS_FOREGROUND_SUSPENSION_GAP_MS + 5_000)
+ const observedClockShift = sentinelTick.observedClockShift
expect(observedClockShift).toBeGreaterThanOrEqual(WS_FOREGROUND_SUSPENSION_GAP_MS)
- expect(await runSentinelIntervals()).toBeGreaterThanOrEqual(1)
+ expect(sentinelTick.count).toBeGreaterThanOrEqual(1)
await expect.poll(() => proxy.connectionFrames.slice(sentinelRecoveryStart).filter((frame) =>
frame.direction === "client-to-server" && frame.type === "connection.ping",
).length).toBe(1)
- await alice.page.evaluate(() => {
- const restore = (window as Window & {
- __alookQaRestoreWallClock?: () => void
- }).__alookQaRestoreWallClock
- if (!restore) throw new Error("QA wall-clock restorer missing")
- restore()
- })
await dispatchDuplicateResumeSignals()
proxy.sendConnectionFrame({ type: "connection.pong", nonce: "sentinel_stale_nonce" })
- await expect(wsOverlay).toHaveAttribute(
- "data-ws-status",
- "reconnecting",
+ await expect.poll(
+ () => proxy.connectionCount(),
{ timeout: WS_CONNECTION_VALIDATION_TIMEOUT_MS + 5_000 },
- )
- await expect.poll(() => proxy.connectionCount()).toBe(sentinelConnectionBaseline + 1)
+ ).toBe(sentinelConnectionBaseline + 1)
+ await expect(wsOverlay).toHaveCount(0)
await expect.poll(() => tokenRequests).toBe(sentinelTokenBaseline + 1)
await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
expect(proxy.connectionFrames.slice(sentinelRecoveryStart).filter((frame) =>
@@ -323,11 +301,11 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
try {
await alice.context.setOffline(true)
await proxy.disconnect()
- await expect(wsOverlay).toHaveAttribute(
- "data-ws-status",
- "reconnecting",
- { timeout: 10_000 },
- )
+ await alice.page.waitForTimeout(1_600)
+ await expect(wsOverlay).toHaveCount(0)
+ await expect.poll(() => composerEditable(alice.page).evaluate((element) => (
+ element.closest("[inert]") !== null
+ ))).toBe(false)
await expect(wsOverlay).toHaveAttribute(
"data-ws-status",
"failed",
@@ -337,21 +315,34 @@ test("mobile foreground proof is exact, bounded, and recovers through one curren
await alice.context.setOffline(false)
}
- await alice.page.getByTestId(tid.wsRetry).click()
+ const retryConnectionBaseline = proxy.connectionCount()
+ const retrySuccessfulTokenBaseline = successfulTokenResponses
+ const retry = alice.page.getByTestId(tid.wsRetry)
+ await retry.focus()
+ await alice.page.keyboard.press("Enter")
await expect(wsOverlay).toHaveCount(0, { timeout: 20_000 })
+ // The failed-only overlay disappears as soon as Retry starts connecting.
+ // Wait for that generation to authenticate before measuring a hard reload,
+ // otherwise the retry socket can race the discarded document's replacement
+ // and make the reload look like it opened two connections.
+ await expect.poll(() => proxy.connectionCount()).toBe(retryConnectionBaseline + 1)
+ await expect.poll(() => successfulTokenResponses).toBe(retrySuccessfulTokenBaseline + 1)
const reloadFrameStart = proxy.connectionFrames.length
const reloadConnectionBaseline = proxy.connectionCount()
const reloadSuccessfulTokenBaseline = successfulTokenResponses
+ await alice.page.evaluate(() => {
+ document.documentElement.removeAttribute("data-e2e-user-ws-authenticated")
+ })
await alice.page.reload({ waitUntil: "commit" })
+ await expect(alice.page.locator("html")).toHaveAttribute(
+ "data-e2e-user-ws-authenticated",
+ "true",
+ { timeout: 20_000 },
+ )
await expect(composerEditable(alice.page)).toBeVisible({ timeout: 20_000 })
await expect.poll(() => proxy.connectionCount()).toBe(reloadConnectionBaseline + 1)
await expect.poll(() => successfulTokenResponses).toBe(reloadSuccessfulTokenBaseline + 1)
- await expect.poll(() => proxy.connectionFrames.slice(reloadFrameStart).filter((frame) =>
- frame.direction === "server-to-client"
- && frame.type === "auth.ok"
- && frame.connectionId === reloadConnectionBaseline + 1,
- ).length).toBe(1)
await alice.page.waitForTimeout(500)
expect(proxy.connectionCount()).toBe(reloadConnectionBaseline + 1)
expect(successfulTokenResponses).toBe(reloadSuccessfulTokenBaseline + 1)
diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
index 4003cbf67..57afaf507 100644
--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
@@ -156,12 +156,12 @@ test.describe.serial("Inbox/read refresh ownership", () => {
expect.stringContaining(`/c/channels/${serverId}/${channelA}`),
])
- const reconciledInbox = page.waitForResponse((response) => (
+ const reconciledAttention = page.waitForResponse((response) => (
response.request().method() === "GET"
- && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
+ && new URL(response.url()).pathname === "/api/community/users/me/attention"
))
readGate.resolve()
- expect((await reconciledInbox).status()).toBe(200)
+ expect((await reconciledAttention).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()
})
@@ -178,15 +178,15 @@ test.describe.serial("Inbox/read refresh ownership", () => {
const readObserverGate = await installReadObserverGate(page)
const proxy = await proxyCommunityWebSockets(context)
await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelA}`)
- const initialInbox = page.waitForResponse((response) => (
+ const initialAttention = page.waitForResponse((response) => (
response.request().method() === "GET"
- && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
+ && new URL(response.url()).pathname === "/api/community/users/me/attention"
))
await expect(page.getByRole("heading", { name: channelAName, exact: true })).toBeVisible({
timeout: 20_000,
})
await page.getByRole("button", { name: "Inbox", exact: true }).click()
- expect((await initialInbox).status()).toBe(200)
+ expect((await initialAttention).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
const stopWatchingA = await watchInboxRow(page, tid.inboxUnreadChannel(channelA))
@@ -199,22 +199,16 @@ test.describe.serial("Inbox/read refresh ownership", () => {
const requestStart = requests.length
const frameStart = proxy.frames.length
await readObserverGate.block()
- const staleInboxResponse = page.waitForResponse(async (response) => {
+ const staleAttentionResponse = page.waitForResponse(async (response) => {
if (
response.request().method() !== "GET"
- || new URL(response.url()).pathname !== "/api/community/users/me/inbox/unreads"
+ || new URL(response.url()).pathname !== "/api/community/users/me/attention"
|| response.status() !== 200
) return false
const payload = await response.json() as {
- servers: Array<{ channels: Array<{
- channelId: string
- children: Array<{ channelId: string }>
- }> }>
+ scopes: Array<{ scopeId: string }>
}
- return payload.servers.some((server) => server.channels.some((channel) => (
- channel.channelId === channelA
- || channel.children.some((child) => child.channelId === channelA)
- )))
+ return payload.scopes.some((scope) => scope.scopeId === channelA)
})
const readResponse = page.waitForResponse((response) => (
response.request().method() === "PUT"
@@ -225,19 +219,12 @@ test.describe.serial("Inbox/read refresh ownership", () => {
const bodyDm = `background dm ${stamp}`
const messageA = await seedMessage("alice", channelA, bodyA)
await expect(page.getByText(bodyA, { exact: true })).toBeVisible({ timeout: 20_000 })
- const staleResponse = await staleInboxResponse
+ const staleResponse = await staleAttentionResponse
expect(staleResponse.status()).toBe(200)
const stalePayload = await staleResponse.json() as {
- servers: Array<{ channels: Array<{
- channelId: string
- children: Array<{ channelId: string }>
- }> }>
- dms: Array<{ channelId: string }>
+ scopes: Array<{ scopeId: string }>
}
- expect(stalePayload.servers.some((server) => server.channels.some((channel) => (
- channel.channelId === channelA
- || channel.children.some((child) => child.channelId === channelA)
- )))).toBe(true)
+ expect(stalePayload.scopes.some((scope) => scope.scopeId === channelA)).toBe(true)
expect(await readObserverGate.pending()).toBeGreaterThan(0)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
const messageB = await seedMessage("alice", channelB, bodyB)
@@ -262,12 +249,13 @@ test.describe.serial("Inbox/read refresh ownership", () => {
request.method === "PUT"
&& request.path === `/api/community/channels/${channelA}/read`
))
- const inboxIndex = journeyRequests.findIndex((request) => (
+ const attentionIndex = journeyRequests.findIndex((request) => (
request.method === "GET"
- && request.path === "/api/community/users/me/inbox/unreads"
+ && request.path === "/api/community/users/me/attention"
))
expect(readIndex).toBeGreaterThanOrEqual(0)
- expect(inboxIndex).toBeLessThan(readIndex)
+ expect(attentionIndex).toBeGreaterThanOrEqual(0)
+ expect(attentionIndex).toBeLessThan(readIndex)
const snapshot = await (await page.request.get(
"/api/community/users/me/read-state",
@@ -288,15 +276,15 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await seedJoinServer("alice", "bob", serverId)
const { page } = await asUser("bob")
await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
- const initialInbox = page.waitForResponse((response) => (
+ const initialAttention = page.waitForResponse((response) => (
response.request().method() === "GET"
- && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
+ && new URL(response.url()).pathname === "/api/community/users/me/attention"
))
await expect(page.getByRole("heading", { name: channelName, exact: true })).toBeVisible({
timeout: 20_000,
})
await page.getByRole("button", { name: "Inbox", exact: true }).click()
- expect((await initialInbox).status()).toBe(200)
+ expect((await initialAttention).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
const retryGate = deferred()
@@ -327,7 +315,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
expect(puts).toBe(2)
})
- test("an Inbox forum child claims only its exact opener and preserves a later opener", async ({ asUser }) => {
+ test("a cold forum opener aggregate uses the canonical parent row", async ({ asUser }) => {
const stamp = Date.now()
const serverId = await seedServer("alice", `Inbox opener handoff ${stamp}`)
const forumId = await seedChannel("alice", serverId, `handoff-forum-${stamp}`, "forum")
@@ -379,29 +367,30 @@ test.describe.serial("Inbox/read refresh ownership", () => {
})
await page.getByRole("button", { name: "Inbox", exact: true }).click()
- await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadChannel(forumId))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toHaveCount(0)
+ await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toHaveCount(0)
const parentRead = page.waitForResponse((response) => (
response.request().method() === "PUT"
&& new URL(response.url()).pathname === `/api/community/channels/${forumId}/read`
))
- await page.getByTestId(tid.inboxUnreadChild(firstChildId)).click()
+ await page.getByTestId(tid.inboxUnreadChannel(forumId)).click()
expect((await parentRead).status()).toBe(200)
await expect.poll(() => new URL(page.url()).searchParams.has("inboxThreadOpener")).toBe(false)
- expect(parentTargets).toEqual([first!.openerMessageId])
+ expect(parentTargets).toEqual([later!.openerMessageId])
expect(childTargets).toEqual([])
await page.getByRole("button", { name: "Inbox", exact: true }).click()
- await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toHaveCount(0)
- await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadChannel(forumId))).toHaveCount(0)
const snapshot = await (await page.request.get(
"/api/community/users/me/read-state",
)).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
expect(snapshot.readStates.find((row) => row.channelId === forumId)?.lastReadSeq)
- .toBe(first!.openerSeq)
+ .toBe(later!.openerSeq)
expect(snapshot.readStates.some((row) => row.channelId === firstChildId)).toBe(false)
})
- test("eligible text children enrich opener state without widening participation", async ({ asUser }) => {
+ test("cold text-child evidence projects through the canonical parent row", async ({ asUser }) => {
const stamp = Date.now()
const serverId = await seedServer("alice", `Inbox text opener ${stamp}`)
const parentId = await seedChannel("alice", serverId, `text-parent-${stamp}`)
@@ -430,14 +419,14 @@ test.describe.serial("Inbox/read refresh ownership", () => {
`Nonparticipant thread ${stamp}`,
)
await seedMessage("alice", nonParticipantChildId, `Invisible child reply ${stamp}`)
- await seedMessage("alice", parentId, `Later parent message ${stamp}`)
+ const laterParentMessageId = await seedMessage("alice", parentId, `Later parent message ${stamp}`)
await page.setViewportSize({ width: 768, height: 844 })
await gotoAfterUserWsAuth(page, "/c/me")
const unreadResponse = await page.request.get("/api/community/users/me/inbox/unreads")
expect(unreadResponse.status()).toBe(200)
const unread = await unreadResponse.json() as {
- servers: Array<{ channels: Array<{ channelId: string; children: Array<{
+ servers: Array<{ channels: Array<{ channelId: string; lastUnreadSeq?: number; children: Array<{
channelId: string
openerMessageId?: string
openerSeq?: number
@@ -458,6 +447,11 @@ test.describe.serial("Inbox/read refresh ownership", () => {
openerUnread: true,
})
expect(parent?.children.some((child) => child.channelId === nonParticipantChildId)).toBe(false)
+ const beforeSnapshot = await (await page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const beforeCursor = (channelId: string) => beforeSnapshot.readStates
+ .find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
const puts: Array<{ channelId: string; target: string }> = []
page.on("request", (request) => {
@@ -469,44 +463,30 @@ test.describe.serial("Inbox/read refresh ownership", () => {
})
await page.getByRole("button", { name: "Inbox", exact: true }).click()
- await expect(page.getByTestId(tid.inboxUnreadChild(readChildId))).toBeVisible()
- const readChildPut = page.waitForResponse((response) => (
- response.request().method() === "PUT"
- && new URL(response.url()).pathname === `/api/community/channels/${readChildId}/read`
- ))
- await page.getByTestId(tid.inboxUnreadChild(readChildId)).click()
- expect((await readChildPut).status()).toBe(200)
- await page.waitForTimeout(700)
- expect(puts.filter((put) => put.channelId === parentId)).toEqual([])
-
- await page.getByRole("button", { name: "Inbox", exact: true }).click()
- await expect(page.getByTestId(tid.inboxUnreadChild(unreadChildId))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadChannel(parentId))).toBeVisible()
+ await expect(page.getByTestId(tid.inboxUnreadChild(readChildId))).toHaveCount(0)
+ await expect(page.getByTestId(tid.inboxUnreadChild(unreadChildId))).toHaveCount(0)
const parentPut = page.waitForResponse((response) => (
response.request().method() === "PUT"
&& new URL(response.url()).pathname === `/api/community/channels/${parentId}/read`
))
- const unreadChildPut = page.waitForResponse((response) => (
- response.request().method() === "PUT"
- && new URL(response.url()).pathname === `/api/community/channels/${unreadChildId}/read`
- ))
- await page.getByTestId(tid.inboxUnreadChild(unreadChildId)).click()
+ await page.getByTestId(tid.inboxUnreadChannel(parentId)).click()
expect((await parentPut).status()).toBe(200)
- expect((await unreadChildPut).status()).toBe(200)
+ await page.waitForTimeout(700)
expect(puts.filter((put) => put.channelId === parentId)).toEqual([
- { channelId: parentId, target: unreadOpenerId },
+ { channelId: parentId, target: laterParentMessageId },
])
+ expect(puts.some((put) => put.channelId === readChildId)).toBe(false)
+ expect(puts.some((put) => put.channelId === unreadChildId)).toBe(false)
const snapshot = await (await page.request.get(
"/api/community/users/me/read-state",
)).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
const cursor = (channelId: string) => snapshot.readStates
.find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
- expect(cursor(parentId)).toBe(unreadChild!.openerSeq)
- expect(cursor(readChildId)).toBeGreaterThan(0)
- expect(cursor(unreadChildId)).toBeGreaterThan(0)
- await page.getByRole("button", { name: "Inbox", exact: true }).click()
- await expect(page.getByTestId(tid.inboxUnreadChannel(parentId))).toBeVisible()
- await expect(page.getByTestId(tid.inboxUnreadChild(nonParticipantChildId))).toHaveCount(0)
+ expect(cursor(parentId)).toBe(parent?.lastUnreadSeq)
+ expect(cursor(readChildId)).toBe(beforeCursor(readChildId))
+ expect(cursor(unreadChildId)).toBe(beforeCursor(unreadChildId))
})
test("a later focused intent keeps its own 500ms generation", async ({ asUser }) => {
@@ -517,15 +497,15 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await seedJoinServer("alice", "bob", serverId)
const { page } = await asUser("bob")
await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
- const initialInbox = page.waitForResponse((response) => (
+ const initialAttention = page.waitForResponse((response) => (
response.request().method() === "GET"
- && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
+ && new URL(response.url()).pathname === "/api/community/users/me/attention"
))
await expect(page.getByRole("heading", { name: channelName, exact: true })).toBeVisible({
timeout: 20_000,
})
await page.getByRole("button", { name: "Inbox", exact: true }).click()
- expect((await initialInbox).status()).toBe(200)
+ expect((await initialAttention).status()).toBe(200)
await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
const stopWatching = await watchInboxRow(page, tid.inboxUnreadChannel(channelId))
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 037129a58..caa6754e0 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
@@ -1,4 +1,4 @@
-import type { Page, Route } from "@playwright/test"
+import type { Page, Request, Response, Route } from "@playwright/test"
import { test, expect } from "./_fixtures/community-fixture"
import { seedChannel, seedServer } from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
@@ -19,11 +19,38 @@ type SidebarFrame = {
opacity: string | null
}
+type HistoryEvent = {
+ kind: "pushState" | "replaceState" | "popstate"
+ pathname: string
+}
+
async function installSidebarFrameProbe(page: Page) {
const channelRowPrefix = tid.channelRow("")
await page.addInitScript(({ channelRowPrefix }) => {
- const state = window as typeof window & { __communitySidebarFrames?: SidebarFrame[] }
+ const state = window as typeof window & {
+ __communityHistoryEvents?: HistoryEvent[]
+ __communitySidebarFrames?: SidebarFrame[]
+ }
state.__communitySidebarFrames = []
+ state.__communityHistoryEvents = []
+ const recordHistory = (
+ kind: HistoryEvent["kind"],
+ href: string | URL | null | undefined,
+ ) => {
+ const url = href == null ? new URL(location.href) : new URL(String(href), location.href)
+ state.__communityHistoryEvents!.push({ kind, pathname: url.pathname })
+ }
+ const pushState = history.pushState.bind(history)
+ history.pushState = (...args) => {
+ recordHistory("pushState", args[2])
+ return pushState(...args)
+ }
+ const replaceState = history.replaceState.bind(history)
+ history.replaceState = (...args) => {
+ recordHistory("replaceState", args[2])
+ return replaceState(...args)
+ }
+ addEventListener("popstate", () => recordHistory("popstate", location.href))
const ownerIds = new WeakMap<Element, number>()
let nextOwnerId = 0
const sample = () => {
@@ -66,6 +93,19 @@ async function clearSidebarFrames(page: Page) {
})
}
+async function clearHistoryEvents(page: Page) {
+ await page.evaluate(() => {
+ ;(window as typeof window & { __communityHistoryEvents?: HistoryEvent[] })
+ .__communityHistoryEvents = []
+ })
+}
+
+async function historyEvents(page: Page): Promise<HistoryEvent[]> {
+ return page.evaluate(() => (
+ window as typeof window & { __communityHistoryEvents?: HistoryEvent[] }
+ ).__communityHistoryEvents ?? [])
+}
+
async function sidebarFrames(page: Page): Promise<SidebarFrame[]> {
return page.evaluate(() => (
window as typeof window & { __communitySidebarFrames?: SidebarFrame[] }
@@ -127,6 +167,79 @@ async function holdServerTransition(
}
}
+function isTargetRsc(request: Request, serverId: string): boolean {
+ return request.resourceType() === "fetch"
+ && request.headers().rsc === "1"
+ && new URL(request.url()).pathname.startsWith(`/c/channels/${serverId}/`)
+}
+
+function observeTargetRsc(
+ page: Page,
+ serverId: string,
+ timeoutMs: number,
+): {
+ finished: Promise<void>
+ requests: () => string[]
+ stop: () => void
+} {
+ const requests: string[] = []
+ let settled = false
+ let resolveFinished!: () => void
+ let rejectFinished!: (error: Error) => void
+ const finished = new Promise<void>((resolve, reject) => {
+ resolveFinished = resolve
+ rejectFinished = reject
+ })
+ const settle = (error?: Error) => {
+ if (settled) return
+ settled = true
+ clearTimeout(timeout)
+ if (error) rejectFinished(error)
+ else resolveFinished()
+ }
+ const onRequest = (request: Request) => {
+ if (isTargetRsc(request, serverId)) requests.push(request.url())
+ }
+ const onRequestFailed = (request: Request) => {
+ if (!isTargetRsc(request, serverId)) return
+ settle(new Error(
+ `Target RSC request failed: ${request.failure()?.errorText ?? "unknown failure"}`,
+ ))
+ }
+ const onResponse = (response: Response) => {
+ if (!isTargetRsc(response.request(), serverId)) return
+ if (response.status() !== 200) {
+ settle(new Error(`Target RSC responded ${response.status()}: ${response.url()}`))
+ return
+ }
+ void response.finished().then((failure) => {
+ if (failure) {
+ settle(new Error(`Target RSC did not finish: ${failure.message}`))
+ return
+ }
+ settle()
+ }, (error: unknown) => {
+ settle(new Error(`Target RSC completion rejected: ${String(error)}`))
+ })
+ }
+ const timeout = setTimeout(() => {
+ settle(new Error(`Target RSC did not finish within ${timeoutMs}ms for server ${serverId}`))
+ }, timeoutMs)
+ page.on("request", onRequest)
+ page.on("requestfailed", onRequestFailed)
+ page.on("response", onResponse)
+ return {
+ finished,
+ requests: () => [...requests],
+ stop: () => {
+ clearTimeout(timeout)
+ page.off("request", onRequest)
+ page.off("requestfailed", onRequestFailed)
+ page.off("response", onResponse)
+ },
+ }
+}
+
async function activateServerIcon(page: Page, serverId: string) {
const icon = page.getByTestId(tid.serverIcon(serverId))
// Focus activates the accessible menu path and starts Server-root prefetch.
@@ -269,18 +382,34 @@ test("server switching exposes one target-scoped cold checkpoint and skips it wh
await page.reload()
await expect(page.getByRole("heading", { name: channelAName })).toBeVisible({ timeout: 30_000 })
const structuralC = await holdServerTransition(page, serverC)
+ const targetRsc = observeTargetRsc(page, serverC, 30_000)
await clearSidebarFrames(page)
- await clickServer(page, serverC)
- await expect.poll(structuralC.heldNavigation).toBeGreaterThan(0)
- await structuralC.release()
- await expectDesktopServerDetail(page, serverC)
- await expect(page.getByTestId(tid.channelRow(channelC))).toBeVisible({ timeout: 30_000 })
- expectAtomicTargetFrames(
- await sidebarFrames(page),
- `server:${serverC}`,
- channelC,
- [channelA, channelB],
- )
+ await clearHistoryEvents(page)
+ try {
+ await clickServer(page, serverC)
+ await expect.poll(structuralC.heldNavigation).toBeGreaterThan(0)
+ await structuralC.release()
+ await targetRsc.finished
+ expect(targetRsc.requests()).toHaveLength(1)
+ await expectDesktopServerDetail(page, serverC)
+ await expect(page.getByTestId(tid.channelRow(channelC))).toBeVisible({ timeout: 30_000 })
+ expectAtomicTargetFrames(
+ await sidebarFrames(page),
+ `server:${serverC}`,
+ channelC,
+ [channelA, channelB],
+ )
+ const navigationEvents = await historyEvents(page)
+ expect(navigationEvents).toHaveLength(2)
+ expect(navigationEvents[0]).toEqual({
+ kind: "pushState",
+ pathname: `/c/channels/${serverC}`,
+ })
+ expect(navigationEvents[1]).toMatchObject({ kind: "replaceState" })
+ expect(navigationEvents[1]?.pathname.startsWith(`/c/channels/${serverC}/`)).toBe(true)
+ } finally {
+ targetRsc.stop()
+ }
await clickServer(page, serverA)
await expectDesktopServerDetail(page, serverA)
diff --git a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
index 0b382bc14..a134edc1e 100644
--- a/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
+++ b/src/web/src/test/e2e-ui/37-server-rail-pdd.spec.ts
@@ -405,7 +405,10 @@ test("first native Server tap is one root push with a stable handle and zero rai
await warm.page.goto(`/c/channels/${serverId}`)
await expect(warm.page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 30_000 })
await warm.page.getByTestId(tid.homeButton).click()
- await expect.poll(() => new URL(warm.page.url()).pathname).toBe("/c/me")
+ await expect.poll(
+ () => new URL(warm.page.url()).pathname,
+ { timeout: 30_000 },
+ ).toBe("/c/me")
await warm.page.getByTestId(tid.dmRow(dmId)).click()
await expect.poll(() => new URL(warm.page.url()).pathname).toBe(`/c/me/${dmId}`)
await warm.page.reload()
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 65235f179..8f58a2c96 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -761,7 +761,13 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
const dmReplyTarget = alice.page.getByTestId(tid.message(dmWsReadyId))
const dmScrollToPresent = alice.page.getByTestId(tid.scrollToPresent)
await expect(dmReplyTarget.or(dmScrollToPresent).first()).toBeVisible()
- if (await dmScrollToPresent.isVisible()) await dmScrollToPresent.click()
+ if (!(await dmReplyTarget.isVisible())) {
+ try {
+ await dmScrollToPresent.click({ timeout: 3_000 })
+ } catch (error) {
+ if (!(await dmReplyTarget.isVisible())) throw error
+ }
+ }
await expect(dmReplyTarget).toBeVisible()
await dispatchSwipe(alice.page, dmWsReadyId, { x: 72, y: 1 })
await expect(replyPreview).toHaveText(`Replying to ${bobInfo.name} · dm reply target ${stamp}`)
diff --git a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
index b7b5db60e..e3ae32771 100644
--- a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
+++ b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
@@ -1,4 +1,4 @@
-import type { Page, Request } from "@playwright/test"
+import type { Page, Response } from "@playwright/test"
import { test, expect } from "./_fixtures/community-fixture"
import {
seedChannel,
@@ -19,42 +19,6 @@ async function expectMobileBack(page: Page) {
return control
}
-function observeColdBootServerReconciliation(page: Page, serverId: string) {
- const readStatePath = "/api/community/users/me/read-state"
- const expectedPaths = new Set([
- `/api/community/servers/${serverId}/categories`,
- `/api/community/servers/${serverId}/channels`,
- `/api/community/servers/${serverId}/unreads`,
- ])
- const reconciliationPaths = new Set(["/api/community/servers", ...expectedPaths])
- const observedPaths = new Set<string>()
- const pending = new Set<Request>()
- let readStateSettled = false
-
- const onRequest = (request: Request) => {
- const pathname = new URL(request.url()).pathname
- if (!readStateSettled || !reconciliationPaths.has(pathname)) return
- if (expectedPaths.has(pathname)) observedPaths.add(pathname)
- pending.add(request)
- }
- const onSettled = (request: Request) => {
- if (new URL(request.url()).pathname === readStatePath) readStateSettled = true
- pending.delete(request)
- }
- page.on("request", onRequest)
- page.on("requestfinished", onSettled)
- page.on("requestfailed", onSettled)
-
- return {
- done: () => observedPaths.size === expectedPaths.size && pending.size === 0,
- dispose: () => {
- page.off("request", onRequest)
- page.off("requestfinished", onSettled)
- page.off("requestfailed", onSettled)
- },
- }
-}
-
test.describe.serial("mobile server header direct hierarchy", () => {
let serverId: string
let textId: string
@@ -112,16 +76,30 @@ test.describe.serial("mobile server header direct hierarchy", () => {
test("639↔640 preserves the header and composer owners without resize requests", async ({ asUser }) => {
const { page } = await asUser("alice")
- const coldBootReconciliation = observeColdBootServerReconciliation(page, serverId)
+ const startupAttentionPaths = [
+ "/api/community/users/me/attention",
+ ] as const
+ const startupAttentionGenerations = new Map<string, number>(
+ startupAttentionPaths.map((pathname) => [pathname, 0]),
+ )
+ const observeStartupAttention = (response: Response) => {
+ const pathname = new URL(response.url()).pathname
+ if (response.request().method() !== "GET" || !response.ok()) return
+ if (!startupAttentionGenerations.has(pathname)) return
+ startupAttentionGenerations.set(pathname, (startupAttentionGenerations.get(pathname) ?? 0) + 1)
+ }
+ page.on("response", observeStartupAttention)
await page.setViewportSize({ width: 639, height: 844 })
await page.goto(`/c/channels/${serverId}/${threadId}`, { waitUntil: "commit" })
await expect(page.getByTestId(tid.composerInput)).toBeVisible({ timeout: 20_000 })
await expectMobileBack(page)
- await expect.poll(coldBootReconciliation.done, {
- message: "cold-boot read-state server reconciliation to settle",
- timeout: 10_000,
- }).toBe(true)
- coldBootReconciliation.dispose()
+ // The shell-owned attention query settles once on cold mount. Keep that
+ // generation outside the resize measurement window.
+ await expect.poll(() => startupAttentionPaths.every(
+ (pathname) => (startupAttentionGenerations.get(pathname) ?? 0) >= 1,
+ )).toBe(true)
+ page.off("response", observeStartupAttention)
+ await page.waitForLoadState("networkidle")
await page.evaluate(({ composerTestId }) => {
const backControl = document.querySelector('button[aria-label="Back"]')
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
index 8cef65867..11a9dfaa3 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -396,7 +396,7 @@ test.describe.serial("account unread projection", () => {
await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
- await expect(page.getByTestId(tid.inboxTrigger).locator('[data-slot="inbox-unread-indicator"]')).not.toHaveAttribute("data-count", "0")
+ await expect(page.getByTestId(tid.inboxTrigger).locator('[data-slot="inbox-unread-indicator"]')).toHaveAttribute("data-count", "0")
await page.getByTestId(tid.inboxTrigger).click()
expect(targetPuts).toEqual([])
diff --git a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts
index 1ce53e84c..96cb8b9bc 100644
--- a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts
+++ b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts
@@ -18,16 +18,6 @@ type ColdRootProbe = {
machinesSeen: boolean
}
-type SkeletonGeometry = {
- wrapper: { left: number; right: number; paddingLeft: number; paddingRight: number }
- base: { left: number; right: number; width: number; height: number }
- expectedColor: string
- borders: Record<"top" | "right" | "bottom" | "left", {
- width: string
- color: string
- }>
-}
-
const coldRootStorageKey = `community:lastRoute:${encodeURIComponent(userId("alice"))}`
async function installColdRootProbe(page: Page, destination: string | null) {
@@ -70,84 +60,29 @@ async function expectNoMachinesDuringColdRootRestore(page: Page) {
).__communityColdRootProbe)).toEqual({ machinesSeen: false })
}
-async function userBarSkeletonGeometry(page: Page): Promise<SkeletonGeometry> {
- return page.getByTestId(tid.initialUserBarPending).evaluate((wrapper) => {
- const base = wrapper.firstElementChild
- if (!(base instanceof HTMLElement)) throw new Error("missing User Bar Skeleton base")
- const wrapperRect = wrapper.getBoundingClientRect()
- const wrapperStyle = getComputedStyle(wrapper)
- const baseRect = base.getBoundingClientRect()
- const baseStyle = getComputedStyle(base)
- const reference = document.createElement("div")
- reference.className = "border border-border/40"
- reference.style.position = "fixed"
- reference.style.visibility = "hidden"
- document.body.appendChild(reference)
- const expectedColor = getComputedStyle(reference).borderTopColor
- reference.remove()
- return {
- wrapper: {
- left: wrapperRect.left,
- right: wrapperRect.right,
- paddingLeft: Number.parseFloat(wrapperStyle.paddingLeft),
- paddingRight: Number.parseFloat(wrapperStyle.paddingRight),
- },
- base: {
- left: baseRect.left,
- right: baseRect.right,
- width: baseRect.width,
- height: baseRect.height,
- },
- expectedColor,
- borders: {
- top: { width: baseStyle.borderTopWidth, color: baseStyle.borderTopColor },
- right: { width: baseStyle.borderRightWidth, color: baseStyle.borderRightColor },
- bottom: { width: baseStyle.borderBottomWidth, color: baseStyle.borderBottomColor },
- left: { width: baseStyle.borderLeftWidth, color: baseStyle.borderLeftColor },
- },
- }
- })
-}
-
-function expectUserBarSkeletonBorderContract(geometry: SkeletonGeometry) {
- expect(geometry.base.height).toBe(48)
- expect(Math.abs(
- geometry.base.left - geometry.wrapper.left - geometry.wrapper.paddingLeft,
- )).toBeLessThanOrEqual(1)
- expect(Math.abs(
- geometry.wrapper.right - geometry.wrapper.paddingRight - geometry.base.right,
- )).toBeLessThanOrEqual(1)
- expect(geometry.base.width).toBeCloseTo(
- geometry.wrapper.right
- - geometry.wrapper.left
- - geometry.wrapper.paddingLeft
- - geometry.wrapper.paddingRight,
- 0,
- )
- expect(geometry.expectedColor).not.toBe("rgba(0, 0, 0, 0)")
- for (const side of ["top", "right", "bottom", "left"] as const) {
- expect(geometry.borders[side]).toEqual({
- width: "1px",
- color: geometry.expectedColor,
- })
- }
-}
-
-async function holdSession(page: Page) {
+async function holdApplicationScripts(page: Page) {
let releaseGate!: () => void
let disposition: "continue" | "abort" = "continue"
const gate = new Promise<void>((resolve) => { releaseGate = resolve })
let hits = 0
- const pattern = "**/api/auth/get-session**"
+ let sessionRequests = 0
+ page.on("request", (request) => {
+ if (new URL(request.url()).pathname === "/api/auth/get-session") sessionRequests += 1
+ })
const handler = async (route: Route) => {
+ if (!/\/_next\/.*\.js(?:\?|$)/.test(route.request().url())) {
+ await route.continue()
+ return
+ }
hits += 1
await gate
if (disposition === "abort") await route.abort("aborted")
else await route.continue()
}
- await page.route(pattern, handler)
+ await page.route("**/_next/**", handler)
return {
hits: () => hits,
+ sessionRequests: () => sessionRequests,
release: () => { releaseGate() },
abort: () => {
disposition = "abort"
@@ -200,7 +135,7 @@ async function expectVisibility(locator: ReturnType<Page["getByTestId"]>, visibl
else await expect(locator).toBeHidden()
}
-async function expectOwnedFrame(
+async function expectServerSeededRouteSkeleton(
page: Page,
expected: ExpectedFrame,
distinctiveStrings: string[],
@@ -208,6 +143,7 @@ async function expectOwnedFrame(
const frame = page.getByTestId(tid.initialFrame)
await expect(frame).toBeVisible()
await expect(frame).toHaveAttribute("data-community-route-kind", expected.route)
+ await expect(page.locator('[data-slot="community-restore-bootstrap"]')).toHaveCount(0)
const mobile = (page.viewportSize()?.width ?? 640) < 640
const shellVisible = expected.sidebar !== "none"
const detailMobile = mobile && expected.surface === "detail"
@@ -237,6 +173,10 @@ async function expectOwnedFrame(
const main = page.getByTestId(tid.pendingMain(expected.main))
await expect(main).toHaveCount(1)
await expectVisibility(main, !listMobile)
+ const existingPlaceholder = expected.main === "route-resolution"
+ ? frame.locator("[data-community-unresolved-main]")
+ : frame.locator('[data-slot="skeleton"]')
+ await expect(existingPlaceholder).not.toHaveCount(0)
await expect(frame.getByRole("button")).toHaveCount(0)
await expect(frame.locator("a")).toHaveCount(0)
for (const value of distinctiveStrings) await expect(frame).not.toContainText(value)
@@ -244,7 +184,7 @@ async function expectOwnedFrame(
async function closeHeldContext(
context: BrowserContext,
- gate: Awaited<ReturnType<typeof holdSession>>,
+ gate: Awaited<ReturnType<typeof holdApplicationScripts>>,
) {
gate.abort()
await context.close()
@@ -271,7 +211,7 @@ test.describe.serial("community initial-load module skeletons", () => {
await seedDmMessage("alice", dmId, privateMessage)
})
- test("cold mobile paths expose only their URL-owned inert modules", async ({ asUser }, testInfo) => {
+ test("cold mobile paths reuse only their URL-owned skeleton modules", async ({ asUser }, testInfo) => {
test.setTimeout(240_000)
const cases: Array<[string, ExpectedFrame]> = [
["/c", { route: "community-root-redirect", surface: "neutral", sidebar: "none", main: "route-resolution" }],
@@ -289,28 +229,12 @@ test.describe.serial("community initial-load module skeletons", () => {
for (const [pathname, expected] of cases) {
const { context, page } = await asUser("alice")
await page.setViewportSize({ width: 390, height: 844 })
- const gate = await holdSession(page)
+ const gate = await holdApplicationScripts(page)
const traffic = captureCommunityTraffic(page)
await page.goto(pathname, { waitUntil: "commit" })
await expect.poll(gate.hits).toBeGreaterThan(0)
- await expectOwnedFrame(page, expected, [serverName, channelName, privateMessage])
- if (pathname === `/c/channels/${serverId}`) {
- await page.evaluate(() => {
- const style = document.documentElement.style
- style.setProperty("--app-safe-area-top", "20px")
- style.setProperty("--app-safe-area-right", "16px")
- style.setProperty("--app-safe-area-bottom", "34px")
- style.setProperty("--app-safe-area-left", "18px")
- })
- const geometry = await userBarSkeletonGeometry(page)
- expectUserBarSkeletonBorderContract(geometry)
- expect(geometry.base.left).toBe(18)
- expect(geometry.base.right).toBe(390 - 16)
- await testInfo.attach("user-bar-skeleton-mobile-390x844", {
- body: await page.screenshot(),
- contentType: "image/png",
- })
- }
+ expect(gate.sessionRequests()).toBe(0)
+ await expectServerSeededRouteSkeleton(page, expected, [serverName, channelName, privateMessage])
if (pathname === "/c") {
await testInfo.attach("community-root-neutral-390x844", {
body: await page.screenshot(),
@@ -319,12 +243,6 @@ test.describe.serial("community initial-load module skeletons", () => {
}
expect(traffic.requests).toEqual([])
expect(traffic.sockets()).toBe(0)
- if (expected.main === "server-conversation") {
- await expect(page.getByLabel("Resolving conversation")).toBeVisible()
- await expect(page.getByTestId(tid.messageHeaderLeadingLoading)).toHaveCount(0)
- await expect(page.getByTestId(tid.channelComposerShell)).toHaveCount(0)
- await expect(page.getByRole("button", { name: "Back" })).toHaveCount(0)
- }
await closeHeldContext(context, gate)
}
})
@@ -339,19 +257,12 @@ test.describe.serial("community initial-load module skeletons", () => {
] satisfies Array<[string, ExpectedFrame]>) {
const { context, page } = await asUser("alice")
await page.setViewportSize({ width: 1280, height: 900 })
- const gate = await holdSession(page)
+ const gate = await holdApplicationScripts(page)
const traffic = captureCommunityTraffic(page)
await page.goto(pathname, { waitUntil: "commit" })
await expect.poll(gate.hits).toBeGreaterThan(0)
- await expectOwnedFrame(page, expected, [serverName, channelName, privateMessage])
- if (pathname === `/c/channels/${serverId}`) {
- const geometry = await userBarSkeletonGeometry(page)
- expectUserBarSkeletonBorderContract(geometry)
- await testInfo.attach("user-bar-skeleton-desktop-1280x900", {
- body: await page.screenshot(),
- contentType: "image/png",
- })
- }
+ expect(gate.sessionRequests()).toBe(0)
+ await expectServerSeededRouteSkeleton(page, expected, [serverName, channelName, privateMessage])
if (pathname === "/c") {
await testInfo.attach("community-root-neutral-1280x900", {
body: await page.screenshot(),
@@ -385,10 +296,11 @@ test.describe.serial("community initial-load module skeletons", () => {
const { context, page } = await asUser("alice")
await page.setViewportSize({ width: 390, height: 844 })
await installColdRootProbe(page, destination)
- const gate = await holdSession(page)
+ const gate = await holdApplicationScripts(page)
await page.goto("/c", { waitUntil: "commit" })
await expect.poll(gate.hits).toBeGreaterThan(0)
- await expectOwnedFrame(page, {
+ expect(gate.sessionRequests()).toBe(0)
+ await expectServerSeededRouteSkeleton(page, {
route: "community-root-redirect",
surface: "neutral",
sidebar: "none",
@@ -409,11 +321,16 @@ test.describe.serial("community initial-load module skeletons", () => {
const { page } = await asUser("alice")
await page.setViewportSize({ width: 390, height: 844 })
await installColdRootProbe(page, null)
- const gate = await holdSession(page)
+ const gate = await holdApplicationScripts(page)
await page.goto("/c", { waitUntil: "commit" })
await expect.poll(gate.hits).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.pendingMain("route-resolution"))).toBeVisible()
- await expect(page.getByTestId(tid.pendingMain("machines"))).toHaveCount(0)
+ expect(gate.sessionRequests()).toBe(0)
+ await expectServerSeededRouteSkeleton(page, {
+ route: "community-root-redirect",
+ surface: "neutral",
+ sidebar: "none",
+ main: "route-resolution",
+ }, [serverName, channelName, privateMessage])
const historyLength = await page.evaluate(() => history.length)
gate.release()
@@ -427,10 +344,16 @@ test.describe.serial("community initial-load module skeletons", () => {
const missingDm = `/c/me/dm_missing_${Date.now()}`
await page.setViewportSize({ width: 390, height: 844 })
await installColdRootProbe(page, missingDm)
- const gate = await holdSession(page)
+ const gate = await holdApplicationScripts(page)
await page.goto("/c", { waitUntil: "commit" })
await expect.poll(gate.hits).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.pendingMain("route-resolution"))).toBeVisible()
+ expect(gate.sessionRequests()).toBe(0)
+ await expectServerSeededRouteSkeleton(page, {
+ route: "community-root-redirect",
+ surface: "neutral",
+ sidebar: "none",
+ main: "route-resolution",
+ }, [serverName, channelName, privateMessage])
const historyLength = await page.evaluate(() => history.length)
gate.release()
@@ -442,7 +365,7 @@ test.describe.serial("community initial-load module skeletons", () => {
.toBe("/c/me/machines")
})
- test("639↔640 preserves one pending main node with zero request or socket delta", async ({ asUser }) => {
+ test("639↔640 preserves one route-owned skeleton main node with zero request or socket delta", async ({ asUser }) => {
test.setTimeout(120_000)
for (const [pathname, mainKind] of [
[`/c/me/${dmId}`, "dm"],
@@ -450,9 +373,10 @@ test.describe.serial("community initial-load module skeletons", () => {
] as const) {
const { context, page } = await asUser("alice")
await page.setViewportSize({ width: 639, height: 844 })
- const gate = await holdSession(page)
+ const gate = await holdApplicationScripts(page)
await page.goto(pathname, { waitUntil: "commit" })
await expect.poll(gate.hits).toBeGreaterThan(0)
+ expect(gate.sessionRequests()).toBe(0)
const main = page.getByTestId(tid.pendingMain(mainKind))
await expect(main).toBeVisible()
await main.evaluate((node) => { Reflect.set(window, "__communityInitialMain", node) })
@@ -474,15 +398,22 @@ test.describe.serial("community initial-load module skeletons", () => {
}
})
- test("releasing identity mounts one user-keyed shell without duplicate route work", async ({ asUser }) => {
+ test("releasing scripts mounts one server-seeded user shell without duplicate route work", async ({ asUser }) => {
test.setTimeout(120_000)
const { page } = await asUser("alice")
await page.setViewportSize({ width: 390, height: 844 })
- const gate = await holdSession(page)
+ const gate = await holdApplicationScripts(page)
const traffic = captureCommunityTraffic(page)
await page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
await expect.poll(gate.hits).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.pendingMain("server-conversation"))).toBeVisible()
+ expect(gate.sessionRequests()).toBe(0)
+ await expectServerSeededRouteSkeleton(page, {
+ route: "server-detail",
+ surface: "detail",
+ sidebar: "server",
+ main: "server-conversation",
+ serverId,
+ }, [serverName, channelName, privateMessage])
expect(traffic.requests).toEqual([])
expect(traffic.sockets()).toBe(0)
diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts
index 97f485c34..a9a19d3b1 100644
--- a/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts
+++ b/src/web/src/test/e2e-ui/46-community-loading-geometry-light.spec.ts
@@ -19,7 +19,7 @@ test.describe.serial("community light loading geometry", () => {
})
test("light: persisted desktop sidebars keep every pending-frame boundary aligned", async ({ asUser }) => {
- test.setTimeout(240_000)
+ test.setTimeout(360_000)
await runDesktopPersistedPendingGeometry("light", asUser)
})
diff --git a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
index 65bc33d8d..73d907228 100644
--- a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
+++ b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
@@ -445,25 +445,19 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {
})
const inboxGets: string[] = []
const completedInboxGets: string[] = []
- const postAuthInboxGets = new WeakSet<Request>()
- const completedPostAuthInboxPaths = new Set<string>()
- let authOkReleased = false
const eagerInboxPaths = [
- "/api/community/users/me/inbox/unreads",
- "/api/community/users/me/inbox/mentions",
+ "/api/community/users/me/attention",
]
bob.page.on("request", (request) => {
const path = new URL(request.url()).pathname
- if (request.method() === "GET" && path.includes("/users/me/inbox/")) {
+ if (request.method() === "GET" && eagerInboxPaths.includes(path)) {
inboxGets.push(path)
- if (authOkReleased) postAuthInboxGets.add(request)
}
})
bob.page.on("requestfinished", (request) => {
const path = new URL(request.url()).pathname
- if (request.method() === "GET" && path.includes("/users/me/inbox/")) {
+ if (request.method() === "GET" && eagerInboxPaths.includes(path)) {
completedInboxGets.push(path)
- if (postAuthInboxGets.has(request)) completedPostAuthInboxPaths.add(path)
}
})
await bob.page.setViewportSize({ width: 639, height: 844 })
@@ -473,10 +467,6 @@ test.describe.serial("mobile Inbox interactive user-bar base", () => {
)), { timeout: 30_000 }).toBe(true)
await expect.poll(ws.heldConnectionCount).toBe(1)
expect(ws.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)
- authOkReleased = true
- await expect.poll(() => eagerInboxPaths.every((path) => (
- completedPostAuthInboxPaths.has(path)
- ))).toBe(true)
const writes = observeWrites(bob.page)
const wsBefore = ws.frames.length
diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
index b64f8d1d4..ac7128b82 100644
--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
@@ -370,6 +370,24 @@ async function waitForCommittedGeometry(scroller: Locator): Promise<MessageViewp
return settled!
}
+async function waitForStableTail(scroller: Locator, label: string): Promise<void> {
+ await expect.poll(async () => {
+ const before = await readMessageViewportGeometry(scroller)
+ await scroller.evaluate(() => new Promise<void>((resolveValue) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolveValue()))
+ }))
+ const after = await readMessageViewportGeometry(scroller)
+ return {
+ atTail: after.distanceToEnd <= 1,
+ stable: Math.abs(after.scrollTop - before.scrollTop) <= 1
+ && Math.abs(after.scrollHeight - before.scrollHeight) <= 1,
+ }
+ }, {
+ timeout: 20_000,
+ message: `${label}: product scroll-to-bottom must finish before exact-pinned setup`,
+ }).toMatchObject({ atTail: true, stable: true })
+}
+
async function advanceScrollTraceFrame(scroller: Locator): Promise<void> {
await scroller.evaluate(() => new Promise<void>((resolveValue) => {
requestAnimationFrame(() => resolveValue())
@@ -623,12 +641,15 @@ test.describe.serial("message scroll characterization", () => {
await installScrollTrace(alice.page)
const proxy = await proxyCommunityWebSockets(alice.context)
await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${upwardChannelId}`)
- await expect(alice.page.getByTestId(tid.newDivider)).toBeVisible({ timeout: 30_000 })
- await alice.page.getByTestId(tid.scrollToPresent).click()
+ const scroller = alice.page.getByTestId(tid.messageScroller)
+ await expect(scroller).toBeVisible({ timeout: 30_000 })
+ const present = alice.page.getByTestId(tid.scrollToPresent)
+ await expect(present).toBeVisible({ timeout: 30_000 })
+ await present.click()
await expect(alice.page.getByTestId(tid.message(upwardProfile.ids.at(-1)!)))
.toBeVisible({ timeout: 30_000 })
- await expect(alice.page.getByTestId(tid.scrollToPresent)).toHaveCount(0)
- const scroller = alice.page.getByTestId(tid.messageScroller)
+ await expect(present).toHaveCount(0)
+ await waitForStableTail(scroller, "remote-fixture-tail")
await startScrollTrace(alice.page, {
scenario: "remote-receive-and-upward-input",
commandDirection: "backward",
@@ -637,7 +658,7 @@ test.describe.serial("message scroll characterization", () => {
})
await markScrollTrace(alice.page, "stimulus:pin-tail")
- const pinnedPrecondition = await establishScrollDistancePrecondition(scroller, "remote-pinned", 0)
+ const pinnedPrecondition = await establishExactPinnedPrecondition(scroller, "remote-pinned", 0)
await markScrollTrace(alice.page, "remote-pinned-precondition", {
detail: pinnedPrecondition,
})
diff --git a/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts b/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts
index 09b7ebd80..749286f4f 100644
--- a/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts
+++ b/src/web/src/test/e2e-ui/57-server-delete-navigation-races.spec.ts
@@ -43,6 +43,31 @@ async function serverIds(key: UserKey): Promise<string[]> {
return body.servers.map((server) => server.id)
}
+async function firstTextChannelId(page: Page, serverId: string): Promise<string> {
+ const response = await page.request.get(
+ `/api/community/servers/${serverId}/channels`,
+ )
+ expect(response.status()).toBe(200)
+ const body = await response.json() as {
+ channels: Array<{ id: string; type: string; parentChannelId?: string | null }>
+ }
+ const channel = body.channels.find((candidate) => (
+ candidate.type === "text" && !candidate.parentChannelId
+ ))
+ expect(channel).toBeTruthy()
+ return channel!.id
+}
+
+async function openChannelRoute(
+ page: Page,
+ serverId: string,
+ channelId: string,
+): Promise<void> {
+ const pathname = `/c/channels/${serverId}/${channelId}`
+ await page.goto(pathname, { waitUntil: "commit" })
+ await expect(page).toHaveURL(pathname)
+}
+
async function seedServerRoute(
key: UserKey,
name: string,
@@ -235,7 +260,11 @@ test("slow target RSC survives delete/list/WS convergence and lands on its remem
)
const targetServerId = (await serverIds("carol")).find((id) => id !== deleted.serverId)
expect(targetServerId).toBeTruthy()
- await openServer(page, targetServerId!)
+ await openChannelRoute(
+ page,
+ targetServerId!,
+ await firstTextChannelId(page, targetServerId!),
+ )
const targetPathname = await expectServerLeaf(page, targetServerId!)
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
await openServer(page, deleted.serverId)
diff --git a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
index dab71b6f8..5e1f6d1c5 100644
--- a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
+++ b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
@@ -1,6 +1,7 @@
import type { Page, Request, Route, TestInfo } from "@playwright/test"
import { expect, test, userId } from "./_fixtures/community-fixture"
import { gotoAfterUserWsAuth, waitForElementMotion } from "./_fixtures/actions"
+import { COMMUNITY_LAYOUT_STORAGE_KEY } from "@/components/community/shell/shell-frame-geometry"
import {
memberInfo,
seedCancelFriendRequest,
@@ -13,7 +14,7 @@ import {
} from "./_fixtures/seed"
import { tid } from "./_fixtures/testids"
-const layoutStorageKey = "react-resizable-panels:community-shell"
+const layoutStorageKey = COMMUNITY_LAYOUT_STORAGE_KEY
const expectedDefaultSidebarWidth = 317
const expectedOuterWidth = 375
const expectedVisibleWidth = 359
@@ -24,10 +25,12 @@ const shellPanel = (page: Page, id: "sidebar" | "main") => (
)
type LayoutSample = {
+ frame: number
sidebar: number
overlay: number
viewportWidth: number
desktopVisible: boolean
+ pending: boolean
}
type ShellGeometry = {
@@ -77,8 +80,15 @@ const outdatedMachine = {
async function installLayoutState(
page: Page,
layout: { sidebar: number; main: number } | null,
+ sampleLimit = 240,
) {
- await page.addInitScript(({ key, savedLayout, sidebarTestId }) => {
+ await page.addInitScript(({
+ key,
+ savedLayout,
+ sidebarTestId,
+ pendingTestId,
+ sampleLimit,
+ }) => {
const initializedKey = `${key}:test-initialized`
if (!sessionStorage.getItem(initializedKey)) {
if (savedLayout) localStorage.setItem(key, JSON.stringify(savedLayout))
@@ -95,38 +105,72 @@ async function installLayoutState(
if (storageKey === key) storageWrites.push(value)
return originalSetItem.call(this, storageKey, value)
}
+ let frame = 0
const capture = () => {
+ frame += 1
const sidebar = document.querySelector<HTMLElement>(
`[data-slot="resizable-panel"][data-testid="${sidebarTestId}"]`,
)
const overlay = document.querySelector<HTMLElement>(
'[data-slot="community-user-bar-overlay"]',
)
- if (sidebar && overlay && samples.length < 240) {
+ if (sidebar && overlay && samples.length < sampleLimit) {
samples.push({
+ frame,
sidebar: sidebar.getBoundingClientRect().width,
overlay: overlay.getBoundingClientRect().width,
viewportWidth: window.innerWidth,
desktopVisible: getComputedStyle(sidebar).display !== "none"
&& getComputedStyle(overlay).display !== "none",
+ pending: document.querySelector(`[data-testid="${pendingTestId}"]`) !== null,
})
}
requestAnimationFrame(capture)
}
requestAnimationFrame(capture)
- }, { key: layoutStorageKey, savedLayout: layout, sidebarTestId: "sidebar" })
+ }, {
+ key: layoutStorageKey,
+ savedLayout: layout,
+ sidebarTestId: "sidebar",
+ pendingTestId: tid.initialFrame,
+ sampleLimit,
+ })
}
-async function holdSession(page: Page) {
+async function holdApplicationScripts(page: Page) {
let release!: () => void
const gate = new Promise<void>((resolve) => { release = resolve })
let hits = 0
+ let sessionRequests = 0
+ page.on("request", (request) => {
+ if (new URL(request.url()).pathname === "/api/auth/get-session") sessionRequests += 1
+ })
const handler = async (route: Route) => {
+ if (!/\/_next\/.*\.js(?:\?|$)/.test(route.request().url())) {
+ await route.continue()
+ return
+ }
hits += 1
await gate
await route.continue()
}
- await page.route("**/api/auth/get-session**", handler)
+ await page.route("**/_next/**", handler)
+ return { hits: () => hits, sessionRequests: () => sessionRequests, release }
+}
+
+async function holdCommunityReads(page: Page) {
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ let hits = 0
+ await page.route("**/api/community/**", async (route) => {
+ if (route.request().method() !== "GET") {
+ await route.continue()
+ return
+ }
+ hits += 1
+ await gate
+ await route.continue()
+ })
return { hits: () => hits, release }
}
@@ -250,14 +294,31 @@ function expectNoTransientDesktopWidth(
const visibleSamples = samples.filter(({ desktopVisible, sidebar, overlay }) => (
desktopVisible && sidebar > 0 && overlay > 0
))
- expect(visibleSamples.length).toBeGreaterThan(0)
- const transientSamples = visibleSamples.filter((sample) => (
+ const desktopSamples = visibleSamples.filter(({ viewportWidth }) => viewportWidth >= 640)
+ expect(desktopSamples.length).toBeGreaterThan(0)
+ const transientSamples = desktopSamples.filter((sample) => (
Math.abs(sample.sidebar - sidebarWidth) > geometryEpsilon
|| Math.abs(sample.overlay - (sidebarWidth + 58)) > geometryEpsilon
))
expect(transientSamples).toEqual([])
}
+function compactLayoutSamples(samples: LayoutSample[]) {
+ const compact: LayoutSample[] = []
+ for (const sample of samples) {
+ const previous = compact.at(-1)
+ if (
+ previous
+ && previous.sidebar === sample.sidebar
+ && previous.overlay === sample.overlay
+ && previous.desktopVisible === sample.desktopVisible
+ && previous.pending === sample.pending
+ ) continue
+ compact.push(sample)
+ }
+ return compact
+}
+
async function readComposerGeometry(page: Page): Promise<ComposerGeometry> {
return page.getByTestId(tid.channelComposerShell).evaluate((shell) => {
const base = shell.querySelector<HTMLElement>(
@@ -328,6 +389,64 @@ test.describe.serial("desktop default User Bar width", () => {
channelId = await seedChannel("alice", serverId, `desktop-width-${stamp}`)
})
+ test("prepaints saved pending-shell widths and preserves the loaded handoff", async ({
+ asUser,
+ }, testInfo) => {
+ test.setTimeout(240_000)
+ const evidence: Array<{
+ targetWidth: number
+ savedLayout: { sidebar: number; main: number }
+ sequence: LayoutSample[]
+ }> = []
+
+ for (const targetWidth of [100, 160, 240, 350, 360]) {
+ const session = await asUser("alice")
+ const page = session.page
+ await page.setViewportSize({ width: 1280, height: 900 })
+ const availablePanelWidth = 1280 - 58
+ const sidebar = targetWidth === 100
+ ? 0
+ : targetWidth === 360
+ ? 100
+ : targetWidth / availablePanelWidth * 100
+ const savedLayout = { sidebar, main: 100 - sidebar }
+ await installLayoutState(page, savedLayout, 2_000)
+ const scripts = await holdApplicationScripts(page)
+ const communityReads = await holdCommunityReads(page)
+
+ await page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
+ await expect.poll(scripts.hits).toBeGreaterThan(0)
+ const pendingFrame = page.getByTestId(tid.initialFrame)
+ await expect(pendingFrame).toBeVisible()
+ await expect.poll(async () => (
+ (await page.evaluate(() => (
+ Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]
+ ))).some(({ pending }) => pending)
+ )).toBe(true)
+ scripts.release()
+ communityReads.release()
+ await expect(page.getByTestId(tid.channelComposerShell)).toBeVisible()
+ await page.evaluate(() => new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ }))
+ const sequence = compactLayoutSamples(await page.evaluate(() => (
+ Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]
+ )))
+ evidence.push({ targetWidth, savedLayout, sequence })
+ await session.context.close()
+ }
+
+ await attachJson(testInfo, "saved-pending-shell-frame-sequences", evidence)
+ for (const { targetWidth, sequence } of evidence) {
+ expect(sequence.every(({ sidebar, overlay }) => (
+ Math.abs(sidebar - targetWidth) <= geometryEpsilon
+ && Math.abs(overlay - (targetWidth + 58)) <= geometryEpsilon
+ ))).toBe(true)
+ expect(sequence.some(({ pending }) => pending)).toBe(true)
+ expect(sequence.at(-1)?.pending).toBe(false)
+ }
+ })
+
test("keeps unsaved, saved, and user-resized layouts pixel-stable", async ({
asUser,
}, testInfo) => {
@@ -501,6 +620,19 @@ test.describe.serial("desktop default User Bar width", () => {
})
await interaction.page.reload({ waitUntil: "commit" })
await expectDesktopGeometry(interaction.page, resizedWidth)
+ const resetHandle = interaction.page.locator('[data-slot="resizable-handle"]')
+ await resetHandle.dblclick({ force: true })
+ await expectDesktopGeometry(interaction.page, expectedDefaultSidebarWidth)
+ await expect.poll(() => interaction.page.evaluate(
+ (key) => localStorage.getItem(key),
+ layoutStorageKey,
+ )).not.toBe(JSON.stringify(storedLayout))
+ const resetStorage = JSON.parse(await interaction.page.evaluate(
+ (key) => localStorage.getItem(key)!,
+ layoutStorageKey,
+ )) as Record<string, unknown>
+ await interaction.page.reload({ waitUntil: "commit" })
+ await expectDesktopGeometry(interaction.page, expectedDefaultSidebarWidth)
await attachJson(testInfo, "desktop-width-layout-evidence", {
hydrationSamples,
mobileGeometry,
@@ -521,7 +653,8 @@ test.describe.serial("desktop default User Bar width", () => {
resized: {
storage: storedLayout,
resizedWidth,
- reloadedWidth: (await readShellGeometry(interaction.page)).sidebar,
+ resetStorage,
+ reloadedResetWidth: (await readShellGeometry(interaction.page)).sidebar,
},
})
})
@@ -717,27 +850,28 @@ test.describe.serial("desktop default User Bar width", () => {
const seededLayout = { sidebar: 25, main: 75 }
const seededStorage = JSON.stringify(seededLayout)
+ const savedSidebarWidth = 0.25 * (1280 - 58)
const saved = await asUser("alice")
await saved.page.setViewportSize({ width: 390, height: 844 })
await installLayoutState(saved.page, seededLayout)
- await gotoAfterUserWsAuth(saved.page, `/c/channels/${serverId}/${channelId}`)
- await expect(saved.page.getByTestId(tid.channelComposerShell)).toBeVisible()
+ await gotoAfterUserWsAuth(saved.page, "/c/me")
+ await expect(saved.page.getByRole("button", { name: "Friends", exact: true })).toBeVisible()
await saved.page.setViewportSize({ width: 639, height: 844 })
- await expect(shellPanel(saved.page, "sidebar")).toBeHidden()
+ await expect(shellPanel(saved.page, "sidebar")).toBeVisible()
const firstSampleCursor = await saved.page.evaluate(() => (
Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]
).length)
await saved.page.setViewportSize({ width: 1280, height: 900 })
await expect(shellPanel(saved.page, "sidebar")).toBeVisible()
- await expect.poll(async () => (
- Math.abs((await readShellGeometry(saved.page)).sidebar - expectedDefaultSidebarWidth)
- )).toBeGreaterThan(1)
+ await expect.poll(() => saved.page.evaluate(() => (
+ document.documentElement.hasAttribute("data-community-shell-layout")
+ ))).toBe(false)
+ await expectDesktopGeometry(saved.page, savedSidebarWidth)
const firstAppliedWidth = (await readShellGeometry(saved.page)).sidebar
- await expectDesktopGeometry(saved.page, firstAppliedWidth)
const firstDesktopSamples = await saved.page.evaluate((cursor) => (
Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]
).slice(cursor), firstSampleCursor)
- expectNoTransientDesktopWidth(firstDesktopSamples, firstAppliedWidth)
+ expectNoTransientDesktopWidth(firstDesktopSamples, savedSidebarWidth)
expect(await saved.page.evaluate(
(key) => localStorage.getItem(key),
layoutStorageKey,
@@ -748,17 +882,23 @@ test.describe.serial("desktop default User Bar width", () => {
await saved.page.setViewportSize({ width: 639, height: 844 })
await expect(shellPanel(saved.page, "sidebar")).toBeHidden()
+ await saved.page.goto("/c/me")
+ await expect(saved.page.getByRole("button", { name: "Friends", exact: true })).toBeVisible()
+ await expect(shellPanel(saved.page, "sidebar")).toBeVisible()
const secondSampleCursor = await saved.page.evaluate(() => (
Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]
).length)
await saved.page.setViewportSize({ width: 1280, height: 900 })
- await expectDesktopGeometry(saved.page, firstAppliedWidth)
+ await expect.poll(() => saved.page.evaluate(() => (
+ document.documentElement.hasAttribute("data-community-shell-layout")
+ ))).toBe(false)
+ await expectDesktopGeometry(saved.page, savedSidebarWidth)
const secondAppliedWidth = (await readShellGeometry(saved.page)).sidebar
expect(secondAppliedWidth).toBe(firstAppliedWidth)
const secondDesktopSamples = await saved.page.evaluate((cursor) => (
Reflect.get(window, "__desktopWidthSamples") as LayoutSample[]
).slice(cursor), secondSampleCursor)
- expectNoTransientDesktopWidth(secondDesktopSamples, firstAppliedWidth)
+ expectNoTransientDesktopWidth(secondDesktopSamples, savedSidebarWidth)
const finalStorage = await saved.page.evaluate(
(key) => localStorage.getItem(key),
layoutStorageKey,
@@ -784,7 +924,7 @@ test.describe.serial("desktop default User Bar width", () => {
await saved.context.close()
})
- test("captures closed, Inbox, Profile, update, and cold Skeleton parity", async ({
+ test("captures closed, Inbox, Profile, update, and cold restore parity", async ({
asUser,
}, testInfo) => {
test.setTimeout(240_000)
@@ -903,16 +1043,23 @@ test.describe.serial("desktop default User Bar width", () => {
await pending.page.setViewportSize({ width, height: width === 1024 ? 768 : 900 })
await pending.page.emulateMedia({ colorScheme: theme })
await installLayoutState(pending.page, null)
- const session = await holdSession(pending.page)
+ const scripts = await holdApplicationScripts(pending.page)
+ const communityReads = await holdCommunityReads(pending.page)
await pending.page.goto(`/c/channels/${serverId}`, { waitUntil: "commit" })
- await expect.poll(session.hits).toBeGreaterThan(0)
- await expect(pending.page.getByTestId(tid.initialFrame)).toBeVisible()
- await expect(pending.page.getByTestId(tid.initialUserBarPending)).toBeVisible()
+ await expect.poll(scripts.hits).toBeGreaterThan(0)
+ expect(scripts.sessionRequests()).toBe(0)
+ const pendingFrame = pending.page.getByTestId(tid.initialFrame)
+ await expect(pendingFrame).toBeVisible()
+ await expect(pendingFrame).toHaveAttribute("aria-busy", "true")
+ await expect(pendingFrame).toHaveAttribute("data-community-route-kind", "server-root")
+ await expect(pending.page.locator('[data-slot="community-restore-bootstrap"]')).toHaveCount(0)
+ await expect(pendingFrame.locator('[data-slot="skeleton"]')).not.toHaveCount(0)
+ scripts.release()
+ await expect.poll(communityReads.hits).toBeGreaterThan(0)
+ await expect(pending.page.locator('[data-slot="community-shell-root"]')).toBeVisible()
const pendingSidebar = shellPanel(pending.page, "sidebar")
const pendingOverlay = pending.page.locator('[data-slot="community-user-bar-overlay"]')
- const pendingBase = pending.page.getByTestId(tid.initialUserBarPending).locator(
- ":scope > div",
- )
+ const pendingBase = pending.page.locator('[data-slot="community-user-bar-base"]')
await expect.poll(async () => Math.abs(
((await pendingSidebar.boundingBox())?.width ?? 0) - expectedDefaultSidebarWidth,
)).toBeLessThanOrEqual(geometryEpsilon)
@@ -925,11 +1072,11 @@ test.describe.serial("desktop default User Bar width", () => {
await attachScreenshot(
pending.page,
testInfo,
- `user-bar-${width}-${theme}-cold-skeleton`,
+ `user-bar-${width}-${theme}-cold-restore`,
)
expect(await pending.page.evaluate((key) => localStorage.getItem(key), layoutStorageKey))
.toBeNull()
- session.release()
+ communityReads.release()
await pending.context.close()
}
}
diff --git a/src/web/src/test/e2e-ui/_fixtures/actions.ts b/src/web/src/test/e2e-ui/_fixtures/actions.ts
index 7e87f1ef5..a72ec5517 100644
--- a/src/web/src/test/e2e-ui/_fixtures/actions.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/actions.ts
@@ -1,4 +1,4 @@
-import { type Locator, type Page, type WebSocket, expect } from "@playwright/test"
+import { type Locator, type Page, expect } from "@playwright/test"
import { tid } from "./testids"
const HOVER_FINE_QUERY = "(hover: hover) and (pointer: fine)"
@@ -19,36 +19,6 @@ export async function waitForElementMotion(locator: Locator): Promise<void> {
export const GEOMETRY_EPSILON = 0.01
-export function observeUserWsAuth(page: Page): {
- authenticated: Promise<void>
- cleanup: () => void
-} {
- const frameHandlers = new Map<WebSocket, (event: { payload: string | Buffer }) => void>()
- let cleanup = () => {}
- const authenticated = new Promise<void>((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error("user WebSocket did not authenticate")), 20_000)
- const onWebSocket = (socket: WebSocket) => {
- const onFrame = (event: { payload: string | Buffer }) => {
- try {
- const message = JSON.parse(event.payload.toString()) as { type?: string }
- if (message.type !== "auth.ok") return
- cleanup()
- resolve()
- } catch {}
- }
- frameHandlers.set(socket, onFrame)
- socket.on("framereceived", onFrame)
- }
- cleanup = () => {
- clearTimeout(timer)
- page.off("websocket", onWebSocket)
- for (const [socket, handler] of frameHandlers) socket.off("framereceived", handler)
- }
- page.on("websocket", onWebSocket)
- })
- return { authenticated, cleanup: () => cleanup() }
-}
-
export async function installInputCapability(
page: Page,
hoverCapable: boolean,
@@ -71,13 +41,27 @@ export async function installInputCapability(
}
export async function gotoAfterUserWsAuth(page: Page, url: string): Promise<void> {
- const auth = observeUserWsAuth(page)
-
- try {
- await Promise.all([page.goto(url, { waitUntil: "commit" }), auth.authenticated])
- } finally {
- auth.cleanup()
- }
+ const attribute = "data-e2e-user-ws-authenticated"
+ await page.addInitScript(({ attribute }) => {
+ const NativeWebSocket = window.WebSocket
+ window.WebSocket = class extends NativeWebSocket {
+ constructor(...args: ConstructorParameters<typeof WebSocket>) {
+ super(...args)
+ if (!new URL(this.url).pathname.endsWith("/user")) return
+ this.addEventListener("message", (event) => {
+ if (typeof event.data !== "string") return
+ try {
+ const message = JSON.parse(event.data) as { type?: string }
+ if (message.type === "auth.ok") {
+ document.documentElement.setAttribute(attribute, "true")
+ }
+ } catch {}
+ })
+ }
+ }
+ }, { attribute })
+ await page.goto(url, { waitUntil: "commit" })
+ await expect(page.locator("html")).toHaveAttribute(attribute, "true", { timeout: 20_000 })
}
// Keep Next's development-only portals from capturing pointer input intended
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
index 79c65042f..d3d680719 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
@@ -3,7 +3,6 @@ import type {
BrowserContextOptions,
Locator,
Page,
- Route,
TestInfo,
} from "@playwright/test"
import { expect, sessionCookie, userId } from "./community-fixture"
@@ -38,6 +37,7 @@ type PersistedSidebarWidth = 100 | 160 | 240 | 350 | 360
const RAIL_OVERFLOW_SERVER_COUNT = 20
const ISOLATED_GEOMETRY_USER: UserKey = "dave"
const DESKTOP_DENSITY_SCALES = [1, 1.25] as const
+const ONE_CSS_PIXEL_WITH_LAYOUT_QUANTIZATION = 1 + (1 / 64)
const ANDROID_USER_AGENTS = {
chrome: "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36",
webview: "Mozilla/5.0 (Linux; Android 15; Pixel 9 Build/AP3A.240905.015; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/140.0.0.0 Mobile Safari/537.36",
@@ -55,25 +55,16 @@ type MatrixCase = {
}
}
-async function holdSession(page: Page) {
- let release!: () => void
- const gate = new Promise<void>((resolve) => { release = resolve })
- let hits = 0
- const handler = async (route: Route) => {
- hits += 1
- await gate
- await route.continue()
- }
- await page.route("**/api/auth/get-session**", handler)
- return { hits: () => hits, release }
-}
-
async function holdApplicationScripts(page: Page) {
let release!: () => void
const gate = new Promise<void>((resolve) => { release = resolve })
const blocked: string[] = []
const received: string[] = []
+ let sessionRequests = 0
const isApplicationScript = (url: string) => /\/_next\/.*\.js(?:\?|$)/.test(url)
+ page.on("request", (request) => {
+ if (new URL(request.url()).pathname === "/api/auth/get-session") sessionRequests += 1
+ })
page.on("response", (response) => {
if (isApplicationScript(response.url())) received.push(response.url())
})
@@ -84,7 +75,56 @@ async function holdApplicationScripts(page: Page) {
}
await route.continue()
})
- return { blocked, received, release }
+ return { blocked, received, sessionRequests: () => sessionRequests, release }
+}
+
+async function holdCommunityReads(page: Page) {
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ let hits = 0
+ await page.route("**/api/community/**", async (route) => {
+ if (route.request().method() !== "GET") {
+ await route.continue()
+ return
+ }
+ hits += 1
+ await gate
+ await route.continue()
+ })
+ return { hits: () => hits, release }
+}
+
+async function expectServerSeededRouteFrame(
+ page: Page,
+ width: number,
+ height: number,
+) {
+ const frame = page.getByTestId(tid.initialFrame)
+ await expect(frame).toBeVisible()
+ await expect(frame).toHaveAttribute("aria-busy", "true")
+ await expect(frame).toHaveAttribute("aria-label", "Loading community")
+ await expect(page.locator('[data-slot="community-restore-bootstrap"]')).toHaveCount(0)
+ await expect(frame.locator(
+ '[data-slot="skeleton"], [data-community-unresolved-main]',
+ )).not.toHaveCount(0)
+ const geometry = await frame.evaluate((root) => {
+ const rect = (element: Element) => {
+ const box = element.getBoundingClientRect()
+ return {
+ display: getComputedStyle(element).display,
+ x: box.x,
+ y: box.y,
+ width: box.width,
+ height: box.height,
+ }
+ }
+ return {
+ root: rect(root),
+ overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
+ }
+ })
+ expect(geometry.overflow).toBe(0)
+ expect(geometry.root).toMatchObject({ x: 0, y: 0, width, height })
}
async function holdRequest(page: Page, pattern: string) {
@@ -234,7 +274,7 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
}
const sample = () => {
const shell = document.querySelector('[data-slot="community-shell-root"]')
- if (shell || parsed) {
+ if (shell) {
const activePanel = '[data-slot="resizable-panel"][data-mobile-active="true"]'
const hiddenPanel = '[data-slot="resizable-panel"][data-mobile-hidden="true"]'
const geometry = Object.fromEntries(Object.entries({
@@ -251,7 +291,7 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
: Reflect.get(window, "__communityApplicationScriptsReleased") ? "hydrating" : "ssr",
readyState: document.readyState,
shellChildCount: shell?.childElementCount ?? 0,
- incompleteShellHtml: geometry.surface ? undefined : shell?.outerHTML ?? "",
+ incompleteShellHtml: geometry.surface ? undefined : shell.outerHTML,
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
geometry,
})
@@ -271,7 +311,7 @@ async function ssrLifecycleSamples(page: Page): Promise<SsrLifecycleSample[]> {
function desktopPanelTrackWidth(viewportWidth: DesktopWidth) {
return viewportWidth
- COMMUNITY_RAIL_WIDTH
- - COMMUNITY_SURFACE_BORDER_WIDTH
+ - (COMMUNITY_SURFACE_BORDER_WIDTH * 2)
- COMMUNITY_SEPARATOR_WIDTH
}
@@ -281,7 +321,7 @@ async function installDesktopPendingFrameProbe(
sidebarWidth: PersistedSidebarWidth | null,
) {
const panelTrackWidth = desktopPanelTrackWidth(viewportWidth)
- await page.addInitScript(({ initialFrameTestId, layoutStorageKey, persistedLayout }) => {
+ await page.addInitScript(({ layoutStorageKey, persistedLayout }) => {
if (persistedLayout) {
localStorage.setItem(layoutStorageKey, JSON.stringify(persistedLayout))
} else {
@@ -289,9 +329,10 @@ async function installDesktopPendingFrameProbe(
}
const samples: DesktopPendingFrameSample[] = []
Reflect.set(window, "__communityDesktopPendingFrameSamples", samples)
+ Reflect.set(window, "__communityDesktopPendingFrameProbeStopped", false)
const sample = () => {
- const frame = document.querySelector(`[data-testid="${initialFrameTestId}"]`)
+ const frame = document.querySelector('[data-slot="community-shell-root"]')
const panels = frame?.querySelectorAll<HTMLElement>('[data-slot="resizable-panel"]')
const sidebar = panels?.[0]
const main = panels?.[1]
@@ -310,11 +351,12 @@ async function installDesktopPendingFrameProbe(
userBarRight: userBarRect.right,
})
}
- if (performance.now() < 5_000) requestAnimationFrame(sample)
+ if (!Reflect.get(window, "__communityDesktopPendingFrameProbeStopped")) {
+ requestAnimationFrame(sample)
+ }
}
requestAnimationFrame(sample)
}, {
- initialFrameTestId: tid.initialFrame,
layoutStorageKey: "react-resizable-panels:community-shell",
persistedLayout: sidebarWidth === null
? null
@@ -479,34 +521,36 @@ export async function runAndroidLoadingGeometry(asUser: CommunityAsUser, testInf
const { context, page } = await asUser("alice", { userAgent })
await page.setViewportSize({ width, height: width === 320 ? 720 : 900 })
await installSsrLifecycleProbe(page, surface)
- const session = await holdSession(page)
const scripts = await holdApplicationScripts(page)
+ const communityReads = await holdCommunityReads(page)
let ssrEvidence: unknown
try {
- await page.goto(pathname, { waitUntil: "domcontentloaded" })
+ await page.goto(pathname, { waitUntil: "commit" })
await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.initialFrame)).toBeVisible()
+ await expectServerSeededRouteFrame(page, width, width === 320 ? 720 : 900)
await page.waitForTimeout(250)
- const ssrSamples = await ssrLifecycleSamples(page)
ssrEvidence = {
- samples: ssrSamples,
blockedScripts: [...scripts.blocked],
receivedScripts: [...scripts.received],
- sessionRequests: session.hits(),
+ sessionRequests: scripts.sessionRequests(),
}
expect(scripts.received, "application JS must remain blocked during SSR measurement").toEqual([])
- expect(session.hits(), "application session request must not run before JS release").toBe(0)
- expect(ssrSamples.some((sample) => sample.phase === "ssr")).toBe(true)
- expectMobileGeometry(ssrSamples, width, surface)
+ expect(
+ scripts.sessionRequests(),
+ "server-seeded identity must not issue a browser session request",
+ ).toBe(0)
+ await page.evaluate(() => Reflect.set(window, "__communityApplicationScriptsReleased", true))
+ scripts.release()
+ await expect.poll(communityReads.hits).toBeGreaterThan(0)
+ await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()
+ await page.waitForTimeout(250)
+ const pendingSamples = await ssrLifecycleSamples(page)
+ expectMobileGeometry(pendingSamples, width, surface)
const pendingHeading = pathname === "/c/me/machines"
? await expectMachinesHeadingSpacing(page)
: null
- await page.evaluate(() => Reflect.set(window, "__communityApplicationScriptsReleased", true))
- scripts.release()
- await expect.poll(session.hits).toBeGreaterThan(0)
- session.release()
- await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })
+ communityReads.release()
await expect(
pathname === "/c/me"
? page.getByRole("button", { name: "Friends", exact: true })
@@ -525,12 +569,12 @@ export async function runAndroidLoadingGeometry(asUser: CommunityAsUser, testInf
ssrEvidence,
allSamples: await ssrLifecycleSamples(page),
releasedScriptResponses: scripts.received,
- sessionRequests: session.hits(),
+ sessionRequests: scripts.sessionRequests(),
})),
contentType: "application/json",
})
scripts.release()
- session.release()
+ communityReads.release()
await context.close()
}
}
@@ -552,13 +596,23 @@ export async function runDesktopPersistedPendingGeometry(
await page.setViewportSize({ width: viewportWidth, height: 900 })
await page.emulateMedia({ colorScheme: theme })
await installDesktopPendingFrameProbe(page, viewportWidth, sidebarWidth)
- const session = await holdSession(page)
+ const scripts = await holdApplicationScripts(page)
+ const communityReads = await holdCommunityReads(page)
await page.goto("/c/me/machines", { waitUntil: "commit" })
- await expect.poll(session.hits).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.initialFrame)).toBeVisible()
+ await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)
+ expect(scripts.sessionRequests()).toBe(0)
+ await expectServerSeededRouteFrame(page, viewportWidth, 900)
+ scripts.release()
+ await expect.poll(communityReads.hits).toBeGreaterThan(0)
+ await expect(page.locator('[data-slot="community-shell-root"]')).toBeVisible()
await page.waitForTimeout(250)
const samples = await desktopPendingFrameSamples(page)
+ await page.evaluate(() => Reflect.set(
+ window,
+ "__communityDesktopPendingFrameProbeStopped",
+ true,
+ ))
expect(samples.length, caseLabel).toBeGreaterThan(0)
for (const [index, sample] of samples.entries()) {
expect(sample.overflow, `${caseLabel}, frame ${index} horizontal overflow`).toBe(0)
@@ -582,9 +636,9 @@ export async function runDesktopPersistedPendingGeometry(
expect(
Math.abs(samples.at(-1)!.sidebarWidth - expectedSidebarWidth),
`${caseLabel}, final sidebar width: ${JSON.stringify(samples.at(-1))}`,
- ).toBeLessThanOrEqual(1)
+ ).toBeLessThanOrEqual(ONE_CSS_PIXEL_WITH_LAYOUT_QUANTIZATION)
- session.release()
+ communityReads.release()
await context.close()
}
}
@@ -598,15 +652,20 @@ export async function runSkeletonLoadingMotion(asUser: CommunityAsUser) {
})
await page.setViewportSize({ width: 320, height: 720 })
await page.emulateMedia({ reducedMotion })
- const session = await holdSession(page)
+ const scripts = await holdApplicationScripts(page)
+ const communityReads = await holdCommunityReads(page)
await page.goto("/c/me/machines", { waitUntil: "commit" })
- await expect.poll(session.hits).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.initialFrame)).toBeVisible()
+ await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)
+ expect(scripts.sessionRequests()).toBe(0)
+ await expectServerSeededRouteFrame(page, 320, 720)
+ scripts.release()
+ await expect.poll(communityReads.hits).toBeGreaterThan(0)
+ await expect(page.locator('[data-slot="skeleton"]:visible').first()).toBeVisible()
const animationProperties = await visibleSkeletonAnimationProperties(page)
expect(animationProperties).toEqual(reducedMotion === "reduce" ? [] : ["opacity"])
- session.release()
+ communityReads.release()
await context.close()
}
}
@@ -623,18 +682,13 @@ export async function runNeutralRootGeometry(
await page.addInitScript((storageKey) => {
localStorage.removeItem(storageKey)
}, `community:lastRoute:${encodeURIComponent(userId(ISOLATED_GEOMETRY_USER))}`)
- const session = await holdSession(page)
+ const scripts = await holdApplicationScripts(page)
await page.goto("/c", { waitUntil: "commit" })
- await expect.poll(session.hits).toBeGreaterThan(0)
+ await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)
+ expect(scripts.sessionRequests()).toBe(0)
const frame = page.getByTestId(tid.initialFrame)
- await expect(frame).toBeVisible()
- await expect(frame).toHaveAttribute(
- "data-community-route-kind",
- "community-root-redirect",
- )
- await expect(page.getByTestId(tid.pendingMain("route-resolution"))).toBeVisible()
- await expect(page.getByTestId(tid.pendingMain("machines"))).toHaveCount(0)
+ await expectServerSeededRouteFrame(page, width, width === 390 ? 844 : 900)
await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(0)
await expect(page.getByTestId(tid.initialRailPending)).toHaveCount(0)
await expect(page.getByTestId(tid.dmSidebarPending)).toHaveCount(0)
@@ -657,8 +711,8 @@ export async function runNeutralRootGeometry(
contentType: "image/png",
})
- session.release()
- await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })
+ scripts.release()
+ await expect(frame).toHaveCount(0, { timeout: 30_000 })
await expect.poll(() => new URL(page.url()).pathname).toBe("/c/me/machines")
await expect(page.getByTestId(tid.machinePairOpen)).toBeVisible({ timeout: 30_000 })
expect(await page.evaluate(() => (
@@ -685,15 +739,22 @@ export async function runRouteLoadingGeometry(
await page.setViewportSize({ width: entry.width, height: entry.width === 390 ? 844 : 900 })
await page.emulateMedia({ colorScheme: theme })
await startClsObserver(page)
- const session = await holdSession(page)
+ const scripts = await holdApplicationScripts(page)
+ const communityReads = await holdCommunityReads(page)
const intermediate = entry.intermediate
? await holdRequest(page, entry.intermediate.requestPattern)
: null
await page.goto(entry.pathname, { waitUntil: "commit" })
- await expect.poll(session.hits).toBeGreaterThan(0)
- await expect(page.getByTestId(tid.initialFrame)).toBeVisible()
+ await expect.poll(() => scripts.blocked.length).toBeGreaterThan(0)
+ expect(scripts.sessionRequests()).toBe(0)
+ await expectServerSeededRouteFrame(
+ page,
+ entry.width,
+ entry.width === 390 ? 844 : 900,
+ )
+ scripts.release()
+ await expect.poll(communityReads.hits).toBeGreaterThan(0)
await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(1)
- await expect(page.locator('[data-slot="community-shell-root"] button')).toHaveCount(0)
const pendingAdd = page.locator('[data-slot="community-server-rail-add"]')
await expect(pendingAdd).toHaveCount(0)
expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth))
@@ -707,10 +768,9 @@ export async function runRouteLoadingGeometry(
})
await resetCls(page)
- session.release()
- await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })
+ communityReads.release()
if (entry.intermediate && intermediate) {
- await expect.poll(intermediate.hits).toBeGreaterThan(0)
+ await expect.poll(intermediate.hits, { timeout: 30_000 }).toBeGreaterThan(0)
await expect(entry.intermediate.ready(page)).toBeVisible({ timeout: 30_000 })
const intermediatePath = testInfo.outputPath(
`${theme}-${entry.width}-${entry.name}-intermediate.png`,
@@ -726,7 +786,7 @@ export async function runRouteLoadingGeometry(
await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(1)
const loadedAdd = page.getByTestId(tid.serverAdd)
if (entry.width === 1280 || entry.mobileRail) {
- await expect(loadedAdd).toBeVisible()
+ await expect(loadedAdd).toBeVisible({ timeout: 30_000 })
const railScroll = page.getByTestId(tid.serverRailScroll)
await expect(railScroll).toBeVisible()
expect(await railScroll.evaluate((element) => element.scrollHeight > element.clientHeight))
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts
index af2f2d810..9c40233ff 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts
@@ -3,8 +3,7 @@ import { expect, type BrowserContext, type Page, type Request } from "@playwrigh
import { proxyCommunityWebSockets } from "./community-ws-proxy"
export const notificationPaths = [
- "/api/community/users/me/inbox/unreads",
- "/api/community/users/me/inbox/mentions",
+ "/api/community/users/me/attention",
"/api/community/users/me/dms",
]
@@ -74,7 +73,10 @@ export async function gotoAfterNotificationStartup(
await initial
await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
trace.phase("auth-release")
- const authenticatedRefresh = notificationResponsesFinished(page)
+ const authenticatedRefresh = notificationResponsesFinished(
+ page,
+ notificationPaths.filter((path) => path.endsWith("/dms")),
+ )
holdAuthentication = false
expect(proxy.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)
await authenticatedRefresh
diff --git a/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
new file mode 100644
index 000000000..501e93c9b
--- /dev/null
+++ b/src/web/src/test/e2e-ui/community-cache-first-warm-reload.journey.ts
@@ -0,0 +1,410 @@
+import type { Page } from "@playwright/test"
+import { expect, test, userId } from "./_fixtures/community-fixture"
+import {
+ seedChannel,
+ seedDm,
+ seedDmMessage,
+ seedMessage,
+ seedServer,
+ seedThread,
+} from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+type ReloadCapture = {
+ customBootstrapSeen: boolean
+ skeletonSeen: boolean
+ firstSkeleton: string | null
+ marks: Record<"start" | "complete" | "cached" | "stable", number>
+}
+
+type PersistedExpectation = {
+ key: readonly unknown[]
+ containsId?: string
+}
+
+type PersistedQuery = {
+ queryKey: unknown[]
+ data: unknown
+}
+
+const structuralLoadingSelectors = [
+ '[aria-label="Loading community"]',
+ "[data-message-list-skeleton]",
+ `[data-testid^="${tid.pendingMain("")}"]`,
+ `[data-testid="${tid.initialRailPending}"]`,
+ `[data-testid="${tid.dmSidebarPending}"]`,
+ `[data-testid^="${tid.channelSidebarPending("")}"]`,
+]
+
+async function persistedQueries(page: Page, viewerId: string): Promise<PersistedQuery[]> {
+ return page.evaluate((key) => new Promise<PersistedQuery[]>((resolve, reject) => {
+ const open = indexedDB.open("keyval-store")
+ open.onerror = () => reject(open.error ?? new Error("failed to open query persister"))
+ open.onsuccess = () => {
+ const db = open.result
+ if (!db.objectStoreNames.contains("keyval")) {
+ db.close()
+ resolve([])
+ return
+ }
+ const request = db.transaction("keyval", "readonly").objectStore("keyval").get(key)
+ request.onerror = () => {
+ db.close()
+ reject(request.error ?? new Error("failed to read query persister"))
+ }
+ request.onsuccess = () => {
+ db.close()
+ if (typeof request.result !== "string") {
+ resolve([])
+ return
+ }
+ const persisted = JSON.parse(request.result) as {
+ clientState?: {
+ queries?: Array<{ queryKey?: unknown[]; state?: { data?: unknown } }>
+ }
+ }
+ resolve((persisted.clientState?.queries ?? []).flatMap((query) => (
+ Array.isArray(query.queryKey)
+ ? [{ queryKey: query.queryKey, data: query.state?.data }]
+ : []
+ )))
+ }
+ }
+ }), `alook:qc:v2:${viewerId}:client`)
+}
+
+function containsPersistedId(value: unknown, id: string): boolean {
+ if (Array.isArray(value)) return value.some((entry) => containsPersistedId(entry, id))
+ if (!value || typeof value !== "object") return false
+ const record = value as Record<string, unknown>
+ return Object.values(record).some((entry) => (
+ entry === id || containsPersistedId(entry, id)
+ ))
+}
+
+async function expectPersistedClosure(
+ page: Page,
+ viewerId: string,
+ expected: readonly PersistedExpectation[],
+) {
+ const missingClosure = async () => {
+ const queries = await persistedQueries(page, viewerId)
+ const persisted = new Map(
+ queries.map((query) => [JSON.stringify(query.queryKey), query.data]),
+ )
+ const failures = expected.flatMap(({ key, containsId }) => {
+ const hash = JSON.stringify(key)
+ if (!persisted.has(hash)) return [`missing ${hash}`]
+ if (containsId && !containsPersistedId(persisted.get(hash), containsId)) {
+ return [`${hash} missing entity ${containsId}`]
+ }
+ return []
+ })
+ const rawMessageQuery = queries.find(({ queryKey }) => (
+ queryKey[0] === "community"
+ && (queryKey[1] === "channel" || queryKey[1] === "dm")
+ && queryKey[3] === "messages"
+ ))
+ if (rawMessageQuery) {
+ failures.push(`unexpected raw message key ${JSON.stringify(rawMessageQuery.queryKey)}`)
+ }
+ return failures
+ }
+ await expect.poll(missingClosure, { timeout: 20_000 }).toEqual([])
+ // The async persister coalesces cache events on a one-second throttle. A
+ // single matching read can still observe the previous blob while a final
+ // write is queued. Require both the keys and target entities to survive one
+ // throttle interval before reloading under blocked network conditions.
+ await page.waitForTimeout(1_100)
+ await expect.poll(missingClosure, { timeout: 20_000 }).toEqual([])
+}
+
+async function clearQueryPersistence(page: Page) {
+ await page.evaluate(() => new Promise<void>((resolve, reject) => {
+ const open = indexedDB.open("keyval-store")
+ open.onerror = () => reject(open.error ?? new Error("failed to open query persister"))
+ open.onsuccess = () => {
+ const db = open.result
+ if (!db.objectStoreNames.contains("keyval")) {
+ db.close()
+ resolve()
+ return
+ }
+ const transaction = db.transaction("keyval", "readwrite")
+ transaction.objectStore("keyval").clear()
+ transaction.oncomplete = () => {
+ db.close()
+ resolve()
+ }
+ transaction.onerror = () => {
+ db.close()
+ reject(transaction.error ?? new Error("failed to clear query persister"))
+ }
+ }
+ }))
+}
+
+async function expectCacheFirstReload(
+ page: Page,
+ assertCachedContent: () => Promise<void>,
+): Promise<ReloadCapture> {
+ await page.addInitScript((loadingSelectors) => {
+ const state = {
+ customBootstrapSeen: false,
+ skeletonSeen: false,
+ firstSkeleton: null as string | null,
+ }
+ Object.defineProperty(window, "__cacheFirstReload", {
+ configurable: true,
+ value: state,
+ })
+ const inspect = () => {
+ if (document.querySelector('[data-slot="community-restore-bootstrap"]')) {
+ state.customBootstrapSeen = true
+ }
+ const skeleton = document.querySelector(loadingSelectors.join(","))
+ if (skeleton) {
+ state.skeletonSeen = true
+ state.firstSkeleton ??= [
+ skeleton.outerHTML.slice(0, 300),
+ ...Array.from({ length: 5 }, (_, index) => {
+ let ancestor = skeleton.parentElement
+ for (let step = 0; step < index; step += 1) ancestor = ancestor?.parentElement ?? null
+ if (!ancestor) return ""
+ return `${ancestor.tagName.toLowerCase()}#${ancestor.id}.${ancestor.className}`
+ }).filter(Boolean),
+ ].join(" <- ")
+ }
+ }
+ new MutationObserver(inspect).observe(document, { childList: true, subtree: true })
+ inspect()
+ }, structuralLoadingSelectors)
+
+ let releaseReads!: () => void
+ const readsGate = new Promise<void>((resolve) => { releaseReads = resolve })
+ let heldReads = 0
+ await page.route("**/api/community/**", async (route) => {
+ if (route.request().method() !== "GET") {
+ await route.continue()
+ return
+ }
+ heldReads += 1
+ await readsGate
+ await route.continue().catch(() => {})
+ })
+ let wsAttempts = 0
+ await page.routeWebSocket((url) => url.pathname.endsWith("/user"), (socket) => {
+ wsAttempts += 1
+ void socket.close({ code: 1012, reason: "cache-first warm reload probe" })
+ })
+
+ try {
+ await page.reload({ waitUntil: "commit" })
+ await assertCachedContent()
+ await expect.poll(() => heldReads).toBeGreaterThan(0)
+ await expect.poll(() => wsAttempts).toBeGreaterThan(0)
+ const readCapture = () => page.evaluate((): ReloadCapture | null => {
+ const state = (window as unknown as {
+ __cacheFirstReload?: {
+ customBootstrapSeen: boolean
+ skeletonSeen: boolean
+ firstSkeleton: string | null
+ }
+ }).__cacheFirstReload
+ const latest = (name: string) => performance.getEntriesByName(name, "mark").at(-1)?.startTime
+ const marks = {
+ start: latest("alook:restore:start"),
+ complete: latest("alook:restore:complete"),
+ cached: latest("alook:restore:first-cached-paint"),
+ stable: latest("alook:restore:stable"),
+ }
+ if (Object.values(marks).some((mark) => mark === undefined)) {
+ return null
+ }
+ return {
+ customBootstrapSeen: state?.customBootstrapSeen === true,
+ skeletonSeen: state?.skeletonSeen === true,
+ firstSkeleton: state?.firstSkeleton ?? null,
+ marks: marks as ReloadCapture["marks"],
+ }
+ })
+ await expect.poll(readCapture, { timeout: 10_000 }).not.toBeNull()
+ const capture = await readCapture()
+ if (!capture) throw new Error("warm reload restore lifecycle marks are incomplete")
+ expect(capture.customBootstrapSeen).toBe(false)
+ expect(capture.skeletonSeen, capture.firstSkeleton ?? "warm reload regional skeleton").toBe(true)
+ expect(capture.marks.complete).toBeGreaterThanOrEqual(capture.marks.start)
+ expect(capture.marks.cached).toBeGreaterThanOrEqual(capture.marks.complete)
+ expect(capture.marks.stable).toBeGreaterThanOrEqual(capture.marks.cached)
+ return capture
+ } finally {
+ releaseReads()
+ await page.unroute("**/api/community/**")
+ }
+}
+
+test("a warm channel reload replaces regional skeletons with cached shell and messages", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const suffix = Date.now().toString(36)
+ const serverId = await seedServer("alice", `Warm channel ${suffix}`)
+ const channelId = await seedChannel("alice", serverId, `warm-${suffix}`)
+ const body = `cached channel ${suffix}`
+ const messageId = await seedMessage("alice", channelId, body)
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${channelId}`)
+ await expect(page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })
+ await expectPersistedClosure(page, userId("alice"), [
+ { key: ["community", "db", userId("alice"), "servers"], containsId: serverId },
+ { key: ["community", "db", userId("alice"), "folders"] },
+ { key: ["community", "db", userId("alice"), "channels"], containsId: channelId },
+ { key: ["community", "db", userId("alice"), "messages"], containsId: messageId },
+ ])
+
+ await expectCacheFirstReload(page, async () => {
+ await expect(page.getByTestId(tid.serverIcon(serverId))).toBeVisible({ timeout: 10_000 })
+ await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
+ await expect(page.getByText(body, { exact: false }).first()).toBeVisible()
+ })
+})
+
+test("a warm DM reload replaces regional skeletons with cached identity and messages", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const dmId = await seedDm("alice", userId("bob"))
+ const body = `cached dm ${Date.now()}`
+ const messageId = await seedDmMessage("bob", dmId, body)
+ const { page } = await asUser("alice")
+ await page.goto(`/c/me/${dmId}`)
+ await expect(page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })
+ await expectPersistedClosure(page, userId("alice"), [
+ { key: ["community", "db", userId("alice"), "servers"] },
+ { key: ["community", "db", userId("alice"), "folders"] },
+ { key: ["community", "db", userId("alice"), "channels"], containsId: dmId },
+ { key: ["community", "db", userId("alice"), "channelMemberships"], containsId: dmId },
+ { key: ["community", "db", userId("alice"), "profiles"], containsId: userId("bob") },
+ { key: ["community", "db", userId("alice"), "messages"], containsId: messageId },
+ ])
+
+ await expectCacheFirstReload(page, async () => {
+ await expect(page.getByTestId(tid.dmRow(dmId))).toBeVisible({ timeout: 10_000 })
+ await expect(page.getByText(body, { exact: false }).first()).toBeVisible()
+ })
+})
+
+test("a warm desktop split reload replaces regional skeletons in both cached panes", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const suffix = Date.now().toString(36)
+ const serverId = await seedServer("alice", `Warm split ${suffix}`)
+ const channelId = await seedChannel("alice", serverId, `split-${suffix}`)
+ const parentBody = `cached parent ${suffix}`
+ const openerId = await seedMessage("alice", channelId, parentBody)
+ const threadId = await seedThread("alice", openerId, `thread-${suffix}`)
+ const threadBody = `cached thread ${suffix}`
+ const threadMessageId = await seedMessage("alice", threadId, threadBody)
+ const { page } = await asUser("alice", { viewport: { width: 1280, height: 900 } })
+ await page.goto(`/c/channels/${serverId}/${threadId}`)
+ await expect(page.getByTestId(tid.threadSplit)).toHaveAttribute("data-layout", "split", {
+ timeout: 20_000,
+ })
+ await expect(page.getByText(threadBody, { exact: false }).first()).toBeVisible({ timeout: 20_000 })
+ await expectPersistedClosure(page, userId("alice"), [
+ { key: ["community", "db", userId("alice"), "servers"], containsId: serverId },
+ { key: ["community", "db", userId("alice"), "folders"] },
+ { key: ["community", "db", userId("alice"), "channels"], containsId: channelId },
+ { key: ["community", "db", userId("alice"), "messages"], containsId: openerId },
+ { key: ["community", "db", userId("alice"), "messages"], containsId: threadMessageId },
+ ])
+
+ await expectCacheFirstReload(page, async () => {
+ await expect(page.getByTestId(tid.threadSplit)).toHaveAttribute("data-layout", "split", {
+ timeout: 10_000,
+ })
+ await expect(page.getByTestId(tid.threadSplitParent).getByText(parentBody, { exact: false }))
+ .toBeVisible()
+ await expect(page.getByTestId(tid.threadSplitPanel).getByText(threadBody, { exact: false }))
+ .toBeVisible()
+ })
+})
+
+test("a true-cold channel load reuses localized skeletons without a custom bootstrap", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const suffix = Date.now().toString(36)
+ const serverId = await seedServer("alice", `Cold control ${suffix}`)
+ const channelId = await seedChannel("alice", serverId, `cold-${suffix}`)
+ const body = `network channel ${suffix}`
+ await seedMessage("alice", channelId, body)
+ const { page } = await asUser("alice")
+ await page.goto("/")
+ await clearQueryPersistence(page)
+ // Clearing IndexedDB does not cancel the current page's already queued
+ // throttled persist. Let that write drain, then clear once more so the next
+ // document really starts without a disk snapshot.
+ await page.waitForTimeout(1_100)
+ await clearQueryPersistence(page)
+ await page.addInitScript((loadingSelectors) => {
+ const state = {
+ customBootstrapSeen: false,
+ localizedSkeletonAfterRestore: false,
+ sessionFrameSeen: false,
+ }
+ Object.defineProperty(window, "__cacheFirstColdControl", {
+ configurable: true,
+ value: state,
+ })
+ const inspect = () => {
+ if (document.querySelector('[data-slot="community-restore-bootstrap"]')) {
+ state.customBootstrapSeen = true
+ }
+ if (document.querySelector('[aria-label="Loading community"]')) {
+ state.sessionFrameSeen = true
+ }
+ if (
+ performance.getEntriesByName("alook:restore:complete", "mark").length > 0
+ && document.querySelector(loadingSelectors.join(","))
+ ) state.localizedSkeletonAfterRestore = true
+ }
+ new MutationObserver(inspect).observe(document, { childList: true, subtree: true })
+ // Restore lifecycle marks do not mutate the DOM. Observe marks as well so
+ // a skeleton that is already mounted when `restore:complete` lands is not
+ // missed merely because no later DOM mutation happens in a fast CI run.
+ new PerformanceObserver(inspect).observe({ type: "mark", buffered: true })
+ inspect()
+ }, structuralLoadingSelectors)
+
+ let releaseReads!: () => void
+ const readsGate = new Promise<void>((resolve) => { releaseReads = resolve })
+ let heldReads = 0
+ await page.route("**/api/community/**", async (route) => {
+ if (route.request().method() !== "GET") {
+ await route.continue()
+ return
+ }
+ heldReads += 1
+ await readsGate
+ await route.continue().catch(() => {})
+ })
+
+ try {
+ await page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
+ await expect.poll(() => page.evaluate(() => {
+ return (window as unknown as {
+ __cacheFirstColdControl?: {
+ customBootstrapSeen: boolean
+ localizedSkeletonAfterRestore: boolean
+ sessionFrameSeen: boolean
+ }
+ }).__cacheFirstColdControl
+ })).toMatchObject({
+ customBootstrapSeen: false,
+ localizedSkeletonAfterRestore: true,
+ sessionFrameSeen: true,
+ })
+ await expect.poll(() => heldReads).toBeGreaterThan(0)
+ expect(await page.evaluate(() => (
+ performance.getEntriesByName("alook:restore:first-cached-paint", "mark").length
+ ))).toBe(0)
+ } finally {
+ releaseReads()
+ await page.unroute("**/api/community/**")
+ }
+ await expect(page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })
+})
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 648dd19e1..9ceefef0e 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
@@ -1,7 +1,7 @@
// Shared schema between the Playwright perf spec (producer) and the report
// generator (consumer). All timestamps are the BROWSER monotonic clock
// (performance.now()) so network, marks, renders, and layout shifts correlate
-// without cross-clock skew. See plans/community-switch-perf-diagnosis.md.
+// without cross-clock skew.
export type CacheState = "cold" | "memory-warm" | "disk-warm"
export type SwitchKind = "server" | "channel"
@@ -56,10 +56,20 @@ export interface CapturedSwitch {
degraded: boolean
}
+export interface CapturedWarmReload {
+ restoreStartTs: number
+ restoreCompleteTs: number
+ firstCachedPaintTs: number
+ stableTs: number
+ customBootstrapSeen: boolean
+ skeletonSeen: boolean
+}
+
export interface CaptureFile {
owner: { email: string; userId: string }
createdAt: string
switches: CapturedSwitch[]
+ warmReload?: CapturedWarmReload
}
// In-page globals installed by the perf spec's PerformanceObserver setup.
@@ -74,5 +84,6 @@ declare global {
__PERF_WAIT_FOR_STABLE_RESIZE__?: () => Promise<void>
__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 f6d5f7309..b3e8c1001 100644
--- a/src/web/src/test/e2e-ui/perf/switch.perf.ts
+++ b/src/web/src/test/e2e-ui/perf/switch.perf.ts
@@ -19,7 +19,7 @@
* - The capture is flushed to switch-events.json after every switch. The
* runner clears old artifacts first and only reports a successful run.
*
- * See plans/community-switch-perf-diagnosis.md. LOCAL-ONLY — runs via
+ * LOCAL-ONLY — runs via
* playwright.perf.config.ts, which has NO global-setup, so the stress-seeded
* DB is preserved and this spec drives as the STABLE seed identity recorded in
* the manifest.
@@ -37,6 +37,7 @@ import { tid } from "../_fixtures/testids"
import type {
CacheState,
CaptureFile,
+ CapturedWarmReload,
CapturedSwitch,
SwitchKind,
} from "./perf-capture-types"
@@ -266,6 +267,7 @@ test("community switch perceived-latency capture", async ({ browser }) => {
await page.waitForSelector("[data-msg-id]", { timeout: 20_000 }).catch(() => {})
const captured: CapturedSwitch[] = []
+ const warmReloadCapture: { current?: CapturedWarmReload } = {}
const startedAt = new Date().toISOString()
async function measureSwitch(
@@ -336,6 +338,7 @@ test("community switch perceived-latency capture", async ({ browser }) => {
owner: manifest.owner,
createdAt: startedAt,
switches: captured,
+ ...(warmReloadCapture.current ? { warmReload: warmReloadCapture.current } : {}),
}
mkdirSync(ARTIFACTS_DIR, { recursive: true })
writeFileSync(CAPTURE_OUT, JSON.stringify(out, null, 2))
@@ -440,8 +443,55 @@ test("community switch perceived-latency capture", async ({ browser }) => {
}
})
), { key: persistedKey, channelId: persistedChannelId })).toBe(true)
+ await page.addInitScript(() => {
+ window.__PERF_WARM_RELOAD__ = { customBootstrapSeen: false, skeletonSeen: false }
+ const inspect = () => {
+ const capture = window.__PERF_WARM_RELOAD__
+ if (!capture) return
+ if (document.querySelector('[data-slot="community-restore-bootstrap"]')) {
+ capture.customBootstrapSeen = true
+ }
+ if (
+ document.querySelector('[aria-label="Loading community"]')
+ || document.querySelector('[data-slot="skeleton"]')
+ ) capture.skeletonSeen = true
+ }
+ new MutationObserver(inspect).observe(document, { childList: true, subtree: true })
+ inspect()
+ })
await page.reload({ waitUntil: "commit" })
await page.waitForSelector("[data-msg-id]", { timeout: 20_000 }).catch(() => {})
+ warmReloadCapture.current = await page.evaluate(() => {
+ const latestMark = (name: string) => {
+ const marks = performance.getEntriesByName(name, "mark")
+ return marks.at(-1)?.startTime ?? null
+ }
+ const restoreStartTs = latestMark("alook:restore:start")
+ const restoreCompleteTs = latestMark("alook:restore:complete")
+ const firstCachedPaintTs = latestMark("alook:restore:first-cached-paint")
+ const stableTs = latestMark("alook:restore:stable")
+ if (
+ restoreStartTs == null
+ || restoreCompleteTs == null
+ || firstCachedPaintTs == null
+ || stableTs == null
+ ) throw new Error("warm reload restore lifecycle marks are incomplete")
+ return {
+ restoreStartTs,
+ restoreCompleteTs,
+ firstCachedPaintTs,
+ stableTs,
+ customBootstrapSeen: window.__PERF_WARM_RELOAD__?.customBootstrapSeen === true,
+ skeletonSeen: window.__PERF_WARM_RELOAD__?.skeletonSeen === true,
+ }
+ })
+ const warmReload = warmReloadCapture.current
+ expect(warmReload.customBootstrapSeen, "warm reload omitted the custom restore bootstrap").toBe(false)
+ expect(warmReload.skeletonSeen, "warm reload reused the route-owned regional skeleton").toBe(true)
+ expect(warmReload.restoreCompleteTs).toBeGreaterThanOrEqual(warmReload.restoreStartTs)
+ expect(warmReload.firstCachedPaintTs).toBeGreaterThanOrEqual(warmReload.restoreCompleteTs)
+ expect(warmReload.stableTs).toBeGreaterThanOrEqual(warmReload.firstCachedPaintTs)
+ flushCapture()
{
const ch = channels[1]
await measureSwitch("channel", ch.id, "disk-warm", async () => {
diff --git a/src/web/src/test/e2e/community-bot-owner-fk.test.ts b/src/web/src/test/e2e/community-bot-owner-fk.test.ts
index 36301200a..f154c2bee 100644
--- a/src/web/src/test/e2e/community-bot-owner-fk.test.ts
+++ b/src/web/src/test/e2e/community-bot-owner-fk.test.ts
@@ -2,7 +2,7 @@ import { describe, it, expect, afterAll } from "vitest"
import { sql, sqlRun, sqlQuery } from "@alook/test-utils"
/**
- * Real-DB verification for `plans/community-account-debt-fixes.md` Fix 1.
+ * Real-DB verification that deleting an owner cannot orphan a bot row.
*
* `src/web/migrations/0050_community_bots.sql` added `ownerUserId TEXT
* REFERENCES user(id)` with no explicit `ON DELETE` clause (defaults to
diff --git a/src/web/src/test/e2e/community-friendship-status-check.test.ts b/src/web/src/test/e2e/community-friendship-status-check.test.ts
index 71b472a45..af6eb8d9b 100644
--- a/src/web/src/test/e2e/community-friendship-status-check.test.ts
+++ b/src/web/src/test/e2e/community-friendship-status-check.test.ts
@@ -3,8 +3,7 @@ import { sql, sqlRun, sqlQuery } from "@alook/test-utils"
/**
* Real-DB verification that the `community_friendship.status` CHECK constraint
- * admits every status the query layer writes. See
- * plans/friend-cancel-card-cleanup.md.
+ * admits every status the query layer writes.
*
* The unit tests for `cancelPendingRequest` / `rejectRequest` mock the drizzle
* chain, so a `.set({ status: 'cancelled' })` "succeeds" without touching the
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index e030d8a96..268bdde0a 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -21,6 +21,9 @@ enabled = true
head_sampling_rate = 0.05
destinations = ["grafana-traces"]
+[version_metadata]
+binding = "CF_VERSION_METADATA"
+
# OpenNext required bindings
[assets]
directory = ".open-next/assets"
@@ -85,8 +88,8 @@ binding = "TASK_QUEUE"
queue = "alook-queue"
# Dev-only direct path to the `alook-queue-worker` HTTP dev endpoint — local
-# Cloudflare Queues can't bridge separate `wrangler dev`/`next dev` processes
-# (see plans/minimal-wake-queue-unread-notice.md), so `queue-transport.ts` uses
+# Cloudflare Queues can't bridge separate `wrangler dev`/`next dev` processes,
+# so `queue-transport.ts` uses
# this binding (with an HTTP fallback, like `WS_DO_WORKER`) instead of
# `TASK_QUEUE` when `NODE_ENV === "development"`. Unused in production.
[[services]]
diff --git a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
index a765ee356..4ca35050b 100644
--- a/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
+++ b/src/ws-do/src/ws-durable/machine-lifecycle.test.ts
@@ -58,7 +58,6 @@ describe("WebSocketDurableObject", () => {
describe("community-machine — webSocketClose presence lifecycle", () => {
// These tests cover the "graceful daemon quit → immediate offline" fix.
- // See plans/community-machine-presence-fix.md § Server transitions.
it("flips status=offline via credential-scoped markMachineOffline and broadcasts on real transition", async () => {
const { durable, store, ctx } = createDO()
store.set("community-machine-identity", {
diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.ts
index 8b820599b..cb9fd9828 100644
--- a/src/ws-do/src/ws-durable/presence-typing.test.ts
+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts
@@ -238,9 +238,8 @@ describe("WebSocketDurableObject", () => {
describe("fetch — /check-user-online (bot-aware, keyed by ?userId=)", () => {
// This DO instance is keyed by `user:<id>` (idFromName) but can't read
- // its own name back off `ctx` on this worker's pinned compatibility_date
- // — see plans/community-account-debt-fixes.md Fix 3 — so every caller
- // passes `?userId=` explicitly and the handler branches on it.
+ // its own name back off `ctx` on this worker's pinned compatibility_date,
+ // so every caller passes `?userId=` explicitly and the handler branches on it.
it("answers via isBotOnline for a bot id, bypassing the live-socket check entirely", async () => {
const { durable, ctx } = createDO()
mockGetUserInternal.mockResolvedValue({ isBot: true } as any)
diff --git a/src/ws-do/src/ws-durable/test-harness.ts b/src/ws-do/src/ws-durable/test-harness.ts
index a9867dbe6..e5f5139e4 100644
--- a/src/ws-do/src/ws-durable/test-harness.ts
+++ b/src/ws-do/src/ws-durable/test-harness.ts
@@ -148,8 +148,7 @@ export const mockD1Batch = vi.fn(async (statements: unknown[]) =>
statements.map(() => ({ success: true, meta: { changes: 1 } })))
export const mockGetUserInternal = vi.fn<(db: unknown, id: string) => Promise<{ isBot: boolean; ownerUserId: string | null } | null>>().mockResolvedValue(null)
// mockToSummary now returns row.status verbatim — status is the source of
-// truth on the column, not a derivation from lastSeenAt. See
-// plans/community-machine-presence-fix.md.
+// truth on the column, not a derivation from lastSeenAt.
export const mockToSummary = vi.fn((row: any) => ({
id: row.id,
hostname: row.hostname ?? "",
diff --git a/src/ws-do/wrangler.toml b/src/ws-do/wrangler.toml
index 2dc1c6c53..345ef2361 100644
--- a/src/ws-do/wrangler.toml
+++ b/src/ws-do/wrangler.toml
@@ -13,7 +13,7 @@ head_sampling_rate = 0.1
# head-sampling is a request-level decision that can't be bypassed by log
# level. Full-rate ingest is affordable here — ws-do's log volume is
# dominated by daemon frames — and is the only reliable way to measure the
-# audit-loss SLO. See plans/d1-critical-path-resilience-v2.md §Observability.
+# audit-loss SLO.
[observability.logs]
invocation_logs = true
head_sampling_rate = 1.0
diff --git a/tests/integration/daemon/control-plane.test.ts b/tests/integration/daemon/control-plane.test.ts
index 5e4ca7eee..51a4ba45e 100644
--- a/tests/integration/daemon/control-plane.test.ts
+++ b/tests/integration/daemon/control-plane.test.ts
@@ -239,7 +239,7 @@ describe("daemon control plane — real ws-do wake round-trip", () => {
// Bot activity is stored on the same `statusEmoji`/`statusText` fields
// humans use — the WS DO translates the daemon's `agent_activity` frame
// into the appropriate preset and writes/broadcasts it as an ordinary
- // status update (see plans/community-bot-status-telemetry.md).
+ // status update.
await channel!.reportAgentActivity({ agentId: fixture.bot.botUserId, state: "running" })
const runningProfile = await waitForAsync(async () => {
const res = await sessionRequest(`/api/community/users/${fixture.bot.botUserId}/profile`, cookie)