Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): unify current resources and reentry lifecycle (#1092)

Generad7804acaf80
diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
index 9da1646e1..857241c7e 100644
--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json
+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json
@@ -320,12 +320,18 @@
{
"key": "src/shared/src/db/queries/community/channel.ts:getServerRootChannelsByIds:inArray:1"
},
+ {
+ "key": "src/shared/src/db/queries/community/channel.ts:listChannelMembershipsForUserInChannels:inArray:1"
+ },
{
"key": "src/shared/src/db/queries/community/channel.ts:listChildChannelsByParentMessageIds:inArray:1"
},
{
"key": "src/shared/src/db/queries/community/channel.ts:listReadableChannelsForUser:inArray:1"
},
+ {
+ "key": "src/shared/src/db/queries/community/channel.ts:listReadableMessageChannelsForUser:inArray:1"
+ },
{
"key": "src/shared/src/db/queries/community/channel.ts:listServerChannelDirectoryForAdmin:inArray:1"
},
@@ -521,6 +527,9 @@
{
"key": "src/shared/src/db/queries/community/thread.ts:removeParticipantFromChildChannels:inArray:1"
},
+ {
+ "key": "src/shared/src/db/queries/community/user-profile.ts:getProfilesByUserIds:inArray:1"
+ },
{
"key": "src/shared/src/db/queries/conversation.ts:getConversationsByIds:inArray:1"
},
diff --git a/src/queue-worker/src/index.test.ts b/src/queue-worker/src/index.test.ts
index 8800e0e4d..df44ff575 100644
--- a/src/queue-worker/src/index.test.ts
+++ b/src/queue-worker/src/index.test.ts
@@ -58,10 +58,9 @@ describe("queue-worker queue consumer", () => {
})
it.each([
- ["legacy bot wake", legacyWake, botWake],
["v1 bot wake", botWake, botWake],
["v1 mobile push", mobilePush, mobilePush],
- ])("normalizes and ACKs a completed %s", async (_name, body, expected) => {
+ ])("executes and ACKs a completed %s", async (_name, body, expected) => {
const message = makeMessage(body)
await handler.queue({ messages: [message] } as never, env)
@@ -77,6 +76,7 @@ describe("queue-worker queue consumer", () => {
})
it.each([
+ ["unversioned", legacyWake, "malformed"],
["malformed", { messageId: "message-1" }, "malformed"],
["unknown", { version: 1, kind: "email", messageId: "message-1", userId: "user-1" }, "unknown_kind"],
["unsupported", { version: 2, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" }, "unsupported_version"],
@@ -131,8 +131,8 @@ describe("queue-worker development HTTP entrypoint", () => {
afterEach(() => vi.useRealTimers())
- it("accepts mixed versioned tasks and normalizes legacy wakes", async () => {
- const response = await handler.fetch!(request("POST", [legacyWake, mobilePush]), env)
+ it("accepts mixed current versioned tasks", async () => {
+ const response = await handler.fetch!(request("POST", [botWake, mobilePush]), env)
expect(response.status).toBe(202)
expect(mockExecuteQueueTask.mock.calls.map((call) => call[2])).toEqual([
@@ -143,7 +143,7 @@ describe("queue-worker development HTTP entrypoint", () => {
it("deduplicates only the same kind/message/recipient tuple", async () => {
const response = await handler.fetch!(request("POST", [
- legacyWake,
+ botWake,
botWake,
mobilePush,
{ ...mobilePush, userId: "user-2" },
@@ -155,8 +155,9 @@ describe("queue-worker development HTTP entrypoint", () => {
it.each([
["non-array", legacyWake],
- ["malformed item", [legacyWake, { messageId: "message-2" }]],
- ["unknown item", [legacyWake, { version: 1, kind: "email", messageId: "message-2", userId: "user-2" }]],
+ ["unversioned item", [botWake, legacyWake]],
+ ["malformed item", [botWake, { messageId: "message-2" }]],
+ ["unknown item", [botWake, { version: 1, kind: "email", messageId: "message-2", userId: "user-2" }]],
])("rejects a %s body before D1", async (_name, body) => {
const response = await handler.fetch!(request("POST", body), env)
expect(response.status).toBe(400)
@@ -172,7 +173,7 @@ describe("queue-worker development HTTP entrypoint", () => {
}
})
- const responsePromise = handler.fetch!(request("POST", [legacyWake, mobilePush]), env)
+ const responsePromise = handler.fetch!(request("POST", [botWake, mobilePush]), env)
await vi.runAllTimersAsync()
const response = await responsePromise
diff --git a/src/queue-worker/src/index.ts b/src/queue-worker/src/index.ts
index d99018dd7..76f14f2e3 100644
--- a/src/queue-worker/src/index.ts
+++ b/src/queue-worker/src/index.ts
@@ -68,7 +68,7 @@ export default {
* `alook-queue-worker` — Cloudflare Queue consumer for `alook-queue`
* (minimal-wake-queue-unread-notice plan §3). Owns a `DB` binding to the
* same `alook-app` database `src/web` writes to: for every minimal
- * accepted legacy or v1 `bot-wake` queue item, `dispatchOneUnreadWake`
+ * accepted v1 `bot-wake` queue item, `dispatchOneUnreadWake`
* re-reads CURRENT D1 state and only then forwards a freshly built
* `agent:wake` `HostCommand`. This is what keeps a stale queue item from
* waking an old machine, an already-caught-up bot, or a bot that lost
@@ -108,8 +108,7 @@ export default {
* 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
- * v1 queue tasks. Runs the same handler as `queue()`, including current-D1
+ * `TASK_QUEUE.sendBatch(...)`. Body is a JSON array of current v1 queue tasks. Runs the same handler as `queue()`, including current-D1
* revalidation and, for bot wakes, the real forward to `alook-ws-do`.
* There is no durable queue behind this dev path:
* candidates get bounded in-process retries and exhausted stable keys are
diff --git a/src/queue-worker/test-runtime/worker.runtime.test.ts b/src/queue-worker/test-runtime/worker.runtime.test.ts
index 2d4b20aa0..8d807bc49 100644
--- a/src/queue-worker/test-runtime/worker.runtime.test.ts
+++ b/src/queue-worker/test-runtime/worker.runtime.test.ts
@@ -2,6 +2,8 @@
import { env, exports } from "cloudflare:workers"
import { describe, expect, it } from "vitest"
+import { createDb, queries, type HostCommand } from "@alook/shared"
+import { communityMachine } from "../../shared/src/db/community-machine-schema"
type RuntimeQueueMessage<T> = {
id: string
@@ -16,7 +18,7 @@ type RuntimeQueueResult = {
retryMessages: Array<{ msgId: string; delaySeconds?: number }>
}
-const runtimeEnv = env as unknown as { DB: D1Database }
+const runtimeEnv = env as unknown as { DB: D1Database; WS_DO_WORKER: Fetcher }
const worker = (exports as unknown as {
default: {
fetch(request: Request): Promise<Response>
@@ -48,7 +50,6 @@ describe("queue-worker workerd runtime", () => {
})
it.each([
- ["legacy", (messageId: string, botUserId: string) => ({ messageId, botUserId })],
["v1", (messageId: string, botUserId: string) => ({ version: 1, kind: "bot-wake", messageId, botUserId })],
])("acks a permanent D1 miss for a %s task through the real queue entrypoint", async (_name, makeBody) => {
const id = `runtime-${crypto.randomUUID()}`
@@ -89,6 +90,8 @@ describe("queue-worker workerd runtime", () => {
const mobileId = `runtime-mobile-${crypto.randomUUID()}`
const botId = `runtime-bot-${crypto.randomUUID()}`
const poisonId = `runtime-poison-${crypto.randomUUID()}`
+ const unversionedId = `runtime-unversioned-${crypto.randomUUID()}`
+ const currentWake = { version: 1, kind: "bot-wake", messageId: `message-${crypto.randomUUID()}`, botUserId: `bot-${crypto.randomUUID()}` }
await runtimeEnv.DB.prepare(
"ALTER TABLE community_message RENAME TO community_message_unavailable",
).run()
@@ -109,12 +112,11 @@ describe("queue-worker workerd runtime", () => {
id: botId,
timestamp: new Date(),
attempts: 1,
- body: {
- version: 1,
- kind: "bot-wake",
- messageId: `message-${crypto.randomUUID()}`,
- botUserId: `bot-${crypto.randomUUID()}`,
- },
+ body: currentWake,
+ },
+ {
+ id: unversionedId, timestamp: new Date(), attempts: 1,
+ body: { messageId: currentWake.messageId, botUserId: currentWake.botUserId },
},
{
id: poisonId,
@@ -126,6 +128,8 @@ describe("queue-worker workerd runtime", () => {
expect(result.outcome).toBe("ok")
expect(result.explicitAcks).toContain(poisonId)
+ expect(result.explicitAcks).toContain(unversionedId)
+ expect(result.retryMessages.some(message => message.msgId === unversionedId)).toBe(false)
expect(result.explicitAcks).not.toContain(mobileId)
expect(result.retryMessages).toContainEqual({ msgId: mobileId, delaySeconds: 5 })
expect(result.explicitAcks).not.toContain(botId)
@@ -135,5 +139,60 @@ describe("queue-worker workerd runtime", () => {
"ALTER TABLE community_message_unavailable RENAME TO community_message",
).run()
}
+ const recovered = await worker.queue("alook-queue", [{ id: botId, timestamp: new Date(), attempts: 2, body: currentWake }])
+ expect(recovered.explicitAcks).toContain(botId)
+ expect(recovered.retryMessages).toEqual([])
+ })
+
+ it("executes current tasks from real D1 and recovers only the failed sibling with a stable wake identity", async () => {
+ const db = createDb(runtimeEnv.DB)
+ const owner = await queries.user.createUser(db, { name: "QueueOwner", email: `${crypto.randomUUID()}@runtime.test` })
+ const machineId = `cm_${crypto.randomUUID()}`
+ await db.insert(communityMachine).values({ id: machineId, userId: owner.id, displayName: "Runtime machine", status: "online" })
+ const bot = await queries.communityBot.createBot(db, { ownerId: owner.id, name: "QueueBot", machineId, runtime: "codex" })
+ const dm = await queries.communityDm.createOrGetDM(db, { userId1: owner.id, userId2: bot.botId })
+ const first = await queries.communityMessage.createMessage(db, { channelId: dm.id, authorId: owner.id, authorKind: "human", content: "First current task" })
+ const second = await queries.communityMessage.createMessage(db, { channelId: dm.id, authorId: owner.id, authorKind: "human", content: "Second current task" })
+ const firstTask = { version: 1, kind: "bot-wake", messageId: first.id, botUserId: bot.botId }
+ const secondTask = { ...firstTask, messageId: second.id }
+ const ids = { old: crypto.randomUUID(), first: crypto.randomUUID(), second: crypto.randomUUID(), missing: crypto.randomUUID() }
+ await runtimeEnv.WS_DO_WORKER.fetch("http://internal/test/fail-once", {
+ method: "POST", body: JSON.stringify({ agentId: bot.botId, seq: second.seq }),
+ })
+ const result = await worker.queue("alook-queue", [
+ { id: ids.old, timestamp: new Date(), attempts: 1, body: { messageId: first.id, botUserId: bot.botId } },
+ { id: ids.first, timestamp: new Date(), attempts: 1, body: firstTask },
+ { id: ids.second, timestamp: new Date(), attempts: 1, body: secondTask },
+ { id: ids.missing, timestamp: new Date(), attempts: 1, body: { ...firstTask, messageId: `missing-${crypto.randomUUID()}` } },
+ ])
+ expect(result.explicitAcks.sort()).toEqual([ids.old, ids.first, ids.missing].sort())
+ expect(result.retryMessages).toEqual([{ msgId: ids.second, delaySeconds: 5 }])
+
+ type WakeReceipt = { path: string; command: Extract<HostCommand, { type: "agent:wake" }> }
+ const readWakes = async () => {
+ const receipts = await (await runtimeEnv.WS_DO_WORKER.fetch("http://internal/test/wakes")).json() as WakeReceipt[]
+ return receipts.filter(receipt => receipt.command.agentId === bot.botId)
+ }
+ const beforeRetry = await readWakes()
+ expect(beforeRetry).toHaveLength(2)
+ expect(beforeRetry.map(receipt => receipt.command.unreadNotice.latestSeq).sort()).toEqual([first.seq, second.seq])
+ for (const receipt of beforeRetry) {
+ expect(receipt.path).toBe(`/community-machine/by-id/${machineId}/forward-agent-wake`)
+ expect(receipt.command.type).toBe("agent:wake")
+ expect(receipt.command.config).toMatchObject({ runtime: "codex" })
+ expect(receipt.command.unreadNotice).toEqual({ kind: "unread_notice", channel: `/.dm/${owner.name}#${owner.discriminator}`, channelId: dm.id, latestSeq: receipt.command.unreadNotice.latestSeq })
+ }
+ const failedWake = beforeRetry.find(receipt => receipt.command.unreadNotice.latestSeq === second.seq)!
+ const recovered = await worker.queue("alook-queue", [{ id: ids.second, timestamp: new Date(), attempts: 2, body: secondTask }])
+ expect(recovered.explicitAcks).toEqual([ids.second])
+ expect(recovered.retryMessages).toEqual([])
+ const afterRetry = await readWakes()
+ expect(afterRetry).toHaveLength(3)
+ expect(afterRetry.filter(receipt => receipt.command.unreadNotice.latestSeq === first.seq)).toHaveLength(1)
+ expect(afterRetry.at(-1)?.command).toEqual(failedWake.command)
+ const audits = await queries.communityBotAuditLog.listOwnedBotActivityEvents(db, { botId: bot.botId, ownerUserId: owner.id })
+ expect(audits).toHaveLength(3)
+ expect(audits?.every(audit => audit.kind === "wake_trigger")).toBe(true)
+ expect(audits?.map(audit => JSON.parse(audit.payload).messageId).sort()).toEqual([first.id, second.id, second.id].sort())
})
})
diff --git a/src/queue-worker/vitest.runtime.config.mts b/src/queue-worker/vitest.runtime.config.mts
index 5aebb6414..434d5707a 100644
--- a/src/queue-worker/vitest.runtime.config.mts
+++ b/src/queue-worker/vitest.runtime.config.mts
@@ -3,6 +3,27 @@ import { cloudflareTest, readD1Migrations } from "@cloudflare/vitest-plugin"
import { defineProject } from "vitest/config"
const migrations = await readD1Migrations(path.resolve(import.meta.dirname, "../web/migrations"))
+const wakeRequests: Array<{ path: string; command: unknown }> = []
+let failOnce: { agentId: string; seq: number } | undefined
+
+async function wsReceiptStub(request: Request): Promise<Response> {
+ const url = new URL(request.url)
+ if (url.pathname === "/test/fail-once") {
+ failOnce = await request.json() as { agentId: string; seq: number }
+ return Response.json({ ok: true })
+ }
+ if (url.pathname === "/test/wakes") return Response.json(wakeRequests)
+ if (url.pathname.endsWith("/forward-agent-wake")) {
+ const command = await request.json() as { agentId: string; unreadNotice: { latestSeq: number } }
+ wakeRequests.push({ path: url.pathname, command })
+ if (command.agentId === failOnce?.agentId && command.unreadNotice.latestSeq === failOnce.seq) {
+ failOnce = undefined
+ return Response.json({ error: "controlled downstream fault" }, { status: 503 })
+ }
+ return Response.json({ attempted: 1 })
+ }
+ return Response.json({ sent: 1 })
+}
export default defineProject({
plugins: [
@@ -12,7 +33,7 @@ export default defineProject({
bindings: { TEST_MIGRATIONS: migrations },
compatibilityFlags: ["nodejs_compat", "service_binding_extra_handlers"],
serviceBindings: {
- WS_DO_WORKER: () => Response.json({ delivered: 0 }),
+ WS_DO_WORKER: wsReceiptStub,
},
},
}),
diff --git a/src/shared/package.json b/src/shared/package.json
index e133b93c0..1a749e50c 100644
--- a/src/shared/package.json
+++ b/src/shared/package.json
@@ -6,6 +6,7 @@
"exports": {
".": "./src/index.ts",
"./crypto": "./src/utils/crypto.ts",
+ "./business-schema-version": "./src/business-schema-version.ts",
"./browser": "./src/browser/index.ts",
"./community-cli-contract": "./src/community-cli-contract.ts",
"./constants/community": "./src/constants/community.ts",
diff --git a/src/shared/src/business-schema-version.ts b/src/shared/src/business-schema-version.ts
new file mode 100644
index 000000000..7ffa91b5c
--- /dev/null
+++ b/src/shared/src/business-schema-version.ts
@@ -0,0 +1 @@
+export const BUSINESS_SCHEMA_VERSION = 7 as const
diff --git a/src/shared/src/community-attention.test.ts b/src/shared/src/community-attention.test.ts
index a7f2df718..7b9371683 100644
--- a/src/shared/src/community-attention.test.ts
+++ b/src/shared/src/community-attention.test.ts
@@ -58,6 +58,22 @@ const included = {
}],
}
+const fullChannel = { id: "c1", type: "text" as const, serverId: "s1", categoryId: null, name: "general", topic: "", parentChannelId: null, parentMessageId: null, creatorId: "u1", position: 0, archived: false, createdAt: "2026-09-27T00:00:00.000Z", lastMessageAt: null, messageCount: 0 }
+const fullMessage = { id: "m7", channelId: "c1", seq: 7, authorId: "u2", type: "chat" as const, createdAt: "2026-09-27T00:00:00.000Z", content: "hello", replyToId: null, clientNonce: null, attachments: [] }
+const currentChannels = [
+ { ...fullChannel, id: "c1", serverId: "s1", name: "general" },
+ { ...fullChannel, id: "forum", serverId: "s1", name: "Ideas", type: "forum" as const },
+ { ...fullChannel, id: "post", serverId: "s1", name: "Launch", type: "thread" as const, parentChannelId: "forum", parentMessageId: "opener" },
+ { ...fullChannel, id: "dm", serverId: null, name: null, type: "dm" as const },
+]
+const currentResources = {
+ viewerId: "u1", servers: [{ id: "s1", name: "One", discriminator: "0001", description: "", ownerId: "u1", position: 0, icon: null, official: false, isOwner: true }],
+ serverMemberships: [{ serverId: "s1", userId: "u1", memberId: "member-u1", role: "owner" }],
+ channels: currentChannels, memberships: currentChannels.map(channel => ({ channelId: channel.id, userId: "u1", relation: "access" as const, source: "explicit" as const })),
+ profiles: [{ id: "u2", name: "Alice", discriminator: "0002", avatar: "", avatarVersion: 1 }, { id: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 1 }],
+ messages: [{ ...fullMessage, id: "m7", channelId: "c1", authorId: "u2", seq: 7, content: "hello" }, { ...fullMessage, id: "opener", channelId: "forum", authorId: "u2", seq: 7, content: "Launch" }],
+}
+
function childThreadSnapshot() {
return {
scopes: [{
@@ -168,55 +184,55 @@ describe("account attention wire schemas", () => {
})
it("accepts self-contained snapshots and the existing reply kind", () => {
- expect(AccountAttentionSnapshotSchema.parse({
+ expect(AccountAttentionSnapshotSchema.parse({ resources: currentResources, ...({
scopes: [scope],
items: [item, { ...item, id: "mention:a2", sourceId: "a2", kind: "reply" }],
limit: 100,
truncated: false,
included,
- }).items).toHaveLength(2)
+ }) }).items).toHaveLength(2)
})
it("rejects display identity and message content inside fact rows", () => {
- expect(AccountAttentionSnapshotSchema.safeParse({
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [{ ...scope, channelName: "general" }],
items: [{ ...item, actorName: "Alice", content: "hello" }],
limit: 100,
truncated: false,
included,
- }).success).toBe(false)
+ }) }).success).toBe(false)
})
it("rejects duplicate ids and dangling scope references", () => {
- expect(AccountAttentionSnapshotSchema.safeParse({
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [scope, scope],
items: [item, item],
limit: 100,
truncated: false,
included,
- }).success).toBe(false)
- expect(AccountAttentionSnapshotSchema.safeParse({
+ }) }).success).toBe(false)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [],
items: [item],
limit: 100,
truncated: false,
included,
- }).success).toBe(false)
+ }) }).success).toBe(false)
})
it("rejects a scope whose canonical owner graph is incomplete", () => {
- expect(AccountAttentionSnapshotSchema.safeParse({
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [scope],
items: [item],
limit: 100,
truncated: false,
included: { ...included, servers: [] },
- }).success).toBe(false)
+ }) }).success).toBe(false)
})
it("validates every child-thread parent and opener edge", () => {
const valid = childThreadSnapshot()
- expect(AccountAttentionSnapshotSchema.safeParse(valid).success).toBe(true)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...(valid) }).success).toBe(true)
const broken = [
(candidate: ReturnType<typeof childThreadSnapshot>) => {
@@ -244,29 +260,29 @@ describe("account attention wire schemas", () => {
for (const mutate of broken) {
const candidate = structuredClone(valid)
mutate(candidate)
- expect(AccountAttentionSnapshotSchema.safeParse(candidate).success).toBe(false)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...(candidate) }).success).toBe(false)
}
const topLevelMismatch = childThreadSnapshot()
Object.assign(topLevelMismatch.scopes[0]!, { parentChannelId: null })
- expect(AccountAttentionSnapshotSchema.safeParse(topLevelMismatch).success).toBe(false)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...(topLevelMismatch) }).success).toBe(false)
})
it("requires a DM scope to carry both its DM and profile owners", () => {
const valid = dmSnapshot()
- expect(AccountAttentionSnapshotSchema.safeParse(valid).success).toBe(true)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...(valid) }).success).toBe(true)
const missingDm = dmSnapshot()
missingDm.included.dms = []
- expect(AccountAttentionSnapshotSchema.safeParse(missingDm).success).toBe(false)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...(missingDm) }).success).toBe(false)
const missingProfile = dmSnapshot()
missingProfile.included.profiles = []
- expect(AccountAttentionSnapshotSchema.safeParse(missingProfile).success).toBe(false)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...(missingProfile) }).success).toBe(false)
})
it("rejects friend and message items without their canonical owners", () => {
- expect(AccountAttentionSnapshotSchema.safeParse({
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [],
items: [{
id: "friend_request:f1",
@@ -280,17 +296,17 @@ describe("account attention wire schemas", () => {
limit: 100,
truncated: false,
included: { ...included, profiles: [] },
- }).success).toBe(false)
+ }) }).success).toBe(false)
- expect(AccountAttentionSnapshotSchema.safeParse({
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [scope],
items: [{ ...item, scopeId: null }],
limit: 100,
truncated: false,
included,
- }).success).toBe(false)
+ }) }).success).toBe(false)
- expect(AccountAttentionSnapshotSchema.safeParse({
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [scope],
items: [item],
limit: 100,
@@ -299,7 +315,7 @@ describe("account attention wire schemas", () => {
...included,
messages: [{ ...included.messages[0], channelId: "other" }],
},
- }).success).toBe(false)
+ }) }).success).toBe(false)
})
it("requires exact forum-post parent, child, opener, and read-target refs", () => {
@@ -341,26 +357,30 @@ describe("account attention wire schemas", () => {
createdAt: "2026-09-27T00:00:00.000Z",
}
- expect(AccountAttentionSnapshotSchema.safeParse({
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [forumScope],
items: [forumPost],
limit: 100,
truncated: false,
included: forumIncluded,
- }).success).toBe(true)
- expect(AccountAttentionSnapshotSchema.safeParse({
+ }) }).success).toBe(true)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [forumScope],
items: [{ ...forumPost, readTarget: { channelId: "forum", seq: 6 } }],
limit: 100,
truncated: false,
included: forumIncluded,
- }).success).toBe(false)
- expect(AccountAttentionSnapshotSchema.safeParse({
+ }) }).success).toBe(false)
+ expect(AccountAttentionSnapshotSchema.safeParse({ resources: currentResources, ...({
scopes: [forumScope],
items: [{ ...forumPost, readTarget: { channelId: "wrong", seq: 7 } }],
limit: 100,
truncated: false,
included: forumIncluded,
- }).success).toBe(false)
+ }) }).success).toBe(false)
})
})
+
+it("requires a resource bundle on the HTTP snapshot even for an empty projection", () => {
+ expect(AccountAttentionSnapshotSchema.safeParse({ scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }).success).toBe(false)
+})
diff --git a/src/shared/src/community-attention.ts b/src/shared/src/community-attention.ts
index 240d48ee5..3e47d20bc 100644
--- a/src/shared/src/community-attention.ts
+++ b/src/shared/src/community-attention.ts
@@ -1,5 +1,5 @@
import { z } from "zod"
-import { CommunityChannelResourceSchema, CommunityMessagePreviewSchema, CommunityResourceProfileSchema } from "./community-resources"
+import { CommunityResourceBundleSchema, CommunityServerResourceSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityResourceProfileSchema } from "./community-resources"
const id = z.string().min(1)
@@ -63,11 +63,7 @@ export const AttentionItemSchema = z.strictObject({
}
})
-export const AttentionIncludedServerSchema = z.strictObject({
- id,
- name: z.string(),
- discriminator: z.string(),
-})
+export const AttentionIncludedServerSchema = CommunityServerResourceSchema.pick({ id: true, name: true, discriminator: true })
export const AttentionIncludedChannelSchema = CommunityChannelResourceSchema.pick({
id: true, serverId: true, name: true, type: true, parentChannelId: true, parentMessageId: true,
@@ -83,10 +79,7 @@ export const AttentionIncludedChannelSchema = CommunityChannelResourceSchema.pic
export const AttentionIncludedDmSchema = z.strictObject({
id,
userId: id,
- name: z.string(),
- discriminator: z.string(),
- avatar: z.string(),
- avatarVersion: z.number().int().nonnegative(),
+ ...CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true }).shape,
lastMessageAt: z.string(),
lastUnreadSeq: z.number().int().nonnegative(),
})
@@ -94,14 +87,13 @@ export const AttentionIncludedDmSchema = z.strictObject({
export const AttentionIncludedProfileSchema = z.strictObject({
userId: CommunityResourceProfileSchema.shape.id,
...CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true }).shape,
- // The existing unversioned Attention wire uses strings for absent identity.
- discriminator: z.string(),
- avatar: z.string(),
+ discriminator: CommunityResourceProfileSchema.shape.discriminator,
+ avatar: CommunityResourceProfileSchema.shape.avatar,
})
-export const AttentionIncludedMessageSchema = CommunityMessagePreviewSchema.pick({
+export const AttentionIncludedMessageSchema = CommunityMessageResourceSchema.pick({
id: true, channelId: true, type: true, authorId: true, authorName: true, seq: true, createdAt: true, content: true,
-}).required({ channelId: true, seq: true, createdAt: true, content: true })
+}).partial({ authorId: true })
export const AttentionIncludedSchema = z.strictObject({
servers: z.array(AttentionIncludedServerSchema),
@@ -111,13 +103,24 @@ export const AttentionIncludedSchema = z.strictObject({
messages: z.array(AttentionIncludedMessageSchema),
})
-export const AccountAttentionSnapshotSchema = z.strictObject({
+export const AccountAttentionProjectionSchema = z.strictObject({
scopes: z.array(AttentionScopeSchema),
items: z.array(AttentionItemSchema),
limit: z.number().int().positive(),
truncated: z.boolean(),
included: AttentionIncludedSchema,
+})
+
+export const AccountAttentionSnapshotSchema = AccountAttentionProjectionSchema.extend({
+ resources: CommunityResourceBundleSchema,
}).superRefine((snapshot, ctx) => {
+ const resources = snapshot.resources
+ if (snapshot.included.servers.some(summary => !resources.servers.some(row => row.id === summary.id))
+ || [...snapshot.included.channels, ...snapshot.included.dms].some(summary => !resources.channels.some(row => row.id === summary.id))
+ || snapshot.included.profiles.some(summary => !resources.profiles.some(row => row.id === summary.userId))
+ || snapshot.included.messages.some(summary => !resources.messages.some(row => row.id === summary.id && row.channelId === summary.channelId))
+ || resources.memberships.some(row => row.userId !== resources.viewerId || row.relation !== "access" || !resources.channels.some(channel => channel.id === row.channelId))
+ || resources.serverMemberships.some(row => row.userId !== resources.viewerId || !resources.servers.some(server => server.id === row.serverId))) ctx.addIssue({ code: "custom", message: "Attention resource closure mismatch" })
const scopeIds = new Set<string>()
for (const scope of snapshot.scopes) {
if (scopeIds.has(scope.scopeId)) {
@@ -227,4 +230,5 @@ export const AccountAttentionSnapshotSchema = z.strictObject({
export type AttentionScope = z.infer<typeof AttentionScopeSchema>
export type AttentionItem = z.infer<typeof AttentionItemSchema>
+export type AccountAttentionProjection = z.infer<typeof AccountAttentionProjectionSchema>
export type AccountAttentionSnapshot = z.infer<typeof AccountAttentionSnapshotSchema>
diff --git a/src/shared/src/community-bot-creation.ts b/src/shared/src/community-bot-creation.ts
index 903a3285f..3f3fb99b9 100644
--- a/src/shared/src/community-bot-creation.ts
+++ b/src/shared/src/community-bot-creation.ts
@@ -1,4 +1,5 @@
import { z } from "zod"
+import { CommunityResourceProfileSchema } from "./community-profile-resource"
import { resolveReasoningEffort } from "./community/bot-reasoning-effort"
import { requiresExplicitModel } from "./community/bot-model"
import type { CommunityMachineRuntime } from "./schemas"
@@ -18,13 +19,9 @@ export const BotCreationSubmitSchema = z.strictObject({
bots: z.array(BotCreationProposalSchema).min(1).max(BOT_CREATION_MAX_ITEMS),
})
-export const BotCreationIdentitySchema = z.strictObject({
- id: z.string(),
- name: z.string(),
- discriminator: z.string(),
- image: z.string().nullable(),
- avatarVersion: z.number().int().nonnegative(),
-})
+export const BotCreationIdentitySchema = CommunityResourceProfileSchema.pick({
+ id: true, name: true, discriminator: true, avatarVersion: true,
+}).extend({ image: CommunityResourceProfileSchema.shape.avatar })
export const BotCreationItemSchema = BotCreationProposalSchema.extend({
itemId: z.string(),
diff --git a/src/shared/src/community-cache.ts b/src/shared/src/community-cache.ts
new file mode 100644
index 000000000..5b0687dd3
--- /dev/null
+++ b/src/shared/src/community-cache.ts
@@ -0,0 +1,115 @@
+import { z } from "zod"
+import { serverRailEntrySchema } from "./community-server-rail"
+import { AttentionScopeSchema, AttentionItemSchema } from "./community-attention"
+import { CommunityServerMembershipResourceSchema, CommunityServerResourceSchema, CommunityCategoryResourceSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityReadStateResourceSchema, CommunityChannelMembershipResourceSchema, CommunityResourceProfileSchema } from "./community-resources"
+
+const nullableString = z.string().nullable()
+const optionalNullableString = nullableString.optional()
+
+export const serverSchema = CommunityServerResourceSchema
+export const categorySchema = CommunityCategoryResourceSchema.extend({ pending: z.boolean() })
+
+export const channelLocalSchema = z.strictObject({
+ muted: z.boolean(),
+ tags: z.array(z.string()),
+ pending: z.boolean(),
+ openerSeq: z.number().int().nonnegative().optional(),
+ openerUnread: z.boolean().optional(),
+ preview: z.string().optional(),
+ firstMessageId: z.string().min(1).nullable().optional(),
+ participantCount: z.number().int().nonnegative().optional(),
+})
+
+export const channelSchema = CommunityChannelResourceSchema.extend(channelLocalSchema.shape)
+
+export const serverMembershipSchema = CommunityServerMembershipResourceSchema.extend({
+ id: z.string().min(1), nickname: optionalNullableString, joinedAt: z.string().optional(), viewer: z.boolean(),
+})
+
+export const channelMembershipSchema = CommunityChannelMembershipResourceSchema.extend({ id: z.string().min(1) })
+
+export const profileSchema = CommunityResourceProfileSchema
+export const messageSchema = CommunityMessageResourceSchema
+
+export const readStateSchema = CommunityReadStateResourceSchema.extend({ observedRevision: z.number().int().nonnegative().optional() })
+
+export const friendshipSchema = z.strictObject({
+ id: z.string().min(1),
+ userId: z.string().min(1),
+ kind: z.enum(["accepted", "incoming", "outgoing", "blocked"]),
+ sub: z.string().optional(),
+ needsOwnerApproval: optionalNullableString,
+})
+
+export const readStateClockSchema = z.strictObject({
+ id: z.literal("account"),
+ revision: z.number().int().nonnegative(),
+})
+
+export const folderSchema = z.strictObject({
+ id: z.string().min(1),
+ name: z.string(),
+})
+
+export const serverRailSchema = z.strictObject({
+ id: z.literal("account"),
+ entries: z.array(serverRailEntrySchema),
+})
+
+export const folderItemSchema = z.strictObject({
+ id: z.string().min(1),
+ folderId: z.string().min(1),
+ serverId: z.string().min(1),
+ position: z.number(),
+})
+
+export const notificationSettingSchema = z.strictObject({
+ 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,
+ friendships: friendshipSchema,
+ readStates: readStateSchema,
+ readStateClock: readStateClockSchema,
+ attentionScopes: AttentionScopeSchema,
+ attentionItems: AttentionItemSchema,
+ serverRail: serverRailSchema,
+ folders: folderSchema,
+ folderItems: folderItemSchema,
+ notificationSettings: notificationSettingSchema,
+} as const
+
+export type CommunityCollectionName = keyof typeof communityCollectionSchemas
+export type CommunityCollectionRows = { [N in CommunityCollectionName]: z.output<typeof communityCollectionSchemas[N]> }
+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 FriendshipRow = z.infer<typeof friendshipSchema>
+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>
diff --git a/src/shared/src/community-contract.ts b/src/shared/src/community-contract.ts
index f8fb8670e..f765ac6fb 100644
--- a/src/shared/src/community-contract.ts
+++ b/src/shared/src/community-contract.ts
@@ -1,19 +1,16 @@
+import { BUSINESS_SCHEMA_VERSION } from "./business-schema-version"
+
export const COMMUNITY_BOT_ACTOR_HEADER = "X-Alook-Bot-Id"
-export const COMMUNITY_CONTRACT_HEADER = "X-Alook-Community-Contract"
-export const COMMUNITY_CONTRACT_VERSION = 2 as const
-export const COMMUNITY_RESOURCE_CONTRACT_VERSION = 3 as const
-export type CommunityContract = 1 | 2 | 3
+export const COMMUNITY_CONTRACT_HEADER = "X-Alook-Community-Contract"
+export const COMMUNITY_CONTRACT_VERSION = BUSINESS_SCHEMA_VERSION
+export const COMMUNITY_RESOURCE_CONTRACT_VERSION = BUSINESS_SCHEMA_VERSION
+export type CommunityContract = typeof BUSINESS_SCHEMA_VERSION
export function requestedCommunityContract(headers: Pick<Headers, "get">): CommunityContract | null {
- const value = headers.get(COMMUNITY_CONTRACT_HEADER)
- if (value === null || value === "1") return 1
- if (value === "2") return 2
- if (value === "3") return 3
- return null
+ return headers.get(COMMUNITY_CONTRACT_HEADER) === String(BUSINESS_SCHEMA_VERSION) ? BUSINESS_SCHEMA_VERSION : null
}
export function requestsCommunityContract(headers: Pick<Headers, "get">): boolean {
- const contract = requestedCommunityContract(headers)
- return contract === 2 || contract === 3
+ return requestedCommunityContract(headers) === BUSINESS_SCHEMA_VERSION
}
diff --git a/src/shared/src/community-dms.ts b/src/shared/src/community-dms.ts
new file mode 100644
index 000000000..d02fe195f
--- /dev/null
+++ b/src/shared/src/community-dms.ts
@@ -0,0 +1,38 @@
+import { z } from "zod"
+import { CommunityChannelResourceSchema, CommunityMemberRelationSchema, CommunityMessageResourceSchema, CommunityResourceProfileSchema } from "./community-resources"
+
+export const CommunityDmReadItemSchema = z.strictObject({
+ id: CommunityChannelResourceSchema.shape.id,
+ userId: CommunityResourceProfileSchema.shape.id,
+ channel: CommunityChannelResourceSchema,
+ profile: CommunityResourceProfileSchema,
+ memberships: z.array(CommunityMemberRelationSchema).length(2),
+ preview: z.string(),
+ activityAt: CommunityChannelResourceSchema.shape.createdAt,
+ unread: z.boolean(),
+ lastUnreadSeq: CommunityMessageResourceSchema.shape.seq.optional(),
+}).superRefine((dm, ctx) => {
+ const users = new Set(dm.memberships.map(row => row.userId))
+ if (dm.channel.id !== dm.id || dm.channel.type !== "dm" || dm.channel.serverId !== null || dm.channel.categoryId !== null || dm.channel.parentChannelId !== null || dm.channel.parentMessageId !== null
+ || dm.profile.id !== dm.userId || users.size !== 2 || !users.has(dm.userId)
+ || dm.memberships.some(row => row.channelId !== dm.id || row.relation !== "access")
+ || dm.unread !== (dm.lastUnreadSeq !== undefined)) {
+ ctx.addIssue({ code: "custom", message: "DM resource scope mismatch" })
+ }
+})
+
+export const CommunityDmsReadSchema = z.strictObject({ conversations: z.array(CommunityDmReadItemSchema) }).superRefine((value, ctx) => {
+ if (new Set(value.conversations.map(row => row.id)).size !== value.conversations.length) {
+ ctx.addIssue({ code: "custom", message: "Duplicate DM resource identity" })
+ }
+})
+
+export function parseCommunityDmsRead(value: unknown, viewerId: string) {
+ const result = CommunityDmsReadSchema.parse(value)
+ if (result.conversations.some(dm => dm.userId === viewerId || !dm.memberships.some(row => row.userId === viewerId))) {
+ throw new Error("DM resource viewer mismatch")
+ }
+ return result
+}
+
+export type CommunityDmsRead = z.infer<typeof CommunityDmsReadSchema>
diff --git a/src/shared/src/community-forum-sidebar.ts b/src/shared/src/community-forum-sidebar.ts
new file mode 100644
index 000000000..75df7387d
--- /dev/null
+++ b/src/shared/src/community-forum-sidebar.ts
@@ -0,0 +1,39 @@
+import { z } from "zod"
+import { BUSINESS_SCHEMA_VERSION } from "./business-schema-version"
+import { CommunityChannelResourceSchema, CommunityResourceBundleSchema } from "./community-resources"
+
+const timestamp = z.string().refine(value => Number.isFinite(Date.parse(value)))
+export const CommunityForumSidebarChannelSummarySchema = CommunityChannelResourceSchema.pick({
+ id: true, name: true, serverId: true, parentChannelId: true, parentMessageId: true,
+}).extend({
+ serverId: CommunityChannelResourceSchema.shape.serverId.unwrap(),
+ parentChannelId: CommunityChannelResourceSchema.shape.parentChannelId.unwrap(),
+ parentMessageId: CommunityChannelResourceSchema.shape.parentMessageId.unwrap(),
+ activityAt: timestamp, expiresAt: timestamp, unread: z.boolean(),
+})
+
+export const CommunityForumSidebarEnvelopeSchema = z.strictObject({
+ schemaVersion: z.literal(BUSINESS_SCHEMA_VERSION), serverId: z.string().min(1),
+ channels: z.array(CommunityForumSidebarChannelSummarySchema),
+ canonicalChannels: z.array(CommunityForumSidebarChannelSummarySchema),
+ retainedChannel: CommunityForumSidebarChannelSummarySchema.nullable(),
+ retainedDisposition: z.enum(["eligible", "opener-archived", "genuine-negative"]).nullable(),
+ resources: CommunityResourceBundleSchema,
+ serverNow: timestamp,
+}).superRefine((data, ctx) => {
+ const selected = [...data.canonicalChannels, ...(data.retainedChannel ? [data.retainedChannel] : [])]
+ if (data.resources.servers.some(row => row.id !== data.serverId) || data.resources.channels.some(row => row.serverId !== data.serverId)
+ || new Set(data.channels.map(row => row.id)).size !== data.channels.length
+ || new Set(data.canonicalChannels.map(row => row.id)).size !== data.canonicalChannels.length
+ || data.canonicalChannels.some(row => data.canonicalChannels.filter(other => other.parentChannelId === row.parentChannelId).length > 5)
+ || data.channels.some(row => !selected.some(other => other.id === row.id))
+ || (data.retainedDisposition === "eligible") !== (data.retainedChannel !== null)
+ || selected.some(row => !data.resources.channels.some(channel => channel.id === row.id && channel.type === "thread"
+ && channel.serverId === row.serverId && channel.parentChannelId === row.parentChannelId && channel.parentMessageId === row.parentMessageId)
+ || !data.resources.messages.some(message => message.id === row.parentMessageId && message.channelId === row.parentChannelId)
+ || !data.resources.memberships.some(member => member.channelId === row.id && member.userId === data.resources.viewerId && member.relation === "notify"))) {
+ ctx.addIssue({ code: "custom", message: "Forum sidebar resource closure mismatch" })
+ }
+})
+
+export type CommunityForumSidebarEnvelope = z.infer<typeof CommunityForumSidebarEnvelopeSchema>
diff --git a/src/shared/src/community-friend-approval.ts b/src/shared/src/community-friend-approval.ts
index 0162b0929..b6a8bf9ee 100644
--- a/src/shared/src/community-friend-approval.ts
+++ b/src/shared/src/community-friend-approval.ts
@@ -1,12 +1,8 @@
import { z } from "zod"
+import { CommunityResourceProfileSchema } from "./community-profile-resource"
-const profile = z.strictObject({
- id: z.string(),
- name: z.string(),
- discriminator: z.string(),
- image: z.string().nullable(),
- avatarVersion: z.number().int().nonnegative(),
-})
+const identity = CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatarVersion: true })
+const profile = identity.extend({ image: CommunityResourceProfileSchema.shape.avatar })
export const FriendApprovalPayloadSchema = z.strictObject({
friendshipId: z.string(),
diff --git a/src/shared/src/community-friends.test.ts b/src/shared/src/community-friends.test.ts
new file mode 100644
index 000000000..378cb2187
--- /dev/null
+++ b/src/shared/src/community-friends.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION } from "./business-schema-version"
+import { CommunityAcceptedFriendsReadSchema, CommunityBlockedFriendsReadSchema, CommunityPendingFriendsReadSchema } from "./community-friends"
+import { CommunityResourceBundleSchema } from "./community-resources"
+
+const resources = () => CommunityResourceBundleSchema.parse({ viewerId: "viewer", servers: [], serverMemberships: [], channels: [], memberships: [], messages: [], profiles: [{ id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0 }] })
+const cases = [
+ { bucket: "friends", schema: CommunityAcceptedFriendsReadSchema, row: { id: "relation", userId: "peer", sub: "detail" } },
+ { bucket: "blocked", schema: CommunityBlockedFriendsReadSchema, row: { id: "block", userId: "peer" } },
+ { bucket: "pending", schema: CommunityPendingFriendsReadSchema, row: { id: "request", userId: "peer", kind: "outgoing", needsOwnerApproval: "viewer" } },
+] as const
+
+describe("current named human friend reads", () => {
+ it.each(cases)("separates $bucket relation identity from the complete profile", ({ bucket, schema, row }) => {
+ const value = { contractVersion: BUSINESS_SCHEMA_VERSION, [bucket]: [row], resources: resources() }
+ expect(schema.parse(value)).toEqual(value)
+ expect(schema.safeParse({ ...value, [bucket]: [{ ...row, name: "second identity" }] }).success).toBe(false)
+ })
+ it.each(cases)("rejects absent/empty peer IDs and missing full profile for $bucket", ({ bucket, schema, row }) => {
+ const value = { contractVersion: BUSINESS_SCHEMA_VERSION, [bucket]: [row], resources: resources() }
+ const { userId: _userId, ...unkeyed } = row
+ expect(schema.safeParse({ ...value, [bucket]: [unkeyed] }).success).toBe(false)
+ expect(schema.safeParse({ ...value, [bucket]: [{ ...row, userId: "" }] }).success).toBe(false)
+ expect(schema.safeParse({ ...value, resources: { ...resources(), profiles: [] } }).success).toBe(false)
+ expect(schema.safeParse({ ...value, resources: { ...resources(), profiles: [{ id: "peer", name: "Peer", discriminator: null, avatarVersion: 0 }] } }).success).toBe(false)
+ })
+ it.each(cases)("keeps current stale $bucket explicit and empty", ({ bucket, schema }) => {
+ const value = { contractVersion: BUSINESS_SCHEMA_VERSION, [bucket]: [], stale: true }
+ expect(schema.parse(value)).toEqual(value)
+ expect(schema.safeParse({ ...value, resources: resources() }).success).toBe(false)
+ expect(schema.safeParse({ ...value, contractVersion: BUSINESS_SCHEMA_VERSION - 1 }).success).toBe(false)
+ })
+ it("rejects accepted/blocked states as pending direction and obsolete success envelopes", () => {
+ const value = { contractVersion: BUSINESS_SCHEMA_VERSION, pending: [{ id: "request", userId: "peer", kind: "accepted" }], resources: resources() }
+ expect(CommunityPendingFriendsReadSchema.safeParse(value).success).toBe(false)
+ expect(CommunityAcceptedFriendsReadSchema.safeParse({ contractVersion: 1, friends: [], resources: resources() }).success).toBe(false)
+ expect(CommunityAcceptedFriendsReadSchema.safeParse({ friends: [], resources: resources() }).success).toBe(false)
+ })
+})
diff --git a/src/shared/src/community-friends.ts b/src/shared/src/community-friends.ts
new file mode 100644
index 000000000..ba818954e
--- /dev/null
+++ b/src/shared/src/community-friends.ts
@@ -0,0 +1,34 @@
+import { z } from "zod"
+import { BUSINESS_SCHEMA_VERSION } from "./business-schema-version"
+import { friendshipSchema } from "./community-cache"
+import { CommunityResourceBundleSchema, type CommunityResourceBundle } from "./community-resources"
+
+export const CommunityAcceptedFriendDescriptorSchema = friendshipSchema.pick({ id: true, userId: true, sub: true })
+export const CommunityBlockedFriendDescriptorSchema = friendshipSchema.pick({ id: true, userId: true })
+export const CommunityPendingFriendDescriptorSchema = friendshipSchema.pick({ id: true, userId: true, needsOwnerApproval: true }).extend({
+ kind: friendshipSchema.shape.kind.extract(["incoming", "outgoing"]),
+})
+
+const envelope = { contractVersion: z.literal(BUSINESS_SCHEMA_VERSION) }
+const fresh = { ...envelope, resources: CommunityResourceBundleSchema, stale: z.literal(false).optional() }
+const stale = { ...envelope, stale: z.literal(true) }
+function checkProfiles(rows: Array<{ userId: string }>, resources: CommunityResourceBundle, ctx: z.RefinementCtx) {
+ if (rows.some(row => !resources.profiles.some(profile => profile.id === row.userId))) {
+ ctx.addIssue({ code: "custom", message: "Friend profile resource missing" })
+ }
+}
+export const CommunityAcceptedFriendsReadSchema = z.union([
+ z.strictObject({ ...fresh, friends: z.array(CommunityAcceptedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.friends, value.resources, ctx)),
+ z.strictObject({ ...stale, friends: z.array(CommunityAcceptedFriendDescriptorSchema).length(0) }),
+])
+export const CommunityBlockedFriendsReadSchema = z.union([
+ z.strictObject({ ...fresh, blocked: z.array(CommunityBlockedFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.blocked, value.resources, ctx)),
+ z.strictObject({ ...stale, blocked: z.array(CommunityBlockedFriendDescriptorSchema).length(0) }),
+])
+export const CommunityPendingFriendsReadSchema = z.union([
+ z.strictObject({ ...fresh, pending: z.array(CommunityPendingFriendDescriptorSchema) }).superRefine((value, ctx) => checkProfiles(value.pending, value.resources, ctx)),
+ z.strictObject({ ...stale, pending: z.array(CommunityPendingFriendDescriptorSchema).length(0) }),
+])
+export type CommunityAcceptedFriendsRead = z.infer<typeof CommunityAcceptedFriendsReadSchema>
+export type CommunityBlockedFriendsRead = z.infer<typeof CommunityBlockedFriendsReadSchema>
+export type CommunityPendingFriendsRead = z.infer<typeof CommunityPendingFriendsReadSchema>
diff --git a/src/shared/src/community-invites.test.ts b/src/shared/src/community-invites.test.ts
new file mode 100644
index 000000000..74d1da086
--- /dev/null
+++ b/src/shared/src/community-invites.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION } from "./business-schema-version"
+import { CommunityInviteCreateSchema } from "./community-ws-events"
+import { CommunityInvitesReadSchema, CommunityInviteListItemSchema } from "./community-invites"
+
+const invite = { id: "invite", token: "token", maxUses: null, uses: 0, expiresAt: null, createdAt: "now", creatorId: "creator" }
+const profile = { id: "creator", name: "Creator", discriminator: "0042", avatar: null, avatarVersion: 0 }
+const value = () => ({ contractVersion: BUSINESS_SCHEMA_VERSION, serverId: "server", invites: [invite], resources: { viewerId: "viewer", servers: [{ id: "server", name: "Server", discriminator: "0042", description: "", ownerId: "owner", icon: null, position: 0, official: false, isOwner: false }], serverMemberships: [{ serverId: "server", userId: "viewer", memberId: "member", role: "member" }], channels: [], memberships: [], messages: [], profiles: [profile] } })
+describe("current named invite reads", () => {
+ it("derives invite descriptor fields from the existing unique invite-create declaration", () => {
+ for (const key of ["id", "token", "createdAt"] as const) expect(CommunityInviteListItemSchema.shape[key]).toBe(CommunityInviteCreateSchema.shape.invite.shape[key])
+ expect(CommunityInvitesReadSchema.parse(value())).toEqual(value())
+ })
+ it("requires actual nullable descriptor facts and full creator core", () => {
+ const v = value()
+ for (const key of ["creatorId", "maxUses", "uses", "expiresAt"]) {
+ const row: Record<string, unknown> = { ...invite }; delete row[key]
+ expect(CommunityInvitesReadSchema.safeParse({ ...v, invites: [row] }).success).toBe(false)
+ }
+ expect(CommunityInvitesReadSchema.safeParse({ ...v, resources: { ...v.resources, profiles: [] } }).success).toBe(false)
+ const { avatar: _avatar, ...incomplete } = profile
+ expect(CommunityInvitesReadSchema.safeParse({ ...v, resources: { ...v.resources, profiles: [incomplete] } }).success).toBe(false)
+ })
+ it("permits an explicitly deleted creator without inventing a profile", () => {
+ const v = value()
+ expect(CommunityInvitesReadSchema.parse({ ...v, invites: [{ ...invite, creatorId: null }], resources: { ...v.resources, profiles: [] } }).invites[0].creatorId).toBeNull()
+ })
+ it("rejects duplicate IDs, foreign server resources, PII hints and invalid use counts", () => {
+ const v = value()
+ expect(CommunityInvitesReadSchema.safeParse({ ...v, invites: [invite, invite] }).success).toBe(false)
+ expect(CommunityInvitesReadSchema.safeParse({ ...v, serverId: "foreign" }).success).toBe(false)
+ for (const key of ["creatorName", "creatorEmail", "creatorImage"]) expect(CommunityInvitesReadSchema.safeParse({ ...v, invites: [{ ...invite, [key]: "duplicate identity" }] }).success).toBe(false)
+ for (const uses of [-1, null, 0.5]) expect(CommunityInvitesReadSchema.safeParse({ ...v, invites: [{ ...invite, uses }] }).success).toBe(false)
+ })
+ it.each([1, 2, 3])("refuses old source version%s", contractVersion => {
+ expect(CommunityInvitesReadSchema.safeParse({ ...value(), contractVersion }).success).toBe(false)
+ })
+})
diff --git a/src/shared/src/community-invites.ts b/src/shared/src/community-invites.ts
new file mode 100644
index 000000000..f1aebd6a9
--- /dev/null
+++ b/src/shared/src/community-invites.ts
@@ -0,0 +1,21 @@
+import { z } from "zod"
+import { BUSINESS_SCHEMA_VERSION } from "./business-schema-version"
+import { CommunityInviteCreateSchema } from "./community-ws-events"
+import { CommunityResourceBundleSchema, CommunityResourceProfileSchema, CommunityServerResourceSchema } from "./community-resources"
+
+export const CommunityInviteListItemSchema = CommunityInviteCreateSchema.shape.invite.required({ maxUses: true, uses: true, expiresAt: true }).extend({
+ uses: CommunityInviteCreateSchema.shape.invite.shape.uses.unwrap().unwrap().int().nonnegative(),
+ creatorId: CommunityResourceProfileSchema.shape.id.nullable(),
+})
+export const CommunityInvitesReadSchema = z.strictObject({
+ contractVersion: z.literal(BUSINESS_SCHEMA_VERSION),
+ serverId: CommunityServerResourceSchema.shape.id,
+ invites: z.array(CommunityInviteListItemSchema),
+ resources: CommunityResourceBundleSchema,
+}).superRefine((value, ctx) => {
+ if (new Set(value.invites.map(row => row.id)).size !== value.invites.length) ctx.addIssue({ code: "custom", message: "Duplicate invite descriptor" })
+ if (!value.resources.servers.some(row => row.id === value.serverId) || value.resources.servers.some(row => row.id !== value.serverId)) ctx.addIssue({ code: "custom", message: "Invite server resource mismatch" })
+ if (value.invites.some(row => row.creatorId !== null && !value.resources.profiles.some(profile => profile.id === row.creatorId))) ctx.addIssue({ code: "custom", message: "Invite creator profile resource missing" })
+})
+export type CommunityInviteListItem = z.infer<typeof CommunityInviteListItemSchema>
+export type CommunityInvitesRead = z.infer<typeof CommunityInvitesReadSchema>
diff --git a/src/shared/src/community-machine-resources.ts b/src/shared/src/community-machine-resources.ts
new file mode 100644
index 000000000..966c757f5
--- /dev/null
+++ b/src/shared/src/community-machine-resources.ts
@@ -0,0 +1,7 @@
+import { z } from "zod"
+import { CommunityMachineSummarySchema } from "./schemas"
+
+export const CommunityMachineIdentityCacheSchema = CommunityMachineSummarySchema.pick({ id: true, hostname: true, displayName: true,
+ platform: true, arch: true, osRelease: true, daemonVersion: true, createdAt: true, updatedAt: true })
+export const CommunityMachineListReadSchema = z.strictObject({ machines: z.array(CommunityMachineSummarySchema), complete: z.literal(true) })
+export type CommunityMachineIdentityCache = z.infer<typeof CommunityMachineIdentityCacheSchema>
diff --git a/src/shared/src/community-message-delivery.ts b/src/shared/src/community-message-delivery.ts
index 3b4f23efc..663460196 100644
--- a/src/shared/src/community-message-delivery.ts
+++ b/src/shared/src/community-message-delivery.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "./business-schema-version";
import { z } from "zod";
import {
communityWsEventSchemaForContract,
@@ -13,21 +14,14 @@ export const MESSAGE_DELIVERY_MAX_USERS = 1_000;
export const MESSAGE_DELIVERY_BODY_MAX_BYTES = 837_347;
export const MESSAGE_DELIVERY_MAX_EVENTS_PER_USER = 5;
-export type MessageDeliveryMemberAdded = {
- userId: string;
- serverId: string;
- channelId: string;
-};
-
export type MessageDeliveryBatch = {
- communityContract?: 3;
+ communityContract: typeof BUSINESS_SCHEMA_VERSION;
messageId: string;
messageEvent: CommunityMessageCreate;
contentUserIds: string[];
unreadPlainUserIds: string[];
unreadMentionUserIds: string[];
mentionUserIds: string[];
- memberAdded?: MessageDeliveryMemberAdded;
joinedParticipantUserIds?: string[];
rosterRefreshUserId?: string;
parentProjection?: CommunityChildChannelUpdate;
@@ -38,21 +32,14 @@ export type MessageDeliveryPartial = { failedUserIds: string[] };
const target = z.string().refine(isValidCommunityUserTarget);
const targetList = z.array(target).max(MESSAGE_DELIVERY_MAX_USERS);
-const memberAddedSchema = z.strictObject({
- userId: target,
- serverId: z.string().min(1),
- channelId: z.string().min(1),
-});
-
const batchShape = z.strictObject({
- communityContract: z.literal(3).optional(),
+ communityContract: z.literal(BUSINESS_SCHEMA_VERSION),
messageId: z.string().min(1),
messageEvent: z.unknown(),
contentUserIds: targetList,
unreadPlainUserIds: targetList,
unreadMentionUserIds: targetList,
mentionUserIds: targetList,
- memberAdded: memberAddedSchema.optional(),
joinedParticipantUserIds: targetList.optional(),
rosterRefreshUserId: target.optional(),
parentProjection: z.unknown().optional(),
@@ -75,7 +62,7 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchP
const outer = batchShape.safeParse(value);
if (!outer.success) return { ok: false, reason: "invalid-payload" };
const data = outer.data;
- const schema = communityWsEventSchemaForContract(data.communityContract ?? 2);
+ const schema = communityWsEventSchemaForContract(data.communityContract);
const message = schema.safeParse(data.messageEvent);
if (!message.success || message.data.type !== "community:message.create") {
return { ok: false, reason: "invalid-payload" };
@@ -120,17 +107,6 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchP
if (data.unreadPlainUserIds.some((id) => unreadMention.has(id))) {
return { ok: false, reason: "invalid-payload" };
}
- if (data.memberAdded) {
- if (
- !content.has(data.memberAdded.userId)
- || message.data.serverId === undefined
- || data.memberAdded.channelId !== message.data.channelId
- || data.memberAdded.serverId !== message.data.serverId
- ) {
- return { ok: false, reason: "invalid-payload" };
- }
- }
-
if ((data.joinedParticipantUserIds === undefined) !== (data.rosterRefreshUserId === undefined)
|| (data.joinedParticipantUserIds && (hasDuplicates(data.joinedParticipantUserIds)
|| !isSubset(data.joinedParticipantUserIds, content) || !message.data.serverId))) return { ok: false, reason: "invalid-payload" };
@@ -146,14 +122,13 @@ export function parseMessageDeliveryBatch(value: unknown): MessageDeliveryBatchP
return {
ok: true,
batch: {
- ...(data.communityContract === 3 ? { communityContract: 3 } : {}),
+ communityContract: BUSINESS_SCHEMA_VERSION,
messageId: data.messageId,
messageEvent: message.data,
contentUserIds: data.contentUserIds,
unreadPlainUserIds: data.unreadPlainUserIds,
unreadMentionUserIds: data.unreadMentionUserIds,
mentionUserIds: data.mentionUserIds,
- ...(data.memberAdded ? { memberAdded: data.memberAdded } : {}),
...(data.joinedParticipantUserIds ? { joinedParticipantUserIds: data.joinedParticipantUserIds, rosterRefreshUserId: data.rosterRefreshUserId } : {}),
...(parentProjection ? { parentProjection } : {}),
...(data.parentProjectionUserIds
diff --git a/src/shared/src/community-profile-reads.ts b/src/shared/src/community-profile-reads.ts
new file mode 100644
index 000000000..155e37d93
--- /dev/null
+++ b/src/shared/src/community-profile-reads.ts
@@ -0,0 +1,106 @@
+import { z } from "zod"
+import { CommunityResourceProfileSchema, CommunityServerMembershipResourceSchema } from "./community-resources"
+import { ROLES } from "./utils/community-roles"
+
+export const CommunitySelfProfileReadSchema = CommunityResourceProfileSchema.pick({
+ id: true, name: true, discriminator: true, avatar: true, avatarVersion: true,
+ aboutMe: true, bannerColor: true, statusEmoji: true, statusText: true,
+}).required()
+
+export function parseCommunitySelfProfileRead(value: unknown, viewerId: string) {
+ const profile = CommunitySelfProfileReadSchema.parse(value)
+ if (profile.id !== viewerId) throw new Error("Self profile viewer mismatch")
+ return profile
+}
+
+const card = CommunitySelfProfileReadSchema.omit({ avatar: true }).extend({
+ image: CommunityResourceProfileSchema.shape.avatar,
+ mutualServers: CommunityResourceProfileSchema.shape.mutualServers.unwrap(),
+})
+export const CommunityUserCardReadSchema = z.discriminatedUnion("kind", [
+ card.extend({ kind: z.literal("human") }),
+ card.extend({ kind: z.literal("bot"), ownerProfile: z.strictObject({ id: CommunityResourceProfileSchema.shape.id, handle: CommunityResourceProfileSchema.shape.ownerHandle.unwrap().unwrap() }), ownedByViewer: CommunityResourceProfileSchema.shape.ownedByViewer.unwrap() }),
+])
+
+export function parseCommunityUserCardRead(value: unknown, userId: string, viewerId: string) {
+ const profile = CommunityUserCardReadSchema.parse(value)
+ if (profile.id !== userId || (profile.kind === "bot" && profile.ownedByViewer !== (profile.ownerProfile.id === viewerId))) throw new Error("User card request scope mismatch")
+ return profile
+}
+export type CommunityUserCardRead = z.infer<typeof CommunityUserCardReadSchema>
+
+export const CommunityServerMemberReadSchema = CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true, statusEmoji: true, statusText: true }).required().extend({
+ id: CommunityServerMembershipResourceSchema.shape.memberId,
+ userId: CommunityResourceProfileSchema.shape.id,
+ role: z.enum(ROLES),
+ status: z.enum(["online", "offline"]),
+ sub: z.string(),
+ isBot: z.literal(true).optional(),
+ ownerUserId: CommunityResourceProfileSchema.shape.id.optional(),
+}).superRefine((row, ctx) => {
+ if ((row.isBot === true) !== (row.ownerUserId !== undefined)) ctx.addIssue({ code: "custom", message: "Member owner metadata mismatch" })
+})
+const page = z.strictObject({
+ viewerId: CommunityResourceProfileSchema.shape.id,
+ serverId: CommunityServerMembershipResourceSchema.shape.serverId,
+ members: z.array(CommunityServerMemberReadSchema),
+ hasMore: z.boolean(), cursor: z.string().min(1).optional(), limit: z.number().int().positive(),
+})
+const validatePage = (value: z.infer<typeof page>, ctx: z.RefinementCtx) => {
+ if ((value.hasMore && !value.cursor) || new Set(value.members.map(row => row.id)).size !== value.members.length
+ || new Set(value.members.map(row => row.userId)).size !== value.members.length || value.members.length > value.limit
+ || value.members.some(row => row.ownerUserId !== undefined && row.ownerUserId !== value.viewerId)) ctx.addIssue({ code: "custom", message: "Member page scope mismatch" })
+}
+export const CommunityServerMembersReadSchema = page.extend({ total: z.number().int().nonnegative() }).superRefine(validatePage)
+export const CommunityServerMemberSearchReadSchema = page.superRefine(validatePage)
+
+export function parseCommunityServerMembersRead(value: unknown, serverId: string, viewerId: string, search: boolean): z.infer<typeof page> & { total?: number } {
+ const result = (search ? CommunityServerMemberSearchReadSchema : CommunityServerMembersReadSchema).parse(value)
+ if (result.serverId !== serverId || result.viewerId !== viewerId) throw new Error("Member page request scope mismatch")
+ return result
+}
+
+export const CommunityUserSearchReadSchema = z.strictObject({ users: z.array(CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatarVersion: true }).extend({ image: CommunityResourceProfileSchema.shape.avatar })) })
+
+export type CommunityUserSearchRead = z.infer<typeof CommunityUserSearchReadSchema>
+
+export type CommunitySelfProfileRead = z.infer<typeof CommunitySelfProfileReadSchema>
+
+export const CommunityReactionActorProfileSchema = CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatar: true, avatarVersion: true })
+export const CommunityReactionDetailsReadSchema = z.strictObject({
+ messageId: CommunityResourceProfileSchema.shape.id,
+ scope: z.discriminatedUnion("kind", [
+ z.strictObject({ kind: z.literal("server"), serverId: CommunityServerMembershipResourceSchema.shape.serverId, channelId: CommunityResourceProfileSchema.shape.id }),
+ z.strictObject({ kind: z.literal("dm"), channelId: CommunityResourceProfileSchema.shape.id }),
+ ]),
+ actors: z.array(z.strictObject({ userId: CommunityResourceProfileSchema.shape.id, profile: CommunityReactionActorProfileSchema.nullable() })),
+}).superRefine((value, ctx) => {
+ if (new Set(value.actors.map(row => row.userId)).size !== value.actors.length || value.actors.some(row => row.profile && row.profile.id !== row.userId)) ctx.addIssue({ code: "custom", message: "Reaction actor identity mismatch" })
+})
+export type CommunityReactionDetailsRead = z.infer<typeof CommunityReactionDetailsReadSchema>
+export type CommunityReactionActorProfile = z.infer<typeof CommunityReactionActorProfileSchema>
+export function parseCommunityReactionDetailsRead(value: unknown, messageId: string, scope: CommunityReactionDetailsRead["scope"]) {
+ const result = CommunityReactionDetailsReadSchema.parse(value)
+ if (result.messageId !== messageId || result.scope.kind !== scope.kind || result.scope.channelId !== scope.channelId
+ || (result.scope.kind === "server" && scope.kind === "server" && result.scope.serverId !== scope.serverId)) throw new Error("Reaction message request scope mismatch")
+ return result
+}
+
+export const CommunityBotProfileSummarySchema = CommunityResourceProfileSchema.pick({ id: true, name: true, avatarVersion: true }).extend({
+ image: CommunityResourceProfileSchema.shape.avatar,
+ discriminator: CommunityResourceProfileSchema.shape.discriminator.optional(),
+ description: CommunityResourceProfileSchema.shape.aboutMe,
+ presence: z.enum(["online", "offline"]).optional(),
+}).strip()
+
+export const CommunityBotsProfileReadSchema = z.object({
+ bots: z.array(CommunityBotProfileSummarySchema.required({ discriminator: true, description: true, presence: true }).extend({ ownerUserId: CommunityResourceProfileSchema.shape.id })),
+}).strip().superRefine((value, ctx) => {
+ if (new Set(value.bots.map(row => row.id)).size !== value.bots.length) ctx.addIssue({ code: "custom", message: "Duplicate bot catalogue identity" })
+})
+export type CommunityBotsProfileRead = z.infer<typeof CommunityBotsProfileReadSchema>
+export function parseCommunityBotsProfileRead(value: unknown, viewerId: string) {
+ const result = CommunityBotsProfileReadSchema.parse(value)
+ if (result.bots.some(row => row.ownerUserId !== viewerId)) throw new Error("Bot catalogue owner mismatch")
+ return result
+}
diff --git a/src/shared/src/community-profile-resource.ts b/src/shared/src/community-profile-resource.ts
new file mode 100644
index 000000000..ce89912ab
--- /dev/null
+++ b/src/shared/src/community-profile-resource.ts
@@ -0,0 +1,18 @@
+import { z } from "zod"
+
+export const CommunityResourceProfileSchema = z.strictObject({
+ id: z.string().min(1),
+ name: z.string(),
+ discriminator: z.string().min(1),
+ avatar: z.string().nullable(),
+ avatarVersion: z.number().int().nonnegative(),
+ aboutMe: z.string().optional(),
+ bannerColor: z.string().nullable().optional(),
+ kind: z.enum(["human", "bot"]).optional(),
+ ownerUserId: z.string().min(1).nullable().optional(),
+ ownerHandle: z.string().nullable().optional(),
+ mutualServers: z.number().int().nonnegative().optional(),
+ ownedByViewer: z.boolean().optional(),
+ statusEmoji: z.string().nullable().optional(),
+ statusText: z.string().nullable().optional(),
+})
diff --git a/src/shared/src/community-resources.ts b/src/shared/src/community-resources.ts
index ac87822af..8afd78056 100644
--- a/src/shared/src/community-resources.ts
+++ b/src/shared/src/community-resources.ts
@@ -1,12 +1,36 @@
+import { CommunityResourceProfileSchema } from "./community-profile-resource"
+export { CommunityResourceProfileSchema } from "./community-profile-resource"
import { z } from "zod"
import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "./community-contract"
import { FriendApprovalPayloadSchema } from "./community-friend-approval"
+import { PARTICIPANT_SOURCE } from "./constants/community"
import { BotCreationPayloadSchema } from "./community-bot-creation"
const id = z.string().min(1)
const nullableId = id.nullable()
export const COMMUNITY_CONVERSATION_ANCHOR_MISSING = "conversation_anchor_missing"
-const legacyArchivedSchema = z.union([z.boolean(), z.literal(0), z.literal(1)]).transform((value) => value === true || value === 1)
+const storedArchivedSchema = z.union([z.boolean(), z.literal(0), z.literal(1)]).transform((value) => value === true || value === 1)
+
+export const CommunityServerResourceSchema = z.strictObject({
+ id: z.string().min(1),
+ position: z.number().int().nonnegative(),
+ name: z.string(),
+ discriminator: z.string(),
+ description: z.string(),
+ ownerId: z.string(),
+ icon: z.string().nullable(),
+ official: z.boolean(),
+ isOwner: z.boolean(),
+})
+
+export const CommunityCategoryResourceSchema = z.strictObject({
+ id: z.string().min(1),
+ serverId: z.string().min(1),
+ name: z.string(),
+ position: z.number(),
+ private: z.boolean(),
+ creatorId: z.string().nullable(),
+})
export const CommunityChannelResourceSchema = z.strictObject({
id,
@@ -28,19 +52,7 @@ export const CommunityChannelResourceSchema = z.strictObject({
export const CommunityChannelIdentitySchema = CommunityChannelResourceSchema.pick({
id: true, type: true, serverId: true, name: true, parentChannelId: true,
parentMessageId: true, creatorId: true, archived: true, lastMessageAt: true, createdAt: true,
-}).partial({ createdAt: true }).strip()
-
-const legacyChannelIdentitySchema = CommunityChannelIdentitySchema.extend({
- archived: legacyArchivedSchema,
- parentChannelId: nullableId.default(null),
- parentMessageId: nullableId.default(null),
- creatorId: nullableId.default(null),
- lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null),
-})
-
-export function normalizeCommunityChannelIdentity(value: unknown) {
- return legacyChannelIdentitySchema.parse(value)
-}
+}).strip()
export const CommunityAccessDecisionSchema = z.strictObject({
channelId: id,
@@ -49,19 +61,6 @@ export const CommunityAccessDecisionSchema = z.strictObject({
canCreateDiscussion: z.boolean(),
})
-export const CommunityLegacyMessageAttachmentSchema = z.strictObject({
- kind: z.enum(["image", "file"]),
- name: z.string(),
- url: z.string(),
- thumbnailUrl: z.string().optional(),
- contentType: z.string().optional(),
- size: z.string().optional(),
- sizeBytes: z.number().nonnegative().optional(),
- width: z.number().nonnegative().optional(),
- height: z.number().nonnegative().optional(),
-})
-
-
export const CommunityMessageAttachmentSchema = z.strictObject({
id,
name: z.string(),
@@ -73,24 +72,6 @@ export const CommunityMessageAttachmentSchema = z.strictObject({
height: z.number().int().nonnegative().nullable(),
})
-export const CommunityMessagePreviewAttachmentSchema = CommunityMessageAttachmentSchema.partial().required({ name: true, url: true })
-
-export const CommunityResourceProfileSchema = z.strictObject({
- id,
- name: z.string(),
- discriminator: z.string().min(1).nullable(),
- avatar: z.string().nullable(),
- avatarVersion: z.number().int().nonnegative(),
- aboutMe: z.string().optional(),
- bannerColor: z.string().nullable().optional(),
- kind: z.enum(["human", "bot"]).optional(),
- ownerUserId: nullableId.optional(),
- ownerHandle: z.string().nullable().optional(),
- mutualServers: z.number().int().nonnegative().optional(),
- ownedByViewer: z.boolean().optional(),
- statusEmoji: z.string().nullable().optional(),
- statusText: z.string().nullable().optional(),
-})
export const CommunityMessageThreadParticipantSchema = CommunityResourceProfileSchema.pick({ id: true, name: true, avatar: true, avatarVersion: true })
@@ -104,15 +85,6 @@ const messageThreadSchema = z.strictObject({
participants: z.array(CommunityMessageThreadParticipantSchema).optional(),
participantCount: z.number().int().nonnegative().optional(),
})
-const legacyMessageThreadSchema = messageThreadSchema.extend({
- name: z.string(),
- lastReplyAt: z.string().optional(),
- participants: z.array(CommunityMessageThreadParticipantSchema.extend({ avatar: z.string() })).optional(),
-})
-const messageThreadPreviewSchema = messageThreadSchema.partial().required({ id: true }).extend({
- participants: z.array(CommunityMessageThreadParticipantSchema.partial().required({ id: true })).optional(),
-})
-
export const CommunityMessageResourceSchema = z.strictObject({
id,
channelId: id,
@@ -135,7 +107,7 @@ export const CommunityMessageResourceSchema = z.strictObject({
authorName: z.string(),
text: z.string(),
deleted: z.boolean().optional(),
- }).optional(),
+ }).refine(reply => reply.deleted === true || reply.authorId !== undefined, { message: "Live reply author identity missing" }).optional(),
embeds: z.array(z.unknown()).optional(),
reactions: z.array(z.strictObject({
emoji: z.string(),
@@ -148,9 +120,19 @@ export const CommunityMessageResourceSchema = z.strictObject({
botCreation: BotCreationPayloadSchema.optional(),
})
-export const CommunityMessagePreviewSchema = CommunityMessageResourceSchema.partial().required({
- id: true, type: true,
-}).extend({ attachments: z.array(CommunityMessagePreviewAttachmentSchema).optional(), thread: messageThreadPreviewSchema.optional() })
+export function communityMessageProfileIds(messages: readonly Pick<CommunityMessageResource, "authorId" | "replyTo">[]) {
+ return [...new Set(messages.flatMap(message => [message.authorId, ...(message.replyTo?.authorId && message.replyTo.deleted !== true ? [message.replyTo.authorId] : [])]))]
+}
+
+export const CommunityMessageResourcesSchema = z.strictObject({
+ messages: z.array(CommunityMessageResourceSchema),
+ profiles: z.array(CommunityResourceProfileSchema),
+}).superRefine((resources, ctx) => {
+ const ids = new Set(resources.profiles.map(profile => profile.id))
+ if (ids.size !== resources.profiles.length || communityMessageProfileIds(resources.messages).some(id => !ids.has(id))) {
+ ctx.addIssue({ code: "custom", path: ["profiles"], message: "Message profile missing or duplicated in resource graph" })
+ }
+})
export const CommunityReadStateResourceSchema = z.strictObject({
channelId: id,
@@ -159,11 +141,18 @@ export const CommunityReadStateResourceSchema = z.strictObject({
lastReadSeq: z.number().int().nonnegative(),
})
-export const CommunityMemberRelationSchema = z.strictObject({
+export const CommunityServerMembershipResourceSchema = z.strictObject({
+ serverId: id, userId: id, memberId: id, role: z.string(),
+})
+
+export const CommunityChannelMembershipResourceSchema = z.strictObject({
channelId: id,
userId: id,
relation: z.enum(["access", "notify"]),
- source: z.string(),
+ source: z.enum([...Object.values(PARTICIPANT_SOURCE), "explicit", "inherited", "admin", "access-decision"]),
+})
+
+export const CommunityMemberRelationSchema = CommunityChannelMembershipResourceSchema.extend({
isCreator: z.boolean(),
role: z.string().nullable(),
memberId: nullableId,
@@ -179,10 +168,31 @@ export const CommunityPageSchema = z.strictObject({
})
const envelope = { contractVersion: z.literal(COMMUNITY_RESOURCE_CONTRACT_VERSION), channelId: id }
+export const CommunityResourceBundleSchema = CommunityMessageResourcesSchema.safeExtend({
+ viewerId: id,
+ servers: z.array(CommunityServerResourceSchema), serverMemberships: z.array(CommunityServerMembershipResourceSchema),
+ channels: z.array(CommunityChannelResourceSchema), memberships: z.array(CommunityChannelMembershipResourceSchema),
+}).superRefine((bundle, ctx) => {
+ const channels = new Set(bundle.channels.map(row => row.id))
+ const servers = new Set(bundle.servers.map(row => row.id))
+ if (channels.size !== bundle.channels.length || servers.size !== bundle.servers.length
+ || new Set(bundle.messages.map(row => row.id)).size !== bundle.messages.length
+ || new Set(bundle.profiles.map(row => row.id)).size !== bundle.profiles.length
+ || new Set(bundle.memberships.map(row => `${row.channelId}:${row.userId}:${row.relation}`)).size !== bundle.memberships.length
+ || new Set(bundle.serverMemberships.map(row => `${row.serverId}:${row.userId}`)).size !== bundle.serverMemberships.length
+ || bundle.messages.some(row => !channels.has(row.channelId))
+ || bundle.servers.some(row => !bundle.serverMemberships.some(member => member.serverId === row.id && member.userId === bundle.viewerId))
+ || bundle.channels.some(row => !bundle.memberships.some(member => member.channelId === row.id && member.userId === bundle.viewerId && member.relation === "access"))
+ || bundle.channels.some(row => row.serverId !== null && !servers.has(row.serverId) || row.parentChannelId !== null && !channels.has(row.parentChannelId))
+ || bundle.memberships.some(row => row.userId !== bundle.viewerId || !channels.has(row.channelId))
+ || bundle.serverMemberships.some(row => row.userId !== bundle.viewerId || !servers.has(row.serverId))) ctx.addIssue({ code: "custom", message: "Resource bundle scope mismatch" })
+})
+export type CommunityResourceBundle = z.infer<typeof CommunityResourceBundleSchema>
+
export const CommunityChannelReadSchema = z.strictObject({ ...envelope, channel: CommunityChannelResourceSchema, access: CommunityAccessDecisionSchema })
-export const CommunityMessagesReadSchema = z.strictObject({ ...envelope, messages: z.array(CommunityMessageResourceSchema), page: CommunityPageSchema,
+export const CommunityMessagesReadSchema = CommunityMessageResourcesSchema.safeExtend({ ...envelope, page: CommunityPageSchema,
surfaceReceipt: z.strictObject({ channelId: id, surfaceKind: z.enum(["channel", "forum", "thread", "dm"]) }) })
-export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.extend({
+export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.safeExtend({
viewerId: id,
peer: CommunityResourceProfileSchema.nullable(),
channel: CommunityChannelResourceSchema,
@@ -197,6 +207,10 @@ export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.
anchorMessageId: nullableId,
}),
}).superRefine((entry, ctx) => {
+ if (entry.opener) {
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: [...entry.messages, entry.opener], profiles: entry.profiles })
+ if (!graph.success) for (const issue of graph.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message })
+ }
for (const [path, channelId] of [
[["channel", "id"], entry.channel.id],
[["access", "channelId"], entry.access.channelId],
@@ -226,50 +240,39 @@ export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.
if (entry.selection.reason === "read_pointer" && entry.selection.anchorMessageId !== entry.readState.lastReadMessageId) ctx.addIssue({ code: "custom", path: ["selection", "anchorMessageId"], message: "Conversation entry read pointer mismatch" })
if (entry.selection.reason === "read_pointer_missing" && entry.readState.lastReadMessageId === null) ctx.addIssue({ code: "custom", path: ["selection", "reason"], message: "Conversation entry missing read pointer" })
})
-export const CommunityMessagePostedSchema = CommunityMessagesReadSchema.pick({ contractVersion: true, channelId: true }).extend({
- message: CommunityMessageResourceSchema, deduped: z.boolean(), threadId: id.optional(),
+export const CommunityMessageReadSchema = z.strictObject({ ...envelope,
+ message: CommunityMessageResourceSchema, profiles: CommunityMessageResourcesSchema.shape.profiles,
+}).superRefine((read, ctx) => {
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: [read.message], profiles: read.profiles })
+ if (!graph.success) for (const issue of graph.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message })
})
-export const CommunityMessageReadSchema = CommunityMessagePostedSchema.omit({ deduped: true, threadId: true })
+export const CommunityMessagePostedSchema = CommunityMessageReadSchema.safeExtend({ deduped: z.boolean(), threadId: id.optional() })
export const CommunityMembersReadSchema = z.strictObject({ ...envelope, relation: z.enum(["access", "notify"]), members: z.array(CommunityMemberRelationSchema), profiles: z.array(CommunityResourceProfileSchema) })
export const CommunityThreadsReadSchema = z.strictObject({ ...envelope, channel: CommunityChannelResourceSchema,
threads: z.array(CommunityChannelResourceSchema),
- included: z.strictObject({ messages: z.array(CommunityMessageResourceSchema), members: z.array(CommunityMemberRelationSchema), profiles: z.array(CommunityResourceProfileSchema),
+ included: CommunityMessageResourcesSchema.safeExtend({ members: z.array(CommunityMemberRelationSchema),
tags: z.array(z.strictObject({ messageId: id, tag: z.string() })),
participantCounts: z.array(z.strictObject({ channelId: id, count: z.number().int().nonnegative() })) }),
page: z.strictObject({ nextCursor: z.string().nullable(), hasMore: z.boolean() }) })
export const CommunityReadAdvanceSchema = z.strictObject({ ...envelope, changed: z.boolean(), targetSeq: z.number().int().nonnegative(), revision: z.number().int().nonnegative() })
+export const CommunityInviteJoinTargetSchema = z.object({ serverId: CommunityServerResourceSchema.shape.id }).strip()
export const CommunityReadErrorSchema = z.strictObject({ contractVersion: z.literal(COMMUNITY_RESOURCE_CONTRACT_VERSION), error: z.strictObject({
code: z.enum(["invalid_input", "invalid_reply_target", "unauthenticated", "not_found", "not_allowed", "blocked", "idempotency_conflict", "rate_limited", "temporarily_unavailable"]),
- message: z.string(), retryable: z.boolean(),
+ message: z.string(), retryable: z.boolean(), details: z.array(z.string()).optional(),
}) })
-const legacyProfileSchema = CommunityResourceProfileSchema.pick({
- id: true, name: true, avatar: true, avatarVersion: true,
-}).extend({ discriminator: z.string().nullable(), statusEmoji: z.string().nullable(), statusText: z.string() })
-export const CommunityLegacyMessageResourceSchema = CommunityMessageResourceSchema.extend({ authorAvatar: z.string().optional(), attachments: z.array(CommunityLegacyMessageAttachmentSchema), thread: legacyMessageThreadSchema.optional() })
-const legacyEnvelope = { contractVersion: z.literal(2), channelId: id }
-const legacyReadSchemas = {
- channel: CommunityChannelReadSchema.extend(legacyEnvelope),
- messages: CommunityMessagesReadSchema.extend({ ...legacyEnvelope, messages: z.array(CommunityLegacyMessageResourceSchema) }),
- members: CommunityMembersReadSchema.extend({ ...legacyEnvelope, profiles: z.array(legacyProfileSchema) }),
- threads: CommunityThreadsReadSchema.extend({ ...legacyEnvelope, included: CommunityThreadsReadSchema.shape.included.extend({
- messages: z.array(CommunityLegacyMessageResourceSchema), profiles: z.array(legacyProfileSchema),
- }) }),
- readAdvance: CommunityReadAdvanceSchema.extend(legacyEnvelope),
- error: CommunityReadErrorSchema.extend({ contractVersion: z.literal(2) }),
-}
const resourceReadSchemas = {
channel: CommunityChannelReadSchema, messages: CommunityMessagesReadSchema,
members: CommunityMembersReadSchema, threads: CommunityThreadsReadSchema, readAdvance: CommunityReadAdvanceSchema, error: CommunityReadErrorSchema,
}
-export function communityReadSchemas(contract: 2): typeof legacyReadSchemas
-export function communityReadSchemas(contract: 3): typeof resourceReadSchemas
-export function communityReadSchemas(contract: 2 | 3): typeof legacyReadSchemas | typeof resourceReadSchemas
-export function communityReadSchemas(contract: 2 | 3) {
- return contract === 2 ? legacyReadSchemas : resourceReadSchemas
+export function communityReadSchemas(contract: number = COMMUNITY_RESOURCE_CONTRACT_VERSION) {
+ if (contract !== COMMUNITY_RESOURCE_CONTRACT_VERSION) throw new Error("Community resource protocol mismatch")
+ return resourceReadSchemas
}
+export type CommunityServerResource = z.infer<typeof CommunityServerResourceSchema>
+export type CommunityCategoryResource = z.infer<typeof CommunityCategoryResourceSchema>
export type CommunityChannelResource = z.infer<typeof CommunityChannelResourceSchema>
export type CommunityChannelIdentity = z.infer<typeof CommunityChannelIdentitySchema>
export type CommunityMessageResource = z.infer<typeof CommunityMessageResourceSchema>
@@ -278,77 +281,33 @@ export type CommunityReadStateResource = z.infer<typeof CommunityReadStateResour
export type CommunityAccessDecision = z.infer<typeof CommunityAccessDecisionSchema>
export type CommunityResourceProfile = z.infer<typeof CommunityResourceProfileSchema>
export type CommunityMessageAttachment = z.infer<typeof CommunityMessageAttachmentSchema>
-export type CommunityMessagePreview = z.infer<typeof CommunityMessagePreviewSchema>
-export type CommunityMessagePreviewAttachment = z.infer<typeof CommunityMessagePreviewAttachmentSchema>
-export type CommunityLegacyMessageAttachment = z.infer<typeof CommunityLegacyMessageAttachmentSchema>
+export type CommunityMessageRead = z.infer<typeof CommunityMessageReadSchema>
+export type CommunityMessagePosted = z.infer<typeof CommunityMessagePostedSchema>
+export type CommunityMessageResources = z.infer<typeof CommunityMessageResourcesSchema>
export type CommunityMessagesRead = z.infer<typeof CommunityMessagesReadSchema>
export type CommunityConversationEntryRead = z.infer<typeof CommunityConversationEntryReadSchema>
export type CommunityThreadsRead = z.infer<typeof CommunityThreadsReadSchema>
-export type CommunityLegacyThreadsRead = z.infer<typeof legacyReadSchemas.threads>
export type CommunityMembersRead = z.infer<typeof CommunityMembersReadSchema>
export type CommunityMessageSurfaceReceipt = CommunityMessagesRead["surfaceReceipt"]
-const legacyChannelResourcePreviewSchema = CommunityChannelResourceSchema.partial().strip().extend({
- archived: legacyArchivedSchema.optional(),
-})
-
-export function normalizeCommunityChannelResourcePreview(value: unknown): Partial<CommunityChannelResource> {
- return legacyChannelResourcePreviewSchema.parse(value)
-}
-
-const legacyChannelResourceSchema = CommunityChannelResourceSchema.strip().extend({
- topic: CommunityChannelResourceSchema.shape.topic.nullish().transform((value) => value ?? ""),
- position: CommunityChannelResourceSchema.shape.position.nullish().transform((value) => value ?? 0),
- messageCount: CommunityChannelResourceSchema.shape.messageCount.nullish().transform((value) => value ?? 0),
- categoryId: nullableId.default(null),
- parentChannelId: nullableId.default(null),
- parentMessageId: nullableId.default(null),
- creatorId: nullableId.default(null),
- lastMessageAt: CommunityChannelResourceSchema.shape.lastMessageAt.default(null),
- archived: legacyArchivedSchema,
-})
-
-export function normalizeCommunityChannelResource(value: unknown): CommunityChannelResource {
- return legacyChannelResourceSchema.parse(value)
-}
-
export function communityChannelResourceFromStorage(value: unknown): CommunityChannelResource {
- return CommunityChannelResourceSchema.strip().extend({ archived: legacyArchivedSchema }).parse(value)
+ return CommunityChannelResourceSchema.strip().extend({ archived: storedArchivedSchema }).parse(value)
}
-const legacyMessageResourceSchema = CommunityLegacyMessageResourceSchema.strip().extend({
- channelId: id.optional(),
- replyToId: nullableId.optional(),
- clientNonce: CommunityMessageResourceSchema.shape.clientNonce.default(null),
- attachments: CommunityLegacyMessageResourceSchema.shape.attachments.default([]),
- embeds: CommunityMessageResourceSchema.shape.embeds.nullable().transform((value) => value ?? undefined),
-})
-export function normalizeCommunityMessageResource(value: unknown, channelId: string) {
- const raw = legacyMessageResourceSchema.parse(value)
- if (raw.channelId !== undefined && raw.channelId !== channelId) throw new Error("Message resource scope mismatch")
- return { ...raw, channelId: id.parse(channelId), replyToId: raw.replyToId ?? raw.replyTo?.id ?? null }
+export function communityUserAvatarUrl(userId: string, avatarVersion?: number): string {
+ const base = `/api/community/users/${userId}/avatar`
+ return avatarVersion && avatarVersion > 0 ? `${base}?v=${avatarVersion}` : base
}
-export function communityMessagePreviewFromLegacy(value: unknown, channelId: string): CommunityMessagePreview {
- const input = typeof value === "object" && value !== null ? value as Record<string, unknown> : {}
- const message = normalizeCommunityMessageResource(value, channelId)
- const attachments = message.attachments.map(({ kind: _kind, size: _size, ...metadata }) => metadata)
- const preview = CommunityMessagePreviewSchema.parse({
- ...message,
- attachments: input.attachments === undefined ? undefined : attachments,
- clientNonce: input.clientNonce === undefined ? undefined : message.clientNonce,
- replyToId: input.replyToId === undefined ? message.replyTo?.id : input.replyToId,
- thread: message.thread ? {
- ...message.thread,
- participants: message.thread.participants?.map(({ avatar, name, ...identity }) => ({
- ...identity,
- ...(name ? { name } : {}),
- ...(avatar && avatar !== (name.trim().charAt(0) || "?").toUpperCase() ? { avatar } : {}),
- })),
- } : undefined,
- })
- return Object.fromEntries(Object.entries(preview).filter(([, field]) => field !== undefined)) as CommunityMessagePreview
+export function communityBotAvatarUrl(botId: string, avatarVersion?: number): string {
+ const base = `/api/community/bots/${botId}/avatar`
+ return avatarVersion && avatarVersion > 0 ? `${base}?v=${avatarVersion}` : base
}
-export type CommunityLegacyMessageResource = z.infer<typeof CommunityLegacyMessageResourceSchema>
+export function canonicalCommunityUserImage(userId: string, image: string | null, avatarVersion: number): string | null {
+ if (!image) return null
+ if (image === communityUserAvatarUrl(userId)) return communityUserAvatarUrl(userId, avatarVersion)
+ if (image === communityBotAvatarUrl(userId)) return communityBotAvatarUrl(userId, avatarVersion)
+ return image
+}
diff --git a/src/shared/src/community-ws-bundle.ts b/src/shared/src/community-ws-bundle.ts
index fa3ebd06f..08ac3d9f9 100644
--- a/src/shared/src/community-ws-bundle.ts
+++ b/src/shared/src/community-ws-bundle.ts
@@ -1,6 +1,8 @@
import {
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
decodeCommunityBrowserEvent,
+ validateCommunityWsEvent,
+ type CommunityBrowserEventEnvelope,
encodeCommunityBrowserEvent,
utf8ByteLength,
type CommunityWsEvent,
@@ -11,11 +13,10 @@ import { COMMUNITY_CONTRACT_VERSION, type CommunityContract } from "./community-
export const COMMUNITY_BROWSER_EVENT_BATCH_TYPE = "community:events.batch" as const
export function communityBrowserEventBatchType(contract: number = COMMUNITY_CONTRACT_VERSION) {
- if (contract === 1) return COMMUNITY_BROWSER_EVENT_BATCH_TYPE
- if (contract === 2) return `${COMMUNITY_BROWSER_EVENT_BATCH_TYPE}.v2` as const
- if (contract === 3) return `${COMMUNITY_BROWSER_EVENT_BATCH_TYPE}.v3` as const
- throw new Error("unsupported community event contract")
+ if (contract !== COMMUNITY_CONTRACT_VERSION) throw new Error("unsupported community event contract")
+ return `${COMMUNITY_BROWSER_EVENT_BATCH_TYPE}.v${COMMUNITY_CONTRACT_VERSION}` as const
}
+
export const COMMUNITY_DELIVERY_OPERATION_ID_PREFIX = "message:" as const
export const COMMUNITY_DELIVERY_OPERATION_ID_HEADER = "x-alook-community-operation-id" as const
export const COMMUNITY_DELIVERY_OPERATION_ID_BYTES = 51
@@ -36,13 +37,13 @@ export type CommunityBrowserEventBatch = {
wireDigest?: CommunityDeliveryDigest
operationId: CommunityDeliveryOperationId
operationDigest: CommunityDeliveryDigest
- events: CommunityWsEvent[]
+ events: CommunityBrowserEventEnvelope[]
}
export type PreparedCommunityDeliveryEvents = {
contract: CommunityContract
events: CommunityWsEvent[]
- envelopes: CommunityWsEvent[]
+ envelopes: CommunityBrowserEventEnvelope[]
bodies: string[]
digest: CommunityDeliveryDigest
}
@@ -196,16 +197,16 @@ export async function computeCommunityDeliveryDigestFromBodies(
export async function prepareCommunityDeliveryEvents(
values: readonly unknown[],
- contract: CommunityContract = 2,
+ contract: CommunityContract = COMMUNITY_CONTRACT_VERSION,
): Promise<CommunityDeliveryPrepareResult> {
if (values.length < 1 || values.length > MESSAGE_DELIVERY_MAX_EVENTS_PER_USER) {
return { ok: false, reason: "invalid-event-count" }
}
const events: CommunityWsEvent[] = []
- const envelopes: CommunityWsEvent[] = []
+ const envelopes: CommunityBrowserEventEnvelope[] = []
const bodies: string[] = []
for (let eventIndex = 0; eventIndex < values.length; eventIndex += 1) {
- const decoded = decodeCommunityBrowserEvent(values[eventIndex], contract)
+ const decoded = validateCommunityWsEvent(values[eventIndex], contract)
if (!decoded.ok) return { ok: false, reason: "invalid-child", eventIndex }
const encoded = encodeCommunityBrowserEvent(decoded.event, contract)
if (!encoded.ok) {
@@ -217,7 +218,7 @@ export async function prepareCommunityDeliveryEvents(
}
}
events.push(decoded.event)
- envelopes.push(encoded.event)
+ envelopes.push(encoded.envelope)
bodies.push(encoded.body)
}
return {
@@ -244,14 +245,14 @@ export async function encodeCommunityBrowserEventBatch(input: {
if (!isCommunityDeliveryDigest(input.operationDigest)) {
return { ok: false, reason: "invalid-operation-digest" }
}
- const prepared = await prepareCommunityDeliveryEvents(input.events, input.contract ?? 1)
+ const prepared = await prepareCommunityDeliveryEvents(input.events, input.contract ?? COMMUNITY_CONTRACT_VERSION)
if (!prepared.ok) return prepared
return encodePreparedCommunityBrowserEventBatch({
operationId: input.operationId,
operationDigest: input.operationDigest,
prepared: prepared.prepared,
- contract: input.contract ?? 1,
- ...(input.contract === 2 || input.contract === 3 ? { sourceDigest: prepared.prepared.digest } : {}),
+ contract: input.contract ?? COMMUNITY_CONTRACT_VERSION,
+ sourceDigest: prepared.prepared.digest,
})
}
@@ -276,13 +277,14 @@ export function encodePreparedCommunityBrowserEventBatch(input: {
}
}
if (input.sourceDigest !== undefined && !isCommunityDeliveryDigest(input.sourceDigest)) return { ok: false, reason: "invalid-operation-digest" }
- const contract = input.contract ?? 1
- if ((contract === 1) !== (input.sourceDigest === undefined) || (input.prepared.contract === 3) !== (contract === 3)) return { ok: false, reason: "invalid-contract" }
+ const contract = input.contract ?? COMMUNITY_CONTRACT_VERSION
+ if (contract !== COMMUNITY_CONTRACT_VERSION || input.prepared.contract !== COMMUNITY_CONTRACT_VERSION) return { ok: false, reason: "invalid-contract" }
+ if (input.sourceDigest !== undefined && input.sourceDigest !== input.prepared.digest) return { ok: false, reason: "digest-mismatch", actualDigest: input.prepared.digest }
const envelope = {
type: communityBrowserEventBatchType(contract),
operationId: input.operationId,
operationDigest: input.sourceDigest ?? input.operationDigest,
- ...(input.sourceDigest === undefined ? {} : { wireDigest: input.prepared.digest }),
+ wireDigest: input.prepared.digest,
}
const prefix = JSON.stringify(envelope).slice(0, -1)
const body = `${prefix},"events":[${input.prepared.bodies.join(",")}]}`
@@ -299,8 +301,8 @@ export function encodePreparedCommunityBrowserEventBatch(input: {
export function isCommunityBrowserEventBatchCandidate(
value: unknown,
-): value is Record<string, unknown> & { type: ReturnType<typeof communityBrowserEventBatchType> } {
- return isRecord(value) && ([1, 2, 3] as const).some((contract) => value.type === communityBrowserEventBatchType(contract))
+): value is Record<string, unknown> & { type: `community:events.batch${string}` } {
+ return isRecord(value) && typeof value.type === "string" && value.type.startsWith(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)
}
export function decodeCommunityBrowserEventBatch(
@@ -315,7 +317,7 @@ export function decodeCommunityBrowserEventBatch(
if (typeof value.type !== "string" || value.type.length === 0) {
return { ok: false, reason: "missing-type" }
}
- if (!([1, 2, 3] as const).some((contract) => value.type === communityBrowserEventBatchType(contract))) {
+ if (value.type !== communityBrowserEventBatchType()) {
return { ok: false, reason: "wrong-type" }
}
if (!isCommunityDeliveryOperationId(value.operationId)) {
@@ -324,11 +326,10 @@ export function decodeCommunityBrowserEventBatch(
if (!isCommunityDeliveryDigest(value.operationDigest)) {
return { ok: false, reason: "invalid-operation-digest" }
}
- const contract: CommunityContract = value.type === communityBrowserEventBatchType(3) ? 3 : value.type === communityBrowserEventBatchType(2) ? 2 : 1
- const current = contract !== 1
+ const contract = COMMUNITY_CONTRACT_VERSION
if (
- Object.keys(value).length !== (current ? 5 : 4)
- || (current && !isCommunityDeliveryDigest(value.wireDigest))
+ Object.keys(value).length !== 5
+ || !isCommunityDeliveryDigest(value.wireDigest)
|| !Object.hasOwn(value, "type")
|| !Object.hasOwn(value, "operationId")
|| !Object.hasOwn(value, "operationDigest")
@@ -344,20 +345,20 @@ export function decodeCommunityBrowserEventBatch(
return { ok: false, reason: "invalid-event-count" }
}
const events: CommunityWsEvent[] = []
- const envelopes: CommunityWsEvent[] = []
+ const envelopes: CommunityBrowserEventEnvelope[] = []
for (let eventIndex = 0; eventIndex < value.events.length; eventIndex += 1) {
const child = decodeCommunityBrowserEvent(value.events[eventIndex], contract)
if (!child.ok) {
return { ok: false, reason: "invalid-child", eventIndex }
}
events.push(child.event)
- envelopes.push(child.event)
+ envelopes.push({ ...child.event, schemaVersion: COMMUNITY_CONTRACT_VERSION })
}
return {
ok: true,
batch: {
type: communityBrowserEventBatchType(contract),
- ...(current ? { wireDigest: value.wireDigest as string } : {}),
+ wireDigest: value.wireDigest as string,
operationId: value.operationId,
operationDigest: value.operationDigest,
events: envelopes,
@@ -366,43 +367,10 @@ export function decodeCommunityBrowserEventBatch(
}
}
-export function projectCommunityEventForContract(event: CommunityWsEvent, contract: CommunityContract, sourceContract: CommunityContract = 2): CommunityWsEvent | null {
- let projected: unknown = event
- if (sourceContract === 3 && contract !== 3) {
- if (event.type === "community:message.create") {
- const decoded = decodeCommunityBrowserEvent(event, 3)
- if (!decoded.ok || decoded.event.type !== event.type) return null
- const { channelId: _channelId, thread: _thread, reactions: _reactions, ...message } = decoded.event.message
- projected = { ...event, message: {
- ...message,
- authorAvatar: message.authorAvatar ?? undefined, clientNonce: message.clientNonce ?? undefined,
- attachments: message.attachments.length ? message.attachments.map((attachment) => ({
- id: attachment.id, filename: attachment.name, url: attachment.url,
- thumbnailUrl: attachment.thumbnailUrl ?? undefined, contentType: attachment.contentType ?? undefined,
- size: attachment.sizeBytes ?? undefined, width: attachment.width, height: attachment.height,
- })) : undefined,
- } }
- } else if (event.type === "community:channel.create") {
- const channel = event.channel
- projected = { ...event, channel: { id: channel.id, name: channel.name ?? "", type: channel.type,
- categoryId: channel.categoryId, topic: channel.topic, position: channel.position, createdAt: channel.createdAt } }
- } else if (event.type === "community:channel.child_create") {
- const channel = event.channel
- projected = { ...event, channel: { id: channel.id, name: channel.name ?? "", type: channel.type,
- creatorId: channel.creatorId ?? undefined, createdAt: channel.createdAt } }
- } else if (event.type === "community:identity.update") {
- projected = { ...event, avatar: event.avatar ?? "" }
- }
- }
- const decoded = decodeCommunityBrowserEvent(projected, contract)
- if (!decoded.ok) return null
- const admitted = decoded.event
- if (contract !== 1) return admitted
- if (admitted.type === "community:friend.block") return { type: admitted.type, userId: admitted.userId }
- if (admitted.type !== "community:channel.membership.change") return admitted
- if (admitted.serverId === null) return null
- return { type: admitted.present ? "community:channel.member_add" : "community:channel.member_remove",
- serverId: admitted.serverId, channelId: admitted.channelId, userId: admitted.userId }
+export function projectCommunityEventForContract(event: CommunityWsEvent, contract: number, sourceContract: number = COMMUNITY_CONTRACT_VERSION): CommunityWsEvent | null {
+ if (contract !== COMMUNITY_CONTRACT_VERSION || sourceContract !== COMMUNITY_CONTRACT_VERSION) return null
+ const decoded = validateCommunityWsEvent(event)
+ return decoded.ok ? decoded.event : null
}
export async function encodeCommunityBrowserEventBatchForContract(input: {
@@ -411,17 +379,14 @@ export async function encodeCommunityBrowserEventBatchForContract(input: {
const source = await prepareCommunityDeliveryEvents(input.prepared.events, input.prepared.contract)
if (!source.ok) return source
if (source.prepared.digest !== input.prepared.digest) return { ok: false, reason: "digest-mismatch", actualDigest: source.prepared.digest }
- const events = input.prepared.events.map((event) => projectCommunityEventForContract(event, input.contract, input.prepared.contract))
- if (events.some((event) => event === null)) return { ok: false, reason: "invalid-child" }
- const wire = await prepareCommunityDeliveryEvents(events, input.contract)
- if (!wire.ok) return wire
- return encodePreparedCommunityBrowserEventBatch({ operationId: input.operationId, operationDigest: wire.prepared.digest,
- prepared: wire.prepared, contract: input.contract, ...(input.contract !== 1 ? { sourceDigest: input.prepared.digest } : {}) })
+ if (input.contract !== COMMUNITY_CONTRACT_VERSION || input.prepared.contract !== COMMUNITY_CONTRACT_VERSION) return { ok: false, reason: "invalid-contract" }
+ return encodePreparedCommunityBrowserEventBatch({ operationId: input.operationId, operationDigest: input.prepared.digest,
+ prepared: input.prepared, contract: input.contract, sourceDigest: input.prepared.digest })
}
export function admitCommunityBrowserEventBatch(value: unknown): CommunityBrowserEventBatchDecodeResult | Promise<CommunityBrowserEventBatchDecodeResult> {
const decoded = decodeCommunityBrowserEventBatch(value)
- if (!decoded.ok || decoded.batch.type === COMMUNITY_BROWSER_EVENT_BATCH_TYPE) return decoded
+ if (!decoded.ok) return decoded
return computeCommunityDeliveryDigestFromBodies((value as { events: unknown[] }).events.map((event) => JSON.stringify(event)))
- .then((digest) => digest === decoded.batch.wireDigest ? decoded : { ok: false, reason: "invalid-payload" })
+ .then((digest) => digest === decoded.batch.wireDigest && digest === decoded.batch.operationDigest ? decoded : { ok: false, reason: "invalid-payload" })
}
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index addd1753a..b7df6f46c 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -1,10 +1,11 @@
import { PiiResultSchema } from "./pii-contract"
import { z } from "zod"
-import type { CommunityContract } from "./community-contract"
+import { COMMUNITY_CONTRACT_VERSION } from "./community-contract"
+import { serverSchema } from "./community-cache"
import { CommunityMachineSummarySchema, RuntimeModelDiscoveryResultSchema } from "./schemas"
import { FriendApprovalPayloadSchema } from "./community-friend-approval"
import { BotCreationPayloadSchema } from "./community-bot-creation"
-import { CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "./community-resources"
+import { CommunityCategoryResourceSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMessageResourcesSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "./community-resources"
export { FriendApprovalPayloadSchema } from "./community-friend-approval"
export type { FriendApprovalPayload, FriendApprovalProfile } from "./community-friend-approval"
@@ -13,42 +14,16 @@ const string = z.string()
const nullableString = string.nullable()
const channelTypeSchema = CommunityChannelResourceSchema.shape.type.extract(["text", "forum"])
-const messageAttachmentSchema = z.strictObject({
- id: string,
- filename: string,
- url: string,
- thumbnailUrl: string.optional(),
- contentType: string.optional(),
- size: z.number().optional(),
- width: z.number().nullable().optional(),
- height: z.number().nullable().optional(),
-})
-
-const messageSchema = CommunityMessageResourceSchema.pick({
- content: true, type: true, systemKind: true, authorAvatar: true, authorAvatarVersion: true,
- mentionType: true, embeds: true, createdAt: true, approval: true, botCreation: true,
-}).extend({
- id: string,
- seq: z.number(),
- authorId: string,
- authorName: string,
- authorAvatar: string.optional(),
- authorAvatarVersion: CommunityMessageResourceSchema.shape.authorAvatarVersion.unwrap(),
- replyToId: nullableString.optional(),
- replyTo: CommunityMessageResourceSchema.shape.replyTo.unwrap().extend({
- id: string,
- authorId: string.optional(),
- }).optional(),
- attachments: z.array(messageAttachmentSchema).optional(),
- clientNonce: string.optional(),
-})
-
-export const CommunityLegacyMessageCreateSchema = z.strictObject({
+const communityMessageCreateSchema = z.strictObject({
type: z.literal("community:message.create"),
channelId: string,
serverId: string.optional(),
parentChannelId: string.optional(),
- message: messageSchema,
+ message: CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }),
+ profiles: CommunityMessageResourcesSchema.shape.profiles,
+}).refine(event => event.message.channelId === event.channelId).superRefine((event, ctx) => {
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: [event.message], profiles: event.profiles })
+ if (!graph.success) for (const issue of graph.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message })
})
const communityMessageUpdatedSchema = z.strictObject({
@@ -105,39 +80,18 @@ const communityTypingStopSchema = z.strictObject({
})
const communityChildChannelCreateSchema = z.strictObject({
- type: z.literal("community:channel.child_create"),
- parentChannelId: string,
- channel: z.strictObject({
- id: string,
- name: string,
- type: z.literal("thread"),
- creatorId: string.optional(),
- createdAt: string,
- }),
- parentMessageId: string.optional(),
-})
+ type: z.literal("community:channel.child_create"), parentChannelId: string,
+ channel: CommunityChannelResourceSchema.extend({ type: z.literal("thread") }), parentMessageId: string.optional(),
+}).refine(event => event.channel.parentChannelId === event.parentChannelId && (event.parentMessageId === undefined || event.parentMessageId === event.channel.parentMessageId))
const communityChildChannelUpdateSchema = z.strictObject({
- type: z.literal("community:channel.child_update"),
- parentChannelId: string,
- channelId: string,
- changes: z.strictObject({
- name: string.optional(),
- archived: z.boolean().optional(),
- tags: z.array(string).nullable().optional(),
- lastMessageAt: string.optional(),
- messageCount: z.number().optional(),
- }),
+ type: z.literal("community:channel.child_update"), parentChannelId: string, channelId: string,
+ changes: CommunityChannelResourceSchema.pick({ name: true, archived: true, lastMessageAt: true, messageCount: true }).partial().extend({ tags: z.array(string).nullable().optional() }),
})
const communityServerUpdateSchema = z.strictObject({
- type: z.literal("community:server.update"),
- serverId: string,
- changes: z.strictObject({
- name: string.optional(),
- description: string.optional(),
- icon: nullableString.optional(),
- }),
+ type: z.literal("community:server.update"), serverId: string,
+ changes: serverSchema.pick({ name: true, description: true, icon: true }).partial(),
})
const communityServerRailChangedSchema = z.strictObject({
@@ -150,29 +104,13 @@ const communityServerDeleteSchema = z.strictObject({
})
const communityChannelCreateSchema = z.strictObject({
- type: z.literal("community:channel.create"),
- serverId: string,
- channel: z.strictObject({
- id: string,
- name: string,
- type: channelTypeSchema,
- categoryId: nullableString.optional(),
- topic: string.optional(),
- position: z.number(),
- createdAt: string,
- }),
-})
+ type: z.literal("community:channel.create"), serverId: string,
+ channel: CommunityChannelResourceSchema.extend({ type: channelTypeSchema }),
+}).refine(event => event.channel.serverId === event.serverId)
const communityChannelUpdateSchema = z.strictObject({
- type: z.literal("community:channel.update"),
- serverId: string,
- channelId: string,
- changes: z.strictObject({
- name: string.optional(),
- topic: string.optional(),
- categoryId: nullableString.optional(),
- type: channelTypeSchema.optional(),
- }),
+ type: z.literal("community:channel.update"), serverId: string, channelId: string,
+ changes: CommunityChannelResourceSchema.pick({ name: true, topic: true, categoryId: true, type: true }).partial().extend({ type: channelTypeSchema.optional() }),
})
const communityChannelDeleteSchema = z.strictObject({
@@ -196,20 +134,6 @@ const communityChannelReorderSchema = z.strictObject({
channels: z.array(positionedIdSchema),
})
-const communityChannelMemberAddSchema = z.strictObject({
- type: z.literal("community:channel.member_add"),
- serverId: string,
- channelId: string,
- userId: string,
-})
-
-const communityChannelMemberRemoveSchema = z.strictObject({
- type: z.literal("community:channel.member_remove"),
- serverId: string,
- channelId: string,
- userId: string,
-})
-
const communityChannelMembershipChangeSchema = z.strictObject({
type: z.literal("community:channel.membership.change"),
channelId: string,
@@ -222,12 +146,7 @@ const communityChannelMembershipChangeSchema = z.strictObject({
const communityCategoryCreateSchema = z.strictObject({
type: z.literal("community:category.create"),
serverId: string,
- category: z.strictObject({
- id: string,
- name: string,
- position: z.number(),
- private: z.boolean(),
- }),
+ category: CommunityCategoryResourceSchema,
})
const communityCategoryUpdateSchema = z.strictObject({
@@ -256,15 +175,8 @@ const communityCategoryReorderSchema = z.strictObject({
const communityMemberJoinSchema = z.strictObject({
type: z.literal("community:member.join"),
serverId: string,
- member: z.strictObject({
- id: string,
- userId: string,
- name: string,
- discriminator: string,
- avatar: string.optional(),
- avatarVersion: z.number().int().nonnegative(),
- role: string,
- joinedAt: string,
+ member: CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatar: true, avatarVersion: true }).extend({
+ id: string, userId: string, role: string, joinedAt: string,
}),
})
@@ -319,7 +231,7 @@ const communityFriendBlockSchema = z.strictObject({
blockedByViewer: z.boolean().optional(),
})
-const communityInviteCreateSchema = z.strictObject({
+export const CommunityInviteCreateSchema = z.strictObject({
type: z.literal("community:invite.create"),
serverId: string,
invite: z.strictObject({
@@ -387,22 +299,13 @@ const communityStatusUpdateSchema = z.strictObject({
statusText: nullableString,
})
-const communityIdentityUpdateSchema = z.strictObject({
- type: z.literal("community:identity.update"),
- userId: string,
- avatar: string,
- avatarVersion: z.number().int().positive(),
+const communityIdentityUpdateSchema = CommunityResourceProfileSchema.pick({ avatar: true, avatarVersion: true }).extend({
+ type: z.literal("community:identity.update"), userId: string,
+ avatarVersion: CommunityResourceProfileSchema.shape.avatarVersion.refine(version => version > 0),
})
-const communityProfileUpdateSchema = z.strictObject({
- type: z.literal("community:profile.update"),
- userId: string,
- name: string,
- discriminator: string,
- aboutMe: string,
- bannerColor: nullableString,
- kind: z.enum(["human", "bot"]),
- ownerUserId: nullableString,
+const communityProfileUpdateSchema = CommunityResourceProfileSchema.pick({ name: true, discriminator: true, aboutMe: true, bannerColor: true, kind: true, ownerUserId: true }).required().extend({
+ type: z.literal("community:profile.update"), userId: string,
})
const communityMachineCreatedSchema = z.strictObject({
@@ -469,8 +372,6 @@ const commonCommunityEventSchemas = [
communityServerDeleteSchema,
communityChannelDeleteSchema,
communityChannelReorderSchema,
- communityChannelMemberAddSchema,
- communityChannelMemberRemoveSchema,
communityChannelMembershipChangeSchema,
communityCategoryCreateSchema,
communityCategoryUpdateSchema,
@@ -484,7 +385,7 @@ const commonCommunityEventSchemas = [
communityFriendRejectSchema,
communityFriendRemoveSchema,
communityFriendBlockSchema,
- communityInviteCreateSchema,
+ CommunityInviteCreateSchema,
communityMentionCreateSchema,
communityUnreadBumpSchema,
communityReadStateAdvancedSchema,
@@ -499,39 +400,20 @@ const commonCommunityEventSchemas = [
communityBotAuditEventSchema,
] as const
-const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
- ...commonCommunityEventSchemas, CommunityLegacyMessageCreateSchema, communityChildChannelCreateSchema,
+export const CommunityWsEventSchema = z.discriminatedUnion("type", [
+ ...commonCommunityEventSchemas, communityMessageCreateSchema, communityChildChannelCreateSchema,
communityChannelCreateSchema, communityChildChannelUpdateSchema, communityChannelUpdateSchema,
communityIdentityUpdateSchema, communityProfileUpdateSchema,
])
+export const CommunityResourceWsEventSchema = CommunityWsEventSchema
-const CommunityResourceWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
- ...commonCommunityEventSchemas,
- CommunityLegacyMessageCreateSchema.extend({ message: CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }) }).refine((event) => event.message.channelId === event.channelId),
- communityChildChannelCreateSchema.extend({ channel: CommunityChannelResourceSchema.extend({ type: z.literal("thread") }) })
- .refine((event) => event.channel.parentChannelId === event.parentChannelId && (event.parentMessageId === undefined || event.parentMessageId === event.channel.parentMessageId)),
- communityChannelCreateSchema.extend({ channel: CommunityChannelResourceSchema.extend({ type: channelTypeSchema }) })
- .refine((event) => event.channel.serverId === event.serverId),
- communityChildChannelUpdateSchema.extend({ changes: CommunityChannelResourceSchema.pick({ name: true, archived: true, lastMessageAt: true, messageCount: true }).partial()
- .extend({ tags: z.array(string).nullable().optional() }) }),
- communityChannelUpdateSchema.extend({ changes: CommunityChannelResourceSchema.pick({ name: true, topic: true, categoryId: true, type: true }).partial()
- .extend({ type: channelTypeSchema.optional() }) }),
- communityIdentityUpdateSchema.extend({ avatar: CommunityResourceProfileSchema.shape.avatar, avatarVersion: CommunityResourceProfileSchema.shape.avatarVersion.refine((version) => version > 0) }),
- CommunityResourceProfileSchema.pick({ name: true, discriminator: true, aboutMe: true, bannerColor: true, kind: true, ownerUserId: true }).required()
- .extend({ type: z.literal("community:profile.update"), userId: string }),
-])
-
-export function communityWsEventSchemaForContract(contract: CommunityContract) {
- return contract === 3 ? CommunityResourceWsEventSchema : CommunityWsEventSchema
+export function communityWsEventSchemaForContract(contract: number = COMMUNITY_CONTRACT_VERSION) {
+ if (contract !== COMMUNITY_CONTRACT_VERSION) throw new Error("Community event protocol mismatch")
+ return CommunityWsEventSchema
}
-export const CommunityWsEventSchema = CommunityWsEventDiscriminatedSchema
-export const CommunityResourceWsEventSchema = CommunityResourceWsEventDiscriminatedSchema
-
-export type CommunityLegacyWsEvent = z.infer<typeof CommunityWsEventSchema>
-export type CommunityResourceWsEvent = z.infer<typeof CommunityResourceWsEventSchema>
-export type CommunityWsEvent = CommunityLegacyWsEvent | CommunityResourceWsEvent
-export type CommunityLegacyMessageCreate = z.infer<typeof CommunityLegacyMessageCreateSchema>
+export type CommunityWsEvent = z.infer<typeof CommunityWsEventSchema>
+export type CommunityResourceWsEvent = CommunityWsEvent
export type CommunityMessageCreate = Extract<CommunityWsEvent, { type: "community:message.create" }>
export type CommunityMessageUpdated = Extract<CommunityWsEvent, { type: "community:message.updated" }>
export type CommunityReactionAdd = Extract<CommunityWsEvent, { type: "community:reaction.add" }>
@@ -549,8 +431,6 @@ export type CommunityChannelCreate = Extract<CommunityWsEvent, { type: "communit
export type CommunityChannelUpdate = Extract<CommunityWsEvent, { type: "community:channel.update" }>
export type CommunityChannelDelete = Extract<CommunityWsEvent, { type: "community:channel.delete" }>
export type CommunityChannelReorder = Extract<CommunityWsEvent, { type: "community:channel.reorder" }>
-export type CommunityChannelMemberAdd = Extract<CommunityWsEvent, { type: "community:channel.member_add" }>
-export type CommunityChannelMemberRemove = Extract<CommunityWsEvent, { type: "community:channel.member_remove" }>
export type CommunityChannelMembershipChange = Extract<CommunityWsEvent, { type: "community:channel.membership.change" }>
export type CommunityCategoryCreate = Extract<CommunityWsEvent, { type: "community:category.create" }>
export type CommunityCategoryUpdate = Extract<CommunityWsEvent, { type: "community:category.update" }>
@@ -621,8 +501,6 @@ export const WS_EVENTS = {
CHANNEL_UPDATE: "community:channel.update",
CHANNEL_DELETE: "community:channel.delete",
CHANNEL_REORDER: "community:channel.reorder",
- CHANNEL_MEMBER_ADD: "community:channel.member_add",
- CHANNEL_MEMBER_REMOVE: "community:channel.member_remove",
CHANNEL_MEMBERSHIP_CHANGE: "community:channel.membership.change",
CATEGORY_CREATE: "community:category.create",
CATEGORY_UPDATE: "community:category.update",
@@ -692,10 +570,13 @@ export type CommunityBrowserEventDecodeResult<Event = CommunityWsEvent> =
type: CommunityWsEvent["type"] | "unknown"
}
+export type CommunityBrowserEventEnvelope = CommunityWsEvent & { schemaVersion: typeof COMMUNITY_CONTRACT_VERSION }
+
export type CommunityBrowserEventEncodeResult<Event = CommunityWsEvent> =
| {
ok: true
event: Event
+ envelope: Event & { schemaVersion: typeof COMMUNITY_CONTRACT_VERSION }
body: string
byteLength: number
}
@@ -718,7 +599,7 @@ export function isCommunityEventType(value: unknown): value is CommunityWsEvent[
return typeof value === "string" && COMMUNITY_EVENT_TYPES.has(value)
}
-export function isCommunityEventCandidate(value: unknown): value is Record<string, unknown> & { type: string } {
+export function isCommunityEventCandidate(value: unknown): value is Record<string, unknown> & { type: `community:${string}` } {
return isRecord(value) && typeof value.type === "string" && value.type.startsWith("community:")
}
@@ -751,10 +632,8 @@ export function encodeCommunityUserTargetPathSegment(target: string): string {
return `${COMMUNITY_USER_TARGET_PATH_PREFIX}${encodeURIComponent(target)}`
}
-export function decodeCommunityBrowserEvent(value: unknown, contract: 3): CommunityBrowserEventDecodeResult<CommunityResourceWsEvent>
-export function decodeCommunityBrowserEvent(value: unknown, contract?: 1 | 2): CommunityBrowserEventDecodeResult<CommunityLegacyWsEvent>
-export function decodeCommunityBrowserEvent(value: unknown, contract: CommunityContract): CommunityBrowserEventDecodeResult
-export function decodeCommunityBrowserEvent(value: unknown, contract: CommunityContract = 2): CommunityBrowserEventDecodeResult {
+export function validateCommunityWsEvent(value: unknown, contract: number = COMMUNITY_CONTRACT_VERSION): CommunityBrowserEventDecodeResult {
+ if (contract !== COMMUNITY_CONTRACT_VERSION) return { ok: false, reason: "invalid-payload", type: "unknown" }
if (!isRecord(value)) return { ok: false, reason: "non-object", type: "unknown" }
if (typeof value.type !== "string" || value.type.length === 0) {
return { ok: false, reason: "missing-type", type: "unknown" }
@@ -771,18 +650,23 @@ export function decodeCommunityBrowserEvent(value: unknown, contract: CommunityC
return { ok: true, event: parsed.data }
}
-export function encodeCommunityBrowserEvent(value: unknown, contract: 3): CommunityBrowserEventEncodeResult<CommunityResourceWsEvent>
-export function encodeCommunityBrowserEvent(value: unknown, contract?: 1 | 2): CommunityBrowserEventEncodeResult<CommunityLegacyWsEvent>
-export function encodeCommunityBrowserEvent(value: unknown, contract: CommunityContract): CommunityBrowserEventEncodeResult
-export function encodeCommunityBrowserEvent(value: unknown, contract: CommunityContract = 2): CommunityBrowserEventEncodeResult {
+export function decodeCommunityBrowserEvent(value: unknown, contract: number = COMMUNITY_CONTRACT_VERSION): CommunityBrowserEventDecodeResult {
+ if (contract !== COMMUNITY_CONTRACT_VERSION || !isRecord(value) || value.schemaVersion !== COMMUNITY_CONTRACT_VERSION) return { ok: false, reason: "invalid-payload", type: "unknown" }
+ const { schemaVersion: _schemaVersion, ...event } = value
+ return validateCommunityWsEvent(event, contract)
+}
+
+export function encodeCommunityBrowserEvent(value: unknown, contract: number = COMMUNITY_CONTRACT_VERSION): CommunityBrowserEventEncodeResult {
+ if (contract !== COMMUNITY_CONTRACT_VERSION) return { ok: false, reason: "invalid-payload", type: "unknown" }
const parsed = communityWsEventSchemaForContract(contract).safeParse(value)
const type = isRecord(value) && isCommunityEventType(value.type) ? value.type : "unknown"
if (!parsed.success) return { ok: false, reason: "invalid-payload", type }
const event = parsed.data
- const body = JSON.stringify(event)
+ const envelope = { ...event, schemaVersion: COMMUNITY_CONTRACT_VERSION }
+ const body = JSON.stringify(envelope)
const byteLength = utf8ByteLength(body)
if (byteLength > COMMUNITY_BROWSER_EVENT_MAX_BYTES) {
return { ok: false, reason: "oversized", type: parsed.data.type, byteLength }
}
- return { ok: true, event, body, byteLength }
+ return { ok: true, event, envelope, body, byteLength }
}
diff --git a/src/shared/src/community/queue-task.ts b/src/shared/src/community/queue-task.ts
index 8d9d94f07..acc4c5141 100644
--- a/src/shared/src/community/queue-task.ts
+++ b/src/shared/src/community/queue-task.ts
@@ -21,7 +21,7 @@ export type QueueTaskRejectReason =
| "unknown_kind"
export type QueueTaskParseResult =
- | { ok: true; source: "legacy" | "v1"; task: AlookQueueTask }
+ | { ok: true; source: "v1"; task: AlookQueueTask }
| { ok: false; reason: QueueTaskRejectReason }
export type QueueTaskBatchParseResult =
@@ -48,28 +48,6 @@ function isNonEmptyId(value: unknown): value is string {
export function parseQueueTask(value: unknown): QueueTaskParseResult {
if (!isRecord(value)) return { ok: false, reason: "malformed" }
- const hasDiscriminator = hasOwn(value, "version") || hasOwn(value, "kind")
- if (!hasDiscriminator) {
- if (
- !hasExactKeys(value, ["messageId", "botUserId"])
- || !isNonEmptyId(value.messageId)
- || !isNonEmptyId(value.botUserId)
- ) {
- return { ok: false, reason: "malformed" }
- }
-
- return {
- ok: true,
- source: "legacy",
- task: {
- version: 1,
- kind: "bot-wake",
- messageId: value.messageId,
- botUserId: value.botUserId,
- },
- }
- }
-
if (!hasOwn(value, "version") || typeof value.version !== "number") {
return { ok: false, reason: "malformed" }
}
diff --git a/src/shared/src/db/queries/community/attachment.ts b/src/shared/src/db/queries/community/attachment.ts
index 9af62eebe..8ed076207 100644
--- a/src/shared/src/db/queries/community/attachment.ts
+++ b/src/shared/src/db/queries/community/attachment.ts
@@ -1,11 +1,10 @@
-import { and, asc, eq, exists, getTableColumns, inArray, isNull, ne, notExists, or, sql } from "drizzle-orm";
-import { alias } from "drizzle-orm/sqlite-core";
-import { communityAttachment, communityChannel, communityChannelMember, communityFriendship, communityMessage, communityMessageAttachment } from "../../community-schema";
+import { and, asc, eq, exists, getTableColumns, inArray, isNull, or, sql } from "drizzle-orm";
+import { communityAttachment, communityChannel, communityMessage, communityMessageAttachment } from "../../community-schema";
import { nanoid } from "nanoid";
import { user } from "../../schema";
import type { Database } from "../../index";
import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
-import { channelReadableSql } from "./channel";
+import { messageChannelReadableSql } from "./channel";
export async function createAttachment(db: Database, data: typeof communityAttachment.$inferInsert) {
const [row] = await db.insert(communityAttachment).select(db.select({
@@ -25,20 +24,11 @@ export async function createAttachment(db: Database, data: typeof communityAttac
}
export function attachmentReadableSql(db: Database, userId: string) {
- const peer = alias(communityChannelMember, "attachment_dm_peer");
- const hasPeer = db.select({ id: peer.id }).from(peer)
- .where(and(eq(peer.channelId, communityChannel.id), eq(peer.relation, "access"), ne(peer.userId, userId)));
- const blocked = db.select({ id: communityFriendship.id }).from(communityFriendship)
- .innerJoin(peer, and(eq(peer.channelId, communityChannel.id), eq(peer.relation, "access"), ne(peer.userId, userId)))
- .where(and(eq(communityFriendship.status, "blocked"), or(
- and(eq(communityFriendship.requesterId, userId), eq(communityFriendship.addresseeId, peer.userId)),
- and(eq(communityFriendship.addresseeId, userId), eq(communityFriendship.requesterId, peer.userId)),
- )));
const readableMessage = db.select({ id: communityMessage.id }).from(communityMessageAttachment)
.innerJoin(communityMessage, eq(communityMessage.id, communityMessageAttachment.messageId))
.innerJoin(communityChannel, eq(communityChannel.id, communityMessage.channelId))
.where(and(eq(communityMessageAttachment.attachmentId, communityAttachment.id),
- channelReadableSql(userId, { id: communityChannel.id, type: communityChannel.type, serverId: communityChannel.serverId, parentChannelId: communityChannel.parentChannelId }), or(ne(communityChannel.type, "dm"), and(exists(hasPeer), notExists(blocked)))));
+ messageChannelReadableSql(db, userId, { id: communityChannel.id, type: communityChannel.type, serverId: communityChannel.serverId, parentChannelId: communityChannel.parentChannelId })));
const activeActor = db.select({ id: user.id }).from(user)
.where(and(eq(user.id, userId), isNull(user.deletedAt)));
return and(exists(activeActor), or(eq(communityAttachment.uploaderId, userId), exists(readableMessage)))!;
diff --git a/src/shared/src/db/queries/community/attention.test.ts b/src/shared/src/db/queries/community/attention.test.ts
index b367c5432..31f5bf917 100644
--- a/src/shared/src/db/queries/community/attention.test.ts
+++ b/src/shared/src/db/queries/community/attention.test.ts
@@ -32,7 +32,7 @@ vi.mock("./mention", () => ({
}))
vi.mock("./server", () => ({ getServersByIds: mocks.getServersByIds }))
-import { DEFAULT_ATTENTION_ITEM_LIMIT, getAccountAttentionSnapshot } from "./attention"
+import { DEFAULT_ATTENTION_ITEM_LIMIT, getAccountAttentionProjection } from "./attention"
beforeEach(() => {
vi.clearAllMocks()
@@ -58,9 +58,9 @@ beforeEach(() => {
mocks.listThreadOpenersByChildIds.mockResolvedValue([])
})
-describe("getAccountAttentionSnapshot", () => {
+describe("getAccountAttentionProjection", () => {
it("uses the default limit and projects ordinary DM unread scopes", async () => {
- const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")
+ const snapshot = await getAccountAttentionProjection({} as never, "user_1")
expect(snapshot.limit).toBe(DEFAULT_ATTENTION_ITEM_LIMIT)
expect(snapshot.scopes).toEqual([{
@@ -101,7 +101,7 @@ describe("getAccountAttentionSnapshot", () => {
id: "s1", name: "Server", discriminator: "0001",
}])
- const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")
+ const snapshot = await getAccountAttentionProjection({} as never, "user_1")
expect(snapshot.included.channels).toEqual([])
expect(snapshot.scopes).toEqual([])
@@ -131,7 +131,7 @@ describe("getAccountAttentionSnapshot", () => {
id: "s2", name: "Other", discriminator: "0002",
}])
- const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")
+ const snapshot = await getAccountAttentionProjection({} as never, "user_1")
expect(snapshot.included.channels).toHaveLength(1)
expect(snapshot.scopes).toEqual([])
@@ -179,7 +179,7 @@ describe("getAccountAttentionSnapshot", () => {
id: "s1", name: "Server", discriminator: "0001",
}])
- const snapshot = await getAccountAttentionSnapshot({} as never, "user_1")
+ const snapshot = await getAccountAttentionProjection({} as never, "user_1")
expect(snapshot.scopes).toHaveLength(1)
expect(snapshot.items.filter((item) => item.kind === "forum_post")).toEqual([])
diff --git a/src/shared/src/db/queries/community/attention.ts b/src/shared/src/db/queries/community/attention.ts
index c1418d3b9..cfde9ddfa 100644
--- a/src/shared/src/db/queries/community/attention.ts
+++ b/src/shared/src/db/queries/community/attention.ts
@@ -1,5 +1,5 @@
import type {
- AccountAttentionSnapshot,
+ AccountAttentionProjection,
AttentionItem,
AttentionScope,
} from "../../../community-attention"
@@ -18,19 +18,19 @@ import { getServersByIds } from "./server"
export const DEFAULT_ATTENTION_ITEM_LIMIT = 100
export const MAX_ATTENTION_ITEM_LIMIT = 200
-type IncludedProfile = AccountAttentionSnapshot["included"]["profiles"][number]
-type IncludedMessage = AccountAttentionSnapshot["included"]["messages"][number]
+type IncludedProfile = AccountAttentionProjection["included"]["profiles"][number]
+type IncludedMessage = AccountAttentionProjection["included"]["messages"][number]
/**
* 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(
+export async function getAccountAttentionProjection(
db: Database,
userId: string,
requestedLimit = DEFAULT_ATTENTION_ITEM_LIMIT,
-): Promise<AccountAttentionSnapshot> {
+): Promise<AccountAttentionProjection> {
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([
@@ -148,7 +148,7 @@ export async function getAccountAttentionSnapshot(
userId: row.otherUserId,
name: row.otherUserName,
discriminator: row.otherUserDiscriminator,
- avatar: row.otherUserImage ?? "",
+ avatar: row.otherUserImage,
avatarVersion: row.otherUserAvatarVersion,
lastMessageAt: row.lastMessageAt,
lastUnreadSeq: row.lastUnreadSeq,
@@ -243,7 +243,7 @@ export async function getAccountAttentionSnapshot(
userId: row.author.id,
name: row.author.name,
discriminator: row.author.discriminator,
- avatar: row.author.image ?? "",
+ avatar: row.author.image,
avatarVersion: row.author.avatarVersion,
})
}
@@ -252,7 +252,7 @@ export async function getAccountAttentionSnapshot(
userId: row.otherUserId,
name: row.otherUserName,
discriminator: row.otherUserDiscriminator,
- avatar: row.otherUserImage ?? "",
+ avatar: row.otherUserImage,
avatarVersion: row.otherUserAvatarVersion,
})
}
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.ts
index a15806a37..defd481e2 100644
--- a/src/shared/src/db/queries/community/channel.ts
+++ b/src/shared/src/db/queries/community/channel.ts
@@ -18,6 +18,7 @@ import { formatHandle } from "../../../lib/discriminator";
import { user } from "../../schema";
import { chunk, D1_MAX_IN_PARAMS, maxInParams, maxRowsPerInsert } from "../_chunk";
import { jsonTextSet } from "../_json-set";
+import { dmPeerReadableSql } from "./dm";
import type { ChannelCategoryMove } from "../../../community-channel-order";
// Column selection shared by every read query.
@@ -109,6 +110,24 @@ export async function listReadableChannelsForUser(
return (await Promise.all(batches)).flat();
}
+export function messageChannelReadableSql(
+ db: Database,
+ userId: string,
+ channel: Parameters<typeof channelReadableSql>[1],
+) {
+ return and(channelReadableSql(userId, channel),
+ or(ne(channel.type, "dm"), dmPeerReadableSql(db, userId, channel.id)))!;
+}
+
+export async function listReadableMessageChannelsForUser(db: Database, userId: string, channelIds: readonly string[]) {
+ const ids = [...new Set(channelIds)];
+ if (!ids.length) return [];
+ return db.select(CHANNEL_COLUMNS).from(communityChannel).where(and(
+ inArray(communityChannel.id, jsonTextSet(db, ids)),
+ messageChannelReadableSql(db, userId, CHANNEL_COLUMNS),
+ ));
+}
+
export async function getReadableMessageChannelId(
db: Database,
userId: string,
@@ -593,6 +612,13 @@ export async function getServerRootChannelsByIds(db: Database, serverId: string,
));
}
+export async function listChannelMembershipsForUserInChannels(db: Database, userId: string, channelIds: string[]) {
+ return (await Promise.all(chunk([...new Set(channelIds)], D1_MAX_IN_PARAMS).map(ids =>
+ db.select({ channelId: communityChannelMember.channelId, userId: communityChannelMember.userId, relation: communityChannelMember.relation, source: communityChannelMember.source })
+ .from(communityChannelMember).where(and(eq(communityChannelMember.userId, userId), inArray(communityChannelMember.channelId, ids)))
+ ))).flat();
+}
+
export async function getChannelsByIds(db: Database, channelIds: string[]) {
if (channelIds.length === 0) return [];
// Hydration on the mentions/unreads paths passes up to a full page (200) of
diff --git a/src/shared/src/db/queries/community/dm.ts b/src/shared/src/db/queries/community/dm.ts
index 8800502cd..d3cce14d9 100644
--- a/src/shared/src/db/queries/community/dm.ts
+++ b/src/shared/src/db/queries/community/dm.ts
@@ -6,6 +6,7 @@ import { user } from "../../schema";
import { PARTICIPANT_SOURCE } from "../../../constants/community";
import { compareAsciiSqliteBinary } from "../../../lib/sqlite-binary";
import type { Database } from "../../index";
+import type { SQLWrapper } from "drizzle-orm";
function dmChannelQuery(
db: Database,
@@ -232,6 +233,9 @@ export async function listDMs(db: Database, userId: string) {
const rows = await db
.select({
id: communityChannel.id,
+ channel: communityChannel,
+ selfSource: selfMember.source,
+ peerSource: peerMember.source,
otherUserId: user.id,
otherUserName: user.name,
otherUserEmail: user.email,
@@ -337,3 +341,17 @@ export async function getDMPeer(
if (!other) return null;
return { otherUserId: other };
}
+
+
+export function dmPeerReadableSql(db: Database, userId: string, channelId: SQLWrapper) {
+ const peer = alias(communityChannelMember, "message_dm_peer");
+ const hasPeer = db.select({ id: peer.id }).from(peer)
+ .where(and(eq(peer.channelId, channelId), eq(peer.relation, "access"), ne(peer.userId, userId)));
+ const blocked = db.select({ id: communityFriendship.id }).from(communityFriendship)
+ .innerJoin(peer, and(eq(peer.channelId, channelId), eq(peer.relation, "access"), ne(peer.userId, userId)))
+ .where(and(eq(communityFriendship.status, "blocked"), or(
+ and(eq(communityFriendship.requesterId, userId), eq(communityFriendship.addresseeId, peer.userId)),
+ and(eq(communityFriendship.addresseeId, userId), eq(communityFriendship.requesterId, peer.userId)),
+ )));
+ return and(exists(hasPeer), notExists(blocked))!;
+}
diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.ts
index a8cd9b372..bca51b51a 100644
--- a/src/shared/src/db/queries/community/friendship.ts
+++ b/src/shared/src/db/queries/community/friendship.ts
@@ -15,6 +15,7 @@ import type {
FriendApprovalPayload,
FriendApprovalProfile,
} from "../../../community-ws-events";
+import { getResourceProfiles } from "./user-profile"
import { createOrGetDM } from "./dm";
import { createMessage, listMessagesReferencingFriendship } from "./message";
import { nanoid } from "nanoid";
@@ -441,17 +442,21 @@ export async function sendRequest(
});
const approval =
projectApproval(inserted, needsOwnerApproval, [botId, needsOwnerApproval], profiles) ?? undefined;
+ const [authorProfile] = await getResourceProfiles(db, [botId])
+ if (!authorProfile) throw new Error("Approval message author resource missing")
broadcasts.push({
userId: needsOwnerApproval,
event: {
type: WS_EVENTS.MESSAGE_CREATE,
channelId: dm.id,
+ profiles: [authorProfile],
message: {
id: msg.id,
+ channelId: dm.id, replyToId: null, clientNonce: null, attachments: [],
seq: msg.seq,
authorId: botId,
- authorName: botP?.name ?? "",
- authorAvatarVersion: botP?.avatarVersion ?? 0,
+ authorName: authorProfile.name,
+ authorAvatarVersion: authorProfile.avatarVersion,
content: msg.content,
type: "chat",
createdAt: msg.createdAt,
@@ -1138,17 +1143,21 @@ export async function ownerDecideOnRow(
});
const approval = projectApproval(updated, addresseeOwner, [row.addresseeId, addresseeOwner], profiles);
if (approval) {
+ const [authorProfile] = await getResourceProfiles(db, [row.addresseeId])
+ if (!authorProfile) throw new Error("Approval message author resource missing")
broadcasts.push({
userId: addresseeOwner,
event: {
type: WS_EVENTS.MESSAGE_CREATE,
channelId: dm.id,
+ profiles: [authorProfile],
message: {
id: msg.id,
+ channelId: dm.id, replyToId: null, clientNonce: null, attachments: [],
seq: msg.seq,
authorId: row.addresseeId,
- authorName: botP?.name ?? "",
- authorAvatarVersion: botP?.avatarVersion ?? 0,
+ authorName: authorProfile.name,
+ authorAvatarVersion: authorProfile.avatarVersion,
content: msg.content,
type: "chat",
createdAt: msg.createdAt,
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index 1fcdeec29..a9042b701 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -15,6 +15,7 @@ import { listParticipatingThreadIds } from "./thread";
import { listVisibleChannelIdsForUser } from "./channel";
import { reachIsParticipantSet } from "../../../utils/community-roles";
import { hasUnreadAttentionSql, notificationEligibleSql } from "./notification-eligibility";
+import { dmPeerReadableSql } from "./dm";
const ELIGIBLE_UNREAD_CHANNEL_CHUNK_SIZE = 80;
@@ -664,7 +665,8 @@ export async function listEligibleUnreadDms(
and(
eq(communityChannelMember.userId, userId),
eq(communityChannelMember.relation, "access"),
- eq(communityChannel.type, "dm")
+ eq(communityChannel.type, "dm"),
+ dmPeerReadableSql(db, userId, communityChannel.id)
)
);
const dmChannelIds = selfRows.map((row) => row.channelId);
diff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.ts
index efc7befc3..731d1e14e 100644
--- a/src/shared/src/db/queries/community/invite.ts
+++ b/src/shared/src/db/queries/community/invite.ts
@@ -1,5 +1,6 @@
import { and, eq, exists, gt, isNull, lt, or, sql } from "drizzle-orm";
import { nanoid } from "nanoid";
+import { CommunityResourceProfileSchema } from "../../../community-profile-resource";
import {
communityServerInvite,
communityServerMember,
@@ -113,6 +114,22 @@ export async function useInvite(
return null;
}
+ const userRows = await db
+ .select({
+ name: user.name,
+ image: user.image,
+ avatarVersion: user.avatarVersion,
+ discriminator: user.discriminator,
+ })
+ .from(user)
+ .where(eq(user.id, userId));
+ const userRow = userRows[0];
+
+ if (!userRow) return null;
+ CommunityResourceProfileSchema.pick({ name: true, discriminator: true, avatarVersion: true }).parse({
+ name: userRow.name, discriminator: userRow.discriminator, avatarVersion: userRow.avatarVersion,
+ });
+
// Consume capacity and create membership in one D1 batch. The INSERT itself
// re-checks expiry/quota inside the write transaction, so two users racing
// for the last use cannot both join. The UPDATE is gated on this request's
@@ -180,27 +197,15 @@ export async function useInvite(
const insertedMember = (batchResults[0] as Array<typeof communityServerMember.$inferSelect>)[0];
if (!insertedMember) return null;
- // Join the joined-user row so WS listeners can render name/avatar without
- // waiting for the next /members refetch.
- const userRows = await db
- .select({
- name: user.name,
- image: user.image,
- avatarVersion: user.avatarVersion,
- discriminator: user.discriminator,
- })
- .from(user)
- .where(eq(user.id, userId));
- const userRow = userRows[0];
return {
invite,
member: {
...insertedMember,
- userName: userRow?.name ?? "",
- userImage: userRow?.image ?? null,
- userAvatarVersion: userRow?.avatarVersion ?? 0,
- discriminator: userRow?.discriminator ?? null,
+ userName: userRow.name,
+ userImage: userRow.image,
+ userAvatarVersion: userRow.avatarVersion,
+ discriminator: userRow.discriminator,
},
};
}
diff --git a/src/shared/src/db/queries/community/user-profile.ts b/src/shared/src/db/queries/community/user-profile.ts
index ba16f176a..ee4a7e50c 100644
--- a/src/shared/src/db/queries/community/user-profile.ts
+++ b/src/shared/src/db/queries/community/user-profile.ts
@@ -1,4 +1,7 @@
-import { and, eq, isNotNull, isNull, or } from "drizzle-orm";
+import { CommunityResourceProfileSchema, canonicalCommunityUserImage } from "../../../community-resources"
+import { getUsersByIds } from "../user"
+import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
+import { and, inArray, eq, isNotNull, isNull, or } from "drizzle-orm";
import { alias } from "drizzle-orm/sqlite-core";
import { communityUserProfile } from "../../community-schema";
import { user } from "../../schema";
@@ -22,7 +25,7 @@ export type PublicProfileForViewer = {
aboutMe: string;
bannerColor: string | null;
statusEmoji: string | null;
- statusText: string;
+ statusText: string | null;
identity: PublicProfileIdentity;
};
@@ -98,11 +101,17 @@ export async function getPublicProfileForViewer(
aboutMe: row.aboutMe ?? "",
bannerColor: row.bannerColor ?? null,
statusEmoji: row.statusEmoji ?? null,
- statusText: row.statusText ?? "",
+ statusText: row.statusText,
identity,
};
}
+export async function getProfilesByUserIds(db: Database, userIds: string[]) {
+ return (await Promise.all(chunk([...new Set(userIds)], D1_MAX_IN_PARAMS).map(ids =>
+ db.select().from(communityUserProfile).where(inArray(communityUserProfile.userId, ids))
+ ))).flat();
+}
+
export async function getProfile(db: Database, userId: string) {
const rows = await db
.select()
@@ -128,7 +137,7 @@ export async function updateProfile(
aboutMe: data.aboutMe ?? "",
bannerColor: data.bannerColor ?? null,
statusEmoji: data.statusEmoji ?? null,
- statusText: data.statusText ?? "",
+ statusText: data.statusText === undefined ? "" : data.statusText,
})
.onConflictDoUpdate({
target: communityUserProfile.userId,
@@ -148,3 +157,15 @@ export async function updateProfile(
.returning();
return row!;
}
+
+
+export async function getResourceProfiles(db: Database, userIds: readonly string[]) {
+ const users = await getUsersByIds(db, [...new Set(userIds)])
+ const profileRows = await getProfilesByUserIds(db, users.map(row => row.id))
+ const profiles = new Map(profileRows.map(row => [row.userId, row]))
+ return users.map(row => CommunityResourceProfileSchema.parse({
+ id: row.id, name: row.name, discriminator: row.discriminator,
+ ...(profiles.has(row.id) ? { aboutMe: profiles.get(row.id)!.aboutMe, bannerColor: profiles.get(row.id)!.bannerColor, statusEmoji: profiles.get(row.id)!.statusEmoji, statusText: profiles.get(row.id)!.statusText } : {}),
+ avatar: canonicalCommunityUserImage(row.id, row.image, row.avatarVersion), avatarVersion: row.avatarVersion,
+ }))
+}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index c5667a3f0..fdf9ffb64 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -558,7 +558,6 @@ export {
export type {
MessageDeliveryBatch,
MessageDeliveryBatchParseResult,
- MessageDeliveryMemberAdded,
MessageDeliveryPartial,
} from "./community-message-delivery";
export type { DispatchOneWakeResult } from "./community/wake-dispatch";
@@ -609,8 +608,6 @@ export type {
CommunityChannelUpdate,
CommunityChannelDelete,
CommunityChannelReorder,
- CommunityChannelMemberAdd,
- CommunityChannelMemberRemove,
CommunityChannelMembershipChange,
CommunityCategoryCreate,
CommunityCategoryUpdate,
@@ -641,17 +638,16 @@ export type {
CommunityMachineRemoved,
CommunityBotAuditEvent,
CommunityWsEvent,
- CommunityLegacyWsEvent,
CommunityResourceWsEvent,
- CommunityLegacyMessageCreate,
+ CommunityBrowserEventEnvelope,
CommunityBrowserEventFailureReason,
CommunityBrowserEventDecodeResult,
CommunityBrowserEventEncodeResult,
} from "./community-ws-events";
export {
+ CommunityInviteCreateSchema,
CommunityWsEventSchema,
CommunityResourceWsEventSchema,
- CommunityLegacyMessageCreateSchema,
communityWsEventSchemaForContract,
FriendApprovalPayloadSchema,
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
@@ -664,6 +660,7 @@ export {
isValidCommunityUserTarget,
encodeCommunityUserTargetPathSegment,
utf8ByteLength,
+ validateCommunityWsEvent,
decodeCommunityBrowserEvent,
encodeCommunityBrowserEvent,
WS_EVENTS,
@@ -841,3 +838,19 @@ export { channelReorderRequestSchema, type ChannelReorderRequest, type ChannelCa
export type { PlatformMachineRequest, PlatformBotRequest } from "./community-platform";
export * from "./pii-contract";
+
+export * from "./business-schema-version";
+export * from "./task-payload-cache";
+export * from "./community-cache";
+
+export * from "./community-forum-sidebar";
+
+export * from "./community-machine-resources"
+
+export * from "./community-friends";
+
+export { CommunityInviteListItemSchema, CommunityInvitesReadSchema, type CommunityInviteListItem, type CommunityInvitesRead } from "./community-invites";
+
+export { CommunityDmReadItemSchema, CommunityDmsReadSchema, parseCommunityDmsRead, type CommunityDmsRead } from "./community-dms";
+
+export * from "./community-profile-reads"
diff --git a/src/shared/src/task-payload-cache.ts b/src/shared/src/task-payload-cache.ts
new file mode 100644
index 000000000..486bd24a4
--- /dev/null
+++ b/src/shared/src/task-payload-cache.ts
@@ -0,0 +1,10 @@
+import { z } from "zod"
+import { CommunityResourceProfileSchema } from "./community-resources"
+
+export const TaskEmailAddressCacheSchema = z.array(z.strictObject({
+ workspaceId: z.string().min(1), agentId: z.string().min(1), emailAddress: z.string(),
+}))
+export const TaskMemberInstructionCacheSchema = z.strictObject({
+ workspaceId: z.string().min(1), userId: z.string().min(1), globalInstruction: z.string(),
+}).nullable()
+export const TaskUserIdentityCacheSchema = CommunityResourceProfileSchema.pick({ id: true, name: true }).extend({ email: z.string() }).nullable()
diff --git a/src/shared/test/business-schema.contract.test.ts b/src/shared/test/business-schema.contract.test.ts
new file mode 100644
index 000000000..58178c483
--- /dev/null
+++ b/src/shared/test/business-schema.contract.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_BOT_ACTOR_HEADER, COMMUNITY_CONTRACT_HEADER, requestedCommunityContract } from "../src/index"
+import { CommunityMessageResourceSchema } from "../src/community-resources"
+import { communityCollectionSchemas } from "../src/community-cache"
+import { encodeCommunityBrowserEvent, decodeCommunityBrowserEvent } from "../src/community-ws-events"
+import { computeCommunityDeliveryDigestFromBodies, prepareCommunityDeliveryEvents, encodePreparedCommunityBrowserEventBatch, admitCommunityBrowserEventBatch } from "../src/community-ws-bundle"
+
+const message = () => CommunityMessageResourceSchema.parse({ id: "message", channelId: "channel", seq: 5, authorId: "author", createdAt: "2026-10-28T00:00:00Z", type: "chat", content: "current", replyToId: null, clientNonce: null, attachments: [], authorName: "Author", authorAvatar: null, authorAvatarVersion: 0 })
+const event = () => ({ type: "community:message.create" as const, channelId: "channel", message: message(), profiles: [{ id: "author", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }] })
+
+describe("one current business resource protocol", () => {
+ it("rejects missing and old request versions while accepting the shared current version", () => {
+ for (const version of [null, "1", "2", "3", "6", String(BUSINESS_SCHEMA_VERSION + 1)]) {
+ const headers = new Headers(version === null ? {} : { [COMMUNITY_CONTRACT_HEADER]: version })
+ expect(requestedCommunityContract(headers)).toBeNull()
+ }
+ expect(requestedCommunityContract(new Headers({ [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }))).toBe(BUSINESS_SCHEMA_VERSION)
+ })
+
+ it("admits complete nullable facts without markers and rejects partial or marker-shaped cached entities", () => {
+ expect(communityCollectionSchemas.messages.parse(message())).toEqual(message())
+ for (const invalid of [{ id: "message", type: "chat" }, { ...message(), resourceComplete: true }]) expect(communityCollectionSchemas.messages.safeParse(invalid).success).toBe(false)
+ expect(communityCollectionSchemas.profiles.safeParse({ id: "author", name: "Author", identityComplete: true }).success).toBe(false)
+ expect(communityCollectionSchemas.profiles.parse({ id: "author", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 })).toMatchObject({ avatar: null, discriminator: "0042" })
+ expect(communityCollectionSchemas.profiles.safeParse({ id: "author", name: "Author", discriminator: null, avatar: null, avatarVersion: 0 }).success).toBe(false)
+ })
+
+ it("validates full inner resources and requires an explicit current version at the wire boundary", () => {
+ const encoded = encodeCommunityBrowserEvent(event())
+ expect(encoded.ok).toBe(true)
+ if (!encoded.ok) throw new Error("Current event rejected")
+ expect(decodeCommunityBrowserEvent(JSON.parse(encoded.body))).toEqual({ ok: true, event: event() })
+ for (const invalid of [event(), { ...encoded.envelope, schemaVersion: 3 }, { ...encoded.envelope, message: { id: "message", type: "chat" } }]) expect(decodeCommunityBrowserEvent(invalid).ok).toBe(false)
+ expect(encodeCommunityBrowserEvent({ ...event(), message: { id: "message", type: "chat" } }).ok).toBe(false)
+ })
+
+ it("binds current batch frames to their full resource bytes and rejects downgraded names or tampering", async () => {
+ const prepared = await prepareCommunityDeliveryEvents([event()])
+ expect(prepared.ok).toBe(true)
+ if (!prepared.ok) throw new Error("Current delivery rejected")
+ const encoded = encodePreparedCommunityBrowserEventBatch({ operationId: `message:${"a".repeat(43)}`, operationDigest: prepared.prepared.digest, sourceDigest: prepared.prepared.digest, prepared: prepared.prepared })
+ expect(encoded.ok).toBe(true)
+ if (!encoded.ok) throw new Error("Current batch rejected")
+ expect((await admitCommunityBrowserEventBatch(JSON.parse(encoded.body))).ok).toBe(true)
+ expect((await admitCommunityBrowserEventBatch({ ...encoded.batch, type: "community:events.batch.v3" })).ok).toBe(false)
+ expect((await admitCommunityBrowserEventBatch({ ...encoded.batch, events: [{ ...encoded.batch.events[0], message: { ...message(), content: "tampered" } }] })).ok).toBe(false)
+ })
+ it.each(["operation-only", "wire-rehashed"] as const)("rejects current %s digest tampering", async mode => {
+ const prepared = await prepareCommunityDeliveryEvents([event()])
+ if (!prepared.ok) throw new Error("Current event rejected")
+ const encoded = encodePreparedCommunityBrowserEventBatch({ operationId: `message:${"b".repeat(43)}`, operationDigest: prepared.prepared.digest, prepared: prepared.prepared })
+ if (!encoded.ok) throw new Error("Current batch rejected")
+ const frame = JSON.parse(encoded.body)
+ if (mode === "operation-only") frame.operationDigest = "0".repeat(64)
+ else {
+ frame.events[0].message.content = "Changed bytes"
+ frame.wireDigest = await computeCommunityDeliveryDigestFromBodies(frame.events.map((row: unknown) => JSON.stringify(row)))
+ }
+ expect((await admitCommunityBrowserEventBatch(frame)).ok).toBe(false)
+ })
+
+})
+
+it("keeps bot selection independent from current business version admission", () => {
+ const headers = new Headers({ [COMMUNITY_BOT_ACTOR_HEADER]: "selected-bot" })
+ expect(requestedCommunityContract(headers)).toBeNull()
+ for (const version of ["2", "3"]) {
+ headers.set(COMMUNITY_CONTRACT_HEADER, version)
+ expect(requestedCommunityContract(headers)).toBeNull()
+ }
+ headers.set(COMMUNITY_CONTRACT_HEADER, String(BUSINESS_SCHEMA_VERSION))
+ expect(requestedCommunityContract(headers)).toBe(BUSINESS_SCHEMA_VERSION)
+})
diff --git a/src/shared/test/community-cache.test.ts b/src/shared/test/community-cache.test.ts
new file mode 100644
index 000000000..441bffa89
--- /dev/null
+++ b/src/shared/test/community-cache.test.ts
@@ -0,0 +1,11 @@
+import { expect, it } from "vitest"
+import { notificationSettingSchema } from "../src/community-cache"
+
+it("requires exactly one current notification target and preserves the chosen scope", () => {
+ const row = { id: "setting", level: "all" }
+ expect(notificationSettingSchema.parse({ ...row, serverId: "server" })).toEqual({ ...row, serverId: "server" })
+ expect(notificationSettingSchema.parse({ ...row, channelId: "channel", serverId: null })).toEqual({ ...row, channelId: "channel", serverId: null })
+ for (const target of [{}, { serverId: null, channelId: null }, { serverId: "server", channelId: "channel" }]) {
+ expect(notificationSettingSchema.safeParse({ ...row, ...target })).toMatchObject({ success: false, error: { issues: [expect.objectContaining({ message: "notification setting requires exactly one target" })] } })
+ }
+})
diff --git a/src/shared/test/community-dms.test.ts b/src/shared/test/community-dms.test.ts
new file mode 100644
index 000000000..8c068f816
--- /dev/null
+++ b/src/shared/test/community-dms.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest"
+import { CommunityDmsReadSchema, parseCommunityDmsRead } from "../src/community-dms"
+import { CommunityChannelResourceSchema, CommunityResourceProfileSchema } from "../src/community-resources"
+import { communityResourceChannelFixture } from "./community-ws-events.fixtures"
+
+const item = (id = "dm", peerId = "peer") => ({
+ id, userId: peerId, preview: "", activityAt: "2026-10-28T00:00:00Z", unread: false,
+ channel: { ...communityResourceChannelFixture, id, type: "dm", serverId: null, parentChannelId: null, parentMessageId: null, categoryId: null, name: null },
+ profile: { id: peerId, name: "Peer", discriminator: "0001", avatar: null, avatarVersion: 0 },
+ memberships: ["viewer", peerId].map(userId => ({ channelId: id, userId, relation: "access", source: "added", isCreator: false, role: null, memberId: null })),
+})
+
+describe("named complete current DM read", () => {
+ it("uses the unique complete resource schemas and keeps the DTO independent from UI identity", () => {
+ const shape = CommunityDmsReadSchema.shape.conversations.element.shape
+ expect(shape.channel).toBe(CommunityChannelResourceSchema)
+ expect(shape.profile).toBe(CommunityResourceProfileSchema)
+ const value = { conversations: [item()] }
+ expect(parseCommunityDmsRead(value, "viewer")).toEqual(value)
+ expect(Object.keys(value.conversations[0]!)).not.toContain("name")
+ expect(parseCommunityDmsRead({ conversations: [] }, "viewer")).toEqual({ conversations: [] })
+ })
+ it.each(["name", "discriminator", "avatar", "avatarVersion"])("refuses the second %s identity source", key => {
+ expect(() => parseCommunityDmsRead({ conversations: [{ ...item(), [key]: "duplicate" }] }, "viewer")).toThrow()
+ })
+ it.each(["avatar", "avatarVersion", "name", "discriminator"])("refuses a missing full profile %s", key => {
+ const value = item()
+ delete (value.profile as Record<string, unknown>)[key]
+ expect(() => parseCommunityDmsRead({ conversations: [value] }, "viewer")).toThrow()
+ })
+ it.each(["peer", "channel", "member-channel", "member-relation", "viewer", "self-peer", "foreign-parent", "foreign-category", "foreign-opener"])("rejects mismatched %s closure", kind => {
+ const value = item()
+ if (kind === "peer") value.profile.id = "other"
+ if (kind === "channel") value.channel.id = "other"
+ if (kind === "member-channel") value.memberships[1]!.channelId = "other"
+ if (kind === "member-relation") value.memberships[1]!.relation = "notify"
+ if (kind === "viewer") value.memberships[0]!.userId = "other-viewer"
+ if (kind === "foreign-parent") Object.assign(value.channel, { parentChannelId: "foreign" })
+ if (kind === "foreign-category") Object.assign(value.channel, { categoryId: "foreign" })
+ if (kind === "foreign-opener") Object.assign(value.channel, { parentMessageId: "foreign" })
+ if (kind === "self-peer") value.userId = value.profile.id = "viewer"
+ expect(() => parseCommunityDmsRead({ conversations: [value] }, "viewer")).toThrow()
+ })
+ it("rejects duplicate DM identities and inconsistent unread metadata", () => {
+ expect(() => parseCommunityDmsRead({ conversations: [item(), item()] }, "viewer")).toThrow()
+ expect(() => parseCommunityDmsRead({ conversations: [{ ...item(), unread: true }] }, "viewer")).toThrow()
+ expect(() => parseCommunityDmsRead({ conversations: [{ ...item(), lastUnreadSeq: 1 }] }, "viewer")).toThrow()
+ expect(parseCommunityDmsRead({ conversations: [{ ...item(), unread: true, lastUnreadSeq: 1 }] }, "viewer").conversations[0]!.lastUnreadSeq).toBe(1)
+ })
+})
diff --git a/src/shared/test/community-forum-sidebar.test.ts b/src/shared/test/community-forum-sidebar.test.ts
new file mode 100644
index 000000000..2e275df23
--- /dev/null
+++ b/src/shared/test/community-forum-sidebar.test.ts
@@ -0,0 +1,41 @@
+import { expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION } from "../src/business-schema-version"
+import { CommunityForumSidebarEnvelopeSchema } from "../src/community-forum-sidebar"
+import { CommunityResourceBundleSchema } from "../src/community-resources"
+import { communityResourceChannelFixture, communityResourceMessageFixture } from "./community-ws-events.fixtures"
+
+const parent = { ...communityResourceChannelFixture, id: "forum", type: "forum" as const }
+function fixture() {
+ const channel = { ...communityResourceChannelFixture, id: "post", type: "thread" as const, parentChannelId: parent.id, parentMessageId: "opener" }
+ const summary = { id: channel.id, name: channel.name, serverId: channel.serverId!, parentChannelId: parent.id, parentMessageId: "opener", activityAt: "2026-10-28T00:00:00Z", expiresAt: "2026-10-31T00:00:00Z", unread: false }
+ return { schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: "server-1", channels: [summary], canonicalChannels: [summary], retainedChannel: null as typeof summary | null, retainedDisposition: null as "eligible" | "genuine-negative" | null, serverNow: "2026-10-28T00:00:00Z",
+ resources: CommunityResourceBundleSchema.parse({ viewerId: "viewer", servers: [{ id: "server-1", position: 0, name: "Server", discriminator: "0042", description: "", ownerId: "viewer", icon: null, official: false, isOwner: true }], serverMemberships: [{ serverId: "server-1", userId: "viewer", memberId: "viewer-member", role: "owner" }], channels: [parent, channel], profiles: communityResourceMessageFixture.profiles, messages: [{ ...communityResourceMessageFixture.message, id: "opener", channelId: "forum" }], memberships: [ ...[parent, channel].map(row => ({ channelId: row.id, userId: "viewer", relation: "access", source: "explicit" })), { channelId: "post", userId: "viewer", relation: "notify", source: "spoke" }] }) }
+}
+it.each([false, true])("keeps canonical and retained sidebar closure: retained=%s", retained => {
+ const value = fixture()
+ if (retained) { value.canonicalChannels = []; value.retainedChannel = value.channels[0]!; value.retainedDisposition = "eligible" }
+ expect(CommunityForumSidebarEnvelopeSchema.parse(value)).toEqual(value)
+})
+it.each(["foreign-server", "foreign-channel", "duplicate-visible", "duplicate-canonical", "parent-budget", "unselected", "retained-disposition", "wrong-type", "wrong-parent", "wrong-opener", "missing-opener", "foreign-opener", "missing-notify", "wrong-viewer", "access-is-not-notify"])("rejects broken sidebar closure: %s", defect => {
+ const value = fixture()
+ if (defect === "foreign-server") { value.resources.servers.push({ id: "foreign", position: 0, name: "Foreign", discriminator: "0042", description: "", ownerId: "viewer", icon: null, official: false, isOwner: false }); value.resources.serverMemberships.push({ serverId: "foreign", userId: "viewer", memberId: "foreign-member", role: "member" }) }
+ if (defect === "foreign-channel") value.resources.channels[0]!.serverId = null
+ if (defect === "duplicate-visible") value.channels.push(value.channels[0]!)
+ if (defect === "duplicate-canonical") value.canonicalChannels.push(value.canonicalChannels[0]!)
+ if (defect === "parent-budget") value.canonicalChannels = Array.from({ length: 6 }, (_, i) => ({ ...value.canonicalChannels[0]!, id: `post-${i}` }))
+ if (defect === "unselected") value.channels[0] = { ...value.channels[0]!, id: "unselected" }
+ if (defect === "retained-disposition") value.retainedDisposition = "eligible"
+ if (defect === "wrong-type") value.resources.channels[1]!.type = "text"
+ if (defect === "wrong-parent") value.resources.channels[1]!.parentChannelId = "foreign"
+ if (defect === "wrong-opener") value.resources.channels[1]!.parentMessageId = "foreign"
+ if (defect === "missing-opener") value.resources.messages = []
+ if (defect === "foreign-opener") value.resources.messages[0]!.channelId = "foreign"
+ if (defect === "missing-notify") value.resources.memberships = value.resources.memberships.filter(row => row.relation !== "notify")
+ if (defect === "wrong-viewer") value.resources.memberships[0]!.userId = "foreign"
+ if (defect === "access-is-not-notify") value.resources.memberships = value.resources.memberships.filter(row => row.relation !== "notify")
+ if (defect === "wrong-parent" || defect === "foreign-opener") {
+ value.resources.channels.push({ ...parent, id: "foreign" })
+ value.resources.memberships.push({ channelId: "foreign", userId: "viewer", relation: "access", source: "explicit" })
+ }
+ expect(CommunityForumSidebarEnvelopeSchema.safeParse(value)).toMatchObject({ success: false, error: { issues: expect.arrayContaining([expect.objectContaining({ message: defect === "wrong-viewer" ? "Resource bundle scope mismatch" : "Forum sidebar resource closure mismatch" })]) } })
+})
diff --git a/src/shared/test/community-message-delivery.test.ts b/src/shared/test/community-message-delivery.test.ts
index 40ec539b0..ffcbc11ce 100644
--- a/src/shared/test/community-message-delivery.test.ts
+++ b/src/shared/test/community-message-delivery.test.ts
@@ -1,13 +1,15 @@
+import { BUSINESS_SCHEMA_VERSION } from "../src/business-schema-version";
import { describe, expect, it } from "vitest";
import { parseMessageDeliveryBatch } from "../src/community-message-delivery";
const messageEvent = {
type: "community:message.create" as const,
+ profiles: [{ id: "u1", name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 }],
channelId: "thread-1",
serverId: "server-1",
parentChannelId: "forum-1",
message: {
- id: "message-1",
+ id: "message-1", channelId: "thread-1", replyToId: null, clientNonce: null, attachments: [],
seq: 4,
authorId: "u1",
authorName: "Alice",
@@ -19,13 +21,13 @@ const messageEvent = {
};
const valid = {
+ communityContract: BUSINESS_SCHEMA_VERSION,
messageId: "message-1",
messageEvent,
contentUserIds: ["u1", "u2"],
unreadPlainUserIds: [],
unreadMentionUserIds: ["u2"],
mentionUserIds: ["u2"],
- memberAdded: { userId: "u1", serverId: "server-1", channelId: "thread-1" },
parentProjection: {
type: "community:channel.child_update" as const,
parentChannelId: "forum-1",
@@ -68,8 +70,8 @@ describe("message delivery batch", () => {
{ ...valid, unreadPlainUserIds: ["outside"] },
{ ...valid, unreadPlainUserIds: ["u2"], unreadMentionUserIds: ["u2"] },
{ ...valid, parentProjectionUserIds: undefined },
- { ...valid, memberAdded: { ...valid.memberAdded, channelId: "other" } },
- { ...valid, memberAdded: { ...valid.memberAdded, serverId: "other" } },
+ { ...valid, memberAdded: { userId: "u1", serverId: "server-1", channelId: "other" } },
+ { ...valid, memberAdded: { userId: "u1", serverId: "other", channelId: "thread-1" } },
{
...valid,
messageEvent: { ...messageEvent, serverId: undefined, parentChannelId: undefined },
diff --git a/src/shared/test/community-profile-reads.test.ts b/src/shared/test/community-profile-reads.test.ts
new file mode 100644
index 000000000..bc4b371fa
--- /dev/null
+++ b/src/shared/test/community-profile-reads.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest"
+import { CommunityResourceProfileSchema } from "../src/community-resources"
+import { CommunitySelfProfileReadSchema, CommunityServerMemberReadSchema, CommunityUserSearchReadSchema, parseCommunitySelfProfileRead, parseCommunityUserCardRead, parseCommunityServerMembersRead } from "../src/community-profile-reads"
+
+const self = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 0, aboutMe: "", bannerColor: null, statusEmoji: null, statusText: null }
+const { avatar, ...core } = self
+const card = { ...core, image: avatar, mutualServers: 0, kind: "human" }
+const member = { id: "membership", userId: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 0, role: "member", sub: "", status: "online", statusEmoji: null, statusText: "" }
+const page = { viewerId: "viewer", serverId: "server", members: [member], hasMore: false, limit: 50, total: 1 }
+
+describe("named complete and subset profile reads", () => {
+ it("derives field validators from the unique profile resource", () => {
+ expect(CommunitySelfProfileReadSchema.shape.avatarVersion.unwrap()).toBe(CommunityResourceProfileSchema.shape.avatarVersion)
+ expect(CommunityServerMemberReadSchema.shape.avatar.unwrap()).toBe(CommunityResourceProfileSchema.shape.avatar)
+ expect(parseCommunitySelfProfileRead(self, "viewer")).toEqual(self)
+ expect(parseCommunityUserCardRead(card, "viewer", "other")).toEqual(card)
+ expect(parseCommunityServerMembersRead(page, "server", "viewer", false)).toEqual(page)
+ const { total: _total, ...search } = page
+ expect(parseCommunityServerMembersRead(search, "server", "viewer", true)).toEqual(search)
+ expect(CommunityUserSearchReadSchema.parse({ users: [{ id: "viewer", name: "Viewer", discriminator: "0042", image: null, avatarVersion: 0 }] }).users[0]!.image).toBeNull()
+ })
+ it.each(Object.keys(self))("requires complete self field %s", key => {
+ const input: Record<string, unknown> = { ...self }; delete input[key]
+ expect(() => parseCommunitySelfProfileRead(input, "viewer")).toThrow()
+ })
+ it("binds self and card identity plus viewer-relative bot ownership", () => {
+ expect(() => parseCommunitySelfProfileRead(self, "foreign")).toThrow()
+ expect(() => parseCommunityUserCardRead(card, "foreign", "viewer")).toThrow()
+ const bot = { ...card, kind: "bot", ownerProfile: { id: "owner", handle: "Owner#0042" }, ownedByViewer: true }
+ expect(parseCommunityUserCardRead(bot, "viewer", "owner")).toEqual(bot)
+ expect(() => parseCommunityUserCardRead(bot, "viewer", "foreign")).toThrow()
+ expect(() => parseCommunityUserCardRead({ ...bot, ownerProfile: { id: "owner" } }, "viewer", "owner")).toThrow()
+ })
+ it.each(["server", "viewer", "later-core", "duplicate-member", "duplicate-user", "cursor", "owned-bot", "oversized"])("refuses the entire member page for %s", defect => {
+ const input = structuredClone(page)
+ if (defect === "server") input.serverId = "foreign"
+ if (defect === "viewer") input.viewerId = "foreign"
+ if (defect === "later-core") input.members.push({ ...member, id: "second", userId: "second", avatarVersion: undefined } as never)
+ if (defect === "duplicate-member") input.members.push({ ...member, userId: "second" })
+ if (defect === "duplicate-user") input.members.push({ ...member, id: "second" })
+ if (defect === "cursor") input.hasMore = true
+ if (defect === "owned-bot") Object.assign(input.members[0]!, { isBot: true, ownerUserId: "foreign" })
+ if (defect === "oversized") input.limit = 0
+ expect(() => parseCommunityServerMembersRead(input, "server", "viewer", false)).toThrow()
+ })
+})
+
+it("keeps bot catalog identity summaries distinct from valid partial command fields", async () => {
+ const { CommunityBotProfileSummarySchema, parseCommunityBotsProfileRead } = await import("../src/community-profile-reads")
+ const patch = { id: "bot", name: "Bot", image: null, avatarVersion: 1 }
+ expect(CommunityBotProfileSummarySchema.parse(patch)).toEqual(patch)
+ const row = { ...patch, discriminator: "0042", description: "Actual instruction", presence: "offline", ownerUserId: "viewer" }
+ expect(parseCommunityBotsProfileRead({ bots: [row], plan: { id: "free" } }, "viewer")).toEqual({ bots: [row] })
+ for (const value of [{ bots: [row, row] }, { bots: [{ ...row, ownerUserId: "foreign" }] }, { bots: [patch] }, { bots: [{ ...row, image: undefined }] }]) expect(() => parseCommunityBotsProfileRead(value, "viewer")).toThrow()
+})
+
+it("binds the named reaction actor subset to the actual requested message scope", async () => {
+ const { parseCommunityReactionDetailsRead } = await import("../src/community-profile-reads")
+ const scope = { kind: "server", serverId: "server", channelId: "channel" } as const
+ const profile = { id: "actor", name: "Actor", discriminator: "0042", avatar: null, avatarVersion: 0 }
+ const value = { messageId: "message", scope, actors: [{ userId: "actor", profile }, { userId: "deleted", profile: null }] }
+ expect(parseCommunityReactionDetailsRead(value, "message", scope)).toEqual(value)
+ for (const changed of [{ messageId: "foreign" }, { scope: { ...scope, serverId: "foreign" } }, { scope: { ...scope, channelId: "foreign" } }, { scope: { kind: "dm", channelId: "channel" } }, { actors: [{ userId: "foreign", profile }] }, { actors: [{ userId: "actor", profile }, { userId: "actor", profile }] }]) expect(() => parseCommunityReactionDetailsRead({ ...value, ...changed }, "message", scope)).toThrow()
+ const dm = { kind: "dm", channelId: "dm" } as const
+ expect(parseCommunityReactionDetailsRead({ ...value, scope: dm }, "message", dm).scope).toEqual(dm)
+})
diff --git a/src/shared/test/community-resources.contract.test.ts b/src/shared/test/community-resources.contract.test.ts
index 6b83d7bb4..c53fa581f 100644
--- a/src/shared/test/community-resources.contract.test.ts
+++ b/src/shared/test/community-resources.contract.test.ts
@@ -1,99 +1,51 @@
import { describe, expect, it } from "vitest"
-import { communityMessagePreviewFromLegacy, CommunityLegacyMessageResourceSchema, communityChannelResourceFromStorage, CommunityMessageAttachmentSchema, CommunityMessagePreviewSchema, CommunityResourceProfileSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, normalizeCommunityChannelIdentity, normalizeCommunityChannelResource, normalizeCommunityChannelResourcePreview, normalizeCommunityMessageResource } from "../src"
+import { BUSINESS_SCHEMA_VERSION, communityChannelResourceFromStorage, CommunityMessageAttachmentSchema, CommunityResourceProfileSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema } from "../src"
import { communityResourceChannelFixture, communityResourceMessageFixture } from "./community-ws-events.fixtures"
import { COMMUNITY_CONTRACT_HEADER, requestsCommunityContract } from "../src/community-contract"
-import { CommunityConversationEntryReadSchema, communityReadSchemas, type CommunityChannelResource } from "../src/community-resources"
-
-describe("common community resources", () => {
- it.each([2, 3] as const)("selects read contract %s without accepting the other version", (contractVersion) => {
- const schemas = communityReadSchemas(contractVersion)
- const body = { contractVersion, channelId: "channel", changed: true, targetSeq: 7, revision: 9 }
- expect(schemas.readAdvance.parse(body)).toEqual(body)
- expect(schemas.readAdvance.safeParse({ ...body, contractVersion: contractVersion === 2 ? 3 : 2 }).success).toBe(false)
- expect(schemas.error.parse({ contractVersion, error: { code: "not_allowed", message: "Denied", retryable: false } }))
- .toEqual({ contractVersion, error: { code: "not_allowed", message: "Denied", retryable: false } })
- })
- it.each([undefined, "1", "2", "02", "3"])("negotiates only the exact supported read contract %s", (version) => {
- const headers = new Headers(version === undefined ? undefined : { [COMMUNITY_CONTRACT_HEADER]: version })
- expect(requestsCommunityContract(headers)).toBe(version === "2" || version === "3")
- })
- it.each(["text", "forum", "thread", "dm"] as const)("normalizes the %s channel without inventing an owner", (type) => {
- const channel = normalizeCommunityChannelResource({ id: "channel", type, serverId: type === "dm" ? null : "server", name: type === "dm" ? null : "Channel",
- archived: 0, createdAt: "2026-10-07T12:00:00Z" })
- expect(channel).toMatchObject({ type, archived: false, parentChannelId: null, parentMessageId: null, categoryId: null, creatorId: null, lastMessageAt: null, messageCount: 0 })
- expect(CommunityChannelResourceSchema.safeParse({ ...channel, pending: true }).success).toBe(false)
- })
- it("validates legacy channel identity without requiring full-read fields", () => {
- const input = { id: "post", type: "thread", serverId: "server", name: "Post", archived: 1, extra: "legacy" }
- expect(normalizeCommunityChannelIdentity(input)).toEqual({ id: "post", type: "thread", serverId: "server", name: "Post", archived: true,
- parentChannelId: null, parentMessageId: null, creatorId: null, lastMessageAt: null })
- expect(() => normalizeCommunityChannelIdentity({ ...input, id: "" })).toThrow()
- expect(() => normalizeCommunityChannelIdentity({ ...input, archived: 2 })).toThrow()
- })
- it.each([[false, false], [true, true], [0, false], [1, true]] as const)("normalizes only the present preview archive fact %s", (archived, expected) => {
- expect(normalizeCommunityChannelResourcePreview({ id: "preview", archived })).toEqual({ id: "preview", archived: expected })
- })
- it("keeps omitted preview fields absent", () => {
- const input = { id: "preview", name: "Preview" }
- expect(normalizeCommunityChannelResourcePreview(input)).toEqual(input)
- expect(normalizeCommunityChannelResourcePreview({})).toEqual({})
- })
- it("preserves supplied preview facts without complete or authority markers", () => {
- const input = { ...communityResourceChannelFixture, name: null, categoryId: "category", creatorId: null, lastMessageAt: "last", messageCount: 7, archived: 1 }
- expect(normalizeCommunityChannelResourcePreview({ ...input, resourceComplete: true, contractVersion: 3, accessDecision: { canRead: true }, proof: { revision: 7 } }))
- .toEqual({ ...input, archived: true })
- })
- it.each([{ archived: 2 }, { archived: -1 }, { archived: "0" }, { archived: "true" }, { archived: null }, { topic: null },
- { messageCount: -1 }, { messageCount: 0.5 }, { position: Infinity }, { id: "" },
- ])("rejects malformed supplied preview facts %j", (fields) => {
- expect(() => normalizeCommunityChannelResourcePreview({ id: "preview", ...fields })).toThrow()
- })
- it("requires committed message identity and rejects foreign scope", () => {
- const message = { id: "message", seq: 1, authorId: "author", createdAt: "2026-10-07T12:00:00Z", type: "chat", content: "hello" }
- expect(normalizeCommunityMessageResource(message, "channel")).toMatchObject({ channelId: "channel", replyToId: null, clientNonce: null, attachments: [] })
- expect(() => normalizeCommunityMessageResource({ ...message, channelId: "other" }, "channel")).toThrow("scope mismatch")
- expect(() => normalizeCommunityMessageResource({ ...message, seq: undefined }, "channel")).toThrow()
- const normalized = normalizeCommunityMessageResource(message, "channel")
- expect(CommunityMessageResourceSchema.safeParse({ ...normalized, type: "pending" }).success).toBe(false)
- })
-
- it("returns a complete canonical resource while stripping only legacy envelope extras", () => {
- const channel = normalizeCommunityChannelResource({ id: "channel", type: "thread", serverId: "server", name: null, archived: 1,
- createdAt: "now", topic: null, position: null, messageCount: null, extra: "legacy" })
- expect(CommunityChannelResourceSchema.parse(channel)).toEqual(channel)
- expect(channel).toMatchObject({ archived: true, topic: "", position: 0, messageCount: 0 })
- expect(channel).not.toHaveProperty("extra")
- const message = normalizeCommunityMessageResource({ id: "message", seq: 0, authorId: "author", createdAt: "now", type: "chat", content: "",
- replyToId: null, replyTo: { id: "reply", authorName: "Author", text: "prior" }, clientNonce: null, embeds: null, extra: "legacy" }, "channel")
- expect(CommunityMessageResourceSchema.parse(message)).toEqual(message)
- expect(message).toMatchObject({ replyToId: "reply", clientNonce: null, attachments: [] })
- expect(message).not.toHaveProperty("extra")
- })
-
- it.each([{ seq: -1 }, { seq: 0.5 }, { authorId: "" }, { attachments: null },
- { attachments: [{ kind: "file", name: "file", url: "/file", extra: true }] },
- { replyTo: { id: "reply", authorName: "Author", text: "prior", extra: true } },
- ])("rejects invalid committed message fields %j", (fields) => {
- expect(() => normalizeCommunityMessageResource({ id: "message", seq: 0, authorId: "author", createdAt: "now", type: "chat", content: "", ...fields }, "channel")).toThrow()
- })
-
- it("rejects an empty publication scope and invalid channel defaults", () => {
- expect(() => normalizeCommunityMessageResource({ id: "message", seq: 0, authorId: "author", createdAt: "now", type: "chat", content: "" }, "")).toThrow()
- for (const fields of [{ messageCount: -1 }, { messageCount: 0.5 }, { position: Infinity }, { archived: 2 }, { name: undefined }, { serverId: undefined }]) {
- expect(() => normalizeCommunityChannelResource({ id: "channel", type: "text", serverId: "server", name: "Channel", archived: 0, createdAt: "now", ...fields })).toThrow()
+import { CommunityMessageResourcesSchema, CommunityMessageReadSchema, CommunityMessagePostedSchema, communityMessageProfileIds, CommunityConversationEntryReadSchema, communityReadSchemas, type CommunityChannelResource } from "../src/community-resources"
+
+describe("current community resources", () => {
+ it("accepts only the exact current read contract", () => {
+ const body = { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "channel", changed: true, targetSeq: 7, revision: 9 }
+ expect(communityReadSchemas().readAdvance.parse(body)).toEqual(body)
+ for (const version of [undefined, 1, 2, 3, BUSINESS_SCHEMA_VERSION + 1]) {
+ expect(() => communityReadSchemas(version === undefined ? 0 : version)).toThrow("protocol mismatch")
+ expect(communityReadSchemas().readAdvance.safeParse({ ...body, contractVersion: version }).success).toBe(false)
}
})
+ it.each([undefined, "1", "2", "02", "3", String(BUSINESS_SCHEMA_VERSION), `0${BUSINESS_SCHEMA_VERSION}`])("requires exact header %s", version => {
+ expect(requestsCommunityContract(new Headers(version === undefined ? {} : { [COMMUNITY_CONTRACT_HEADER]: version }))).toBe(version === String(BUSINESS_SCHEMA_VERSION))
+ })
+ it.each(["text", "forum", "thread", "dm"] as const)("requires complete current %s channel facts", type => {
+ const value = { ...communityResourceChannelFixture, type }
+ expect(CommunityChannelResourceSchema.parse(value)).toEqual(value)
+ for (const key of Object.keys(value)) {
+ const partial: Record<string, unknown> = { ...value }; delete partial[key]
+ expect(CommunityChannelResourceSchema.safeParse(partial).success).toBe(false)
+ }
+ for (const fields of [{ archived: 0 }, { topic: null }, { messageCount: -1 }, { position: Infinity }, { resourceComplete: true }]) {
+ expect(CommunityChannelResourceSchema.safeParse({ ...value, ...fields }).success).toBe(false)
+ }
+ })
+ it("rejects incomplete committed messages and old attachment formats", () => {
+ const value = communityResourceMessageFixture.message
+ for (const key of ["id", "channelId", "seq", "authorId", "createdAt", "content", "replyToId", "clientNonce", "attachments"]) {
+ const partial: Record<string, unknown> = { ...value }; delete partial[key]
+ expect(CommunityMessageResourceSchema.safeParse(partial).success).toBe(false)
+ }
+ expect(CommunityMessageResourceSchema.safeParse({ ...value, attachments: [{ kind: "file", name: "file", url: "/file", size: "1 KB" }] }).success).toBe(false)
+ })
})
describe("conversation entry resource", () => {
const entry = () => ({
- contractVersion: 3,
+ contractVersion: BUSINESS_SCHEMA_VERSION,
channelId: communityResourceChannelFixture.id,
viewerId: "viewer", peer: null,
channel: communityResourceChannelFixture,
access: { channelId: communityResourceChannelFixture.id, canRead: true, canSend: true, canCreateDiscussion: false },
readState: { channelId: communityResourceChannelFixture.id, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },
- messages: [],
+ messages: [], profiles: [],
page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 },
surfaceReceipt: { channelId: communityResourceChannelFixture.id, surfaceKind: "channel" },
readStateRevision: 0, selection: { reason: "tail", anchorMessageId: null },
@@ -107,9 +59,9 @@ describe("conversation entry resource", () => {
const opener = { ...communityResourceMessageFixture.message, id: "opener", channelId: channel.id }
const message = { ...opener, id: "reply", channelId: child.id }
return { ...value, channel, surfaceReceipt: { ...value.surfaceReceipt, surfaceKind: "forum" }, forumFeed: {
- contractVersion: 3, channelId: channel.id, channel, threads: [child],
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: channel.id, channel, threads: [child],
included: { messages: [opener, message], tags: [{ messageId: "opener", tag: "tag" }], participantCounts: [{ channelId: child.id, count: 1 }],
- profiles: [{ id: "peer", name: "Peer", discriminator: "1234", avatar: null, avatarVersion: 0 }],
+ profiles: [...communityResourceMessageFixture.profiles, { id: "peer", name: "Peer", discriminator: "1234", avatar: null, avatarVersion: 0 }],
members: [{ channelId: child.id, userId: "peer", relation: "notify", source: "added", isCreator: false, role: null, memberId: null }] },
page: { nextCursor: null, hasMore: false },
} }
@@ -140,7 +92,7 @@ describe("conversation entry resource", () => {
it("preserves a confirmed empty entry without inventing a read pointer", () => {
const value = entry()
expect(CommunityConversationEntryReadSchema.parse(value)).toEqual(value)
- expect(communityReadSchemas(3).messages.safeParse(value).success).toBe(false)
+ expect(communityReadSchemas().messages.safeParse(value).success).toBe(false)
})
it.each(["channel", "access", "readState", "surfaceReceipt"] as const)("rejects a foreign %s in the entry", (field) => {
@@ -184,7 +136,7 @@ describe("conversation entry resource", () => {
})
-describe("full v3 resource facts", () => {
+describe("full current resource facts", () => {
it("preserves nullable metadata, IDs, order and raw embeds without presentation fields", () => {
const value = JSON.parse(JSON.stringify(communityResourceMessageFixture.message))
expect(CommunityMessageResourceSchema.parse(value)).toEqual(value)
@@ -196,7 +148,6 @@ describe("full v3 resource facts", () => {
expect(CommunityMessageAttachmentSchema.safeParse(attachment).success).toBe(false)
}
for (const sizeBytes of [-1, 0.5, Infinity]) expect(CommunityMessageAttachmentSchema.safeParse({ ...value.attachments[0], sizeBytes }).success).toBe(false)
- expect(CommunityMessagePreviewSchema.parse({ id: "preview", type: "chat" })).toEqual({ id: "preview", type: "chat" })
expect(CommunityMessageResourceSchema.safeParse({ id: "preview", type: "chat" }).success).toBe(false)
})
it("decodes only actual storage booleans and requires every full channel field", () => {
@@ -215,28 +166,66 @@ describe("full v3 resource facts", () => {
})
-describe("nested resource and legacy preview boundaries", () => {
- it("keeps unknown legacy nonce and reply identity omitted", () => {
- const input = { id: "preview", seq: 1, authorId: "author", createdAt: "now", type: "chat", content: "body" }
- const preview = communityMessagePreviewFromLegacy(input, "channel")
- for (const field of ["clientNonce", "replyToId", "attachments"]) expect(preview).not.toHaveProperty(field)
- expect(communityMessagePreviewFromLegacy({ ...input, clientNonce: null, replyToId: null, attachments: [] }, "channel"))
- .toMatchObject({ clientNonce: null, replyToId: null, attachments: [] })
- })
- it("preserves actual nested NULLs only in full 3 and never stores a legacy initial as a fact", () => {
+describe("nested current resource facts", () => {
+ it("preserves actual nullable thread fields and requires participant facts", () => {
const thread = { id: "thread", name: null, messageCount: 0, lastReplyAt: null, participants: [{ id: "peer", name: "Peer", avatar: null, avatarVersion: 4 }] }
const message = { ...communityResourceMessageFixture.message, thread }
expect(CommunityMessageResourceSchema.parse(message).thread).toEqual(thread)
- expect(CommunityLegacyMessageResourceSchema.safeParse({ ...message, attachments: [] }).success).toBe(false)
- const legacyThread = { ...thread, name: "Thread", lastReplyAt: "now", participants: [{ id: "peer", name: "Peer", avatar: "P", avatarVersion: 4 }] }
- const legacy = { ...message, authorAvatar: "A", attachments: [], thread: legacyThread }
- expect(CommunityLegacyMessageResourceSchema.parse(legacy).thread).toEqual(legacyThread)
- const preview = communityMessagePreviewFromLegacy(legacy, message.channelId)
- expect(preview.thread?.participants).toEqual([{ id: "peer", name: "Peer", avatarVersion: 4 }])
for (const field of ["name", "avatar", "avatarVersion"]) {
- const participant: Record<string, unknown> = { ...thread.participants[0] }
- delete participant[field]
+ const participant: Record<string, unknown> = { ...thread.participants[0] }; delete participant[field]
expect(CommunityMessageResourceSchema.safeParse({ ...message, thread: { ...thread, participants: [participant] } }).success).toBe(false)
}
})
})
+
+
+describe("complete message author dependency graphs", () => {
+ const author = { id: "author", name: "Former", discriminator: "0042", avatar: null, avatarVersion: 0 }
+ const replyAuthor = { ...author, id: "reply-author", name: "Reply author" }
+ const message = { ...communityResourceMessageFixture.message, authorId: author.id, replyToId: "prior", replyTo: { id: "prior", authorId: replyAuthor.id, authorName: replyAuthor.name, text: "Prior" } }
+ it("requires every live author and preserves real nullable profile fields", () => {
+ const graph = { messages: [message], profiles: [author, replyAuthor] }
+ expect(CommunityMessageResourcesSchema.parse(graph)).toEqual(graph)
+ expect(communityMessageProfileIds(graph.messages)).toEqual([author.id, replyAuthor.id])
+ expect(CommunityMessageResourcesSchema.parse({ messages: [], profiles: [] })).toEqual({ messages: [], profiles: [] })
+ })
+ it.each(["main", "reply", "duplicate", "null-discriminator", "missing-avatar", "live-reply-id"])("rejects incomplete or ambiguous author dependencies (%s)", defect => {
+ const profiles = defect === "main" ? [replyAuthor] : defect === "reply" ? [author] : defect === "duplicate" ? [author, replyAuthor, author] : [author, replyAuthor]
+ const graph: { messages: unknown[]; profiles: unknown[] } = { messages: [message], profiles }
+ if (defect === "null-discriminator") graph.profiles = [{ ...author, discriminator: null }, replyAuthor]
+ if (defect === "missing-avatar") { const { avatar: _avatar, ...partial } = author; graph.profiles = [partial, replyAuthor] }
+ if (defect === "live-reply-id") { const { authorId: _authorId, ...partial } = message.replyTo; graph.messages = [{ ...message, replyTo: partial }] }
+ expect(CommunityMessageResourcesSchema.safeParse(graph).success).toBe(false)
+ })
+ it("keeps an explicit deleted reply sentinel separate from a missing live person", () => {
+ const sentinel = { ...message, replyTo: { id: "prior", authorName: "Deleted user", text: "", deleted: true } }
+ expect(CommunityMessageResourcesSchema.parse({ messages: [sentinel], profiles: [author] }).messages[0].replyTo).toEqual(sentinel.replyTo)
+ expect(communityMessageProfileIds([sentinel])).toEqual([author.id])
+ })
+
+ it.each([CommunityMessageReadSchema, CommunityMessagePostedSchema])("validates the complete current single-message envelope and its graph issues", schema => {
+ const value = { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: message.channelId, message, profiles: [author, replyAuthor],
+ ...(schema === CommunityMessagePostedSchema ? { deduped: false } : {}) }
+ expect(schema.parse(value)).toEqual(value)
+ for (const profiles of [[author], [replyAuthor], []]) {
+ const result = schema.safeParse({ ...value, profiles })
+ expect(result.success).toBe(false)
+ if (!result.success) expect(result.error.issues.some(issue => issue.code === "custom")).toBe(true)
+ }
+ })
+
+ it("requires the explicit thread opener author in the current entry graph", () => {
+ const parent = { ...communityResourceChannelFixture, id: "parent", type: "text" as const }
+ const channel = { ...parent, id: "thread", type: "thread" as const, parentChannelId: parent.id, parentMessageId: "opener" }
+ const opener = { ...communityResourceMessageFixture.message, id: "opener", channelId: parent.id, authorId: author.id }
+ const value = { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: channel.id, viewerId: "viewer", peer: null, channel, parent, opener,
+ access: { channelId: channel.id, canRead: true, canSend: true, canCreateDiscussion: false },
+ readState: { channelId: channel.id, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },
+ messages: [], profiles: [author], page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 },
+ surfaceReceipt: { channelId: channel.id, surfaceKind: "thread" }, readStateRevision: 0, selection: { reason: "tail", anchorMessageId: null } }
+ expect(CommunityConversationEntryReadSchema.parse(value)).toEqual(value)
+ const result = CommunityConversationEntryReadSchema.safeParse({ ...value, profiles: [] })
+ expect(result.success).toBe(false)
+ if (!result.success) expect(result.error.issues).toContainEqual(expect.objectContaining({ code: "custom", path: ["profiles"], message: "Message profile missing or duplicated in resource graph" }))
+ })
+})
diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.ts
index a86d98cf8..abc0deb3c 100644
--- a/src/shared/test/community-ws-bundle.contract.test.ts
+++ b/src/shared/test/community-ws-bundle.contract.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it, vi } from "vitest"
import {
+ BUSINESS_SCHEMA_VERSION,
+ projectCommunityEventForContract,
COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,
COMMUNITY_BROWSER_EVENT_BATCH_TYPE,
communityBrowserEventBatchType,
@@ -22,7 +24,7 @@ import {
type CommunityBotAuditEvent,
type CommunityWsEvent,
} from "../src"
-import { communityWsEventFixtures, communityResourceMessageFixture, communityResourceChannelFixture } from "./community-ws-events.fixtures"
+import { communityWsEventFixtures, communityResourceMessageFixture } from "./community-ws-events.fixtures"
function maximizeAuditPadding(): CommunityBotAuditEvent {
let low = 0
@@ -47,58 +49,35 @@ function maximizeAuditPadding(): CommunityBotAuditEvent {
}
describe("community WS batch transport contract", () => {
- it("derives all three wire names from one family and the supported contract", () => {
- expect(communityBrowserEventBatchType(1)).toBe("community:events.batch")
- expect(communityBrowserEventBatchType()).toBe("community:events.batch.v2")
- expect(communityBrowserEventBatchType(2)).toBe("community:events.batch.v2")
- expect(() => communityBrowserEventBatchType(0)).toThrow("unsupported community event contract")
- expect(communityBrowserEventBatchType(3)).toBe("community:events.batch.v3")
- expect(() => communityBrowserEventBatchType(4)).toThrow("unsupported community event contract")
+ it("derives one current wire name and rejects old or invalid contracts", () => {
+ expect(communityBrowserEventBatchType()).toBe(`community:events.batch.v${BUSINESS_SCHEMA_VERSION}`)
+ expect(communityBrowserEventBatchType(BUSINESS_SCHEMA_VERSION)).toBe(`community:events.batch.v${BUSINESS_SCHEMA_VERSION}`)
+ for (const contract of [0, 1, 2, 3, BUSINESS_SCHEMA_VERSION - 1]) expect(() => communityBrowserEventBatchType(contract)).toThrow("unsupported community event contract")
})
- it("keeps the source digest while projecting one strict format per connection", async () => {
+ it("uses identical source and wire digests with no old membership projection", async () => {
const change = { type: WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE, channelId: "thread", serverId: "server", userId: "joined", relation: "notify", present: true } as const
const prepared = await prepareCommunityDeliveryEvents([change])
if (!prepared.ok) throw new Error("invalid fixture")
const operationId = await deriveCommunityDeliveryOperationId("joined-message")
- for (const contract of [1, 2] as const) {
- await expect(encodeCommunityBrowserEventBatchForContract({ operationId, prepared: { ...prepared.prepared, digest: "0".repeat(64) }, contract }))
- .resolves.toMatchObject({ ok: false, reason: "digest-mismatch" })
- }
- const old = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 1 })
- const current = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 2 })
- if (!old.ok || !current.ok) throw new Error("invalid projection")
- expect(old.body).toBe("{\"type\":\"community:events.batch\",\"operationId\":\"message:qbWQs0jZgHxxQP2XnrG_JaBwIEH7tss-wN83NwGGFco\",\"operationDigest\":\"02f419257acb00e467b673a0d10295eacaa0176c6f6700926ced78aabd78f053\",\"events\":[{\"type\":\"community:channel.member_add\",\"serverId\":\"server\",\"channelId\":\"thread\",\"userId\":\"joined\"}]}")
- expect(old.byteLength).toBe(296)
- expect(current.body).toBe("{\"type\":\"community:events.batch.v2\",\"operationId\":\"message:qbWQs0jZgHxxQP2XnrG_JaBwIEH7tss-wN83NwGGFco\",\"operationDigest\":\"256d83c615e1feac6685548ba38cfa9296913b0e0b64fd11ec8d4331711390b6\",\"wireDigest\":\"256d83c615e1feac6685548ba38cfa9296913b0e0b64fd11ec8d4331711390b6\",\"events\":[{\"type\":\"community:channel.membership.change\",\"channelId\":\"thread\",\"serverId\":\"server\",\"userId\":\"joined\",\"relation\":\"notify\",\"present\":true}]}")
- expect(current.byteLength).toBe(421)
- expect(admitCommunityBrowserEventBatch(old.batch)).not.toBeInstanceOf(Promise)
- expect(admitCommunityBrowserEventBatch(old.batch)).toMatchObject({ ok: true })
- expect(admitCommunityBrowserEventBatch(current.batch)).toBeInstanceOf(Promise)
- expect(old.batch.type).toBe(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)
- expect(Object.keys(old.batch)).toHaveLength(4)
- expect(old.batch.events).toEqual([{ type: WS_EVENTS.CHANNEL_MEMBER_ADD, serverId: "server", channelId: "thread", userId: "joined" }])
- expect(old.batch.operationDigest).not.toBe(prepared.prepared.digest)
- expect(current.batch).toMatchObject({ type: communityBrowserEventBatchType(), operationDigest: prepared.prepared.digest, wireDigest: prepared.prepared.digest })
- expect(await admitCommunityBrowserEventBatch(JSON.parse(current.body))).toMatchObject({ ok: true })
- expect(decodeCommunityBrowserEventBatch({ ...old.batch, wireDigest: current.batch.wireDigest }).ok).toBe(false)
- const tampered = JSON.parse(current.body)
- tampered.events[0].present = false
- expect(await admitCommunityBrowserEventBatch(tampered)).toMatchObject({ ok: false })
- const invalid = JSON.parse(current.body)
- invalid.events[0].extra = true
- expect(await admitCommunityBrowserEventBatch(invalid)).toMatchObject({ ok: false })
+ await expect(encodeCommunityBrowserEventBatchForContract({ operationId, prepared: { ...prepared.prepared, digest: "0".repeat(64) }, contract: BUSINESS_SCHEMA_VERSION })).resolves.toMatchObject({ ok: false, reason: "digest-mismatch" })
+ const current = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: BUSINESS_SCHEMA_VERSION })
+ if (!current.ok) throw new Error("invalid current fixture")
+ expect(current.batch.events).toEqual([{ ...change, schemaVersion: BUSINESS_SCHEMA_VERSION }])
+ expect(current.batch).toMatchObject({ operationDigest: prepared.prepared.digest, wireDigest: prepared.prepared.digest })
+ expect(await admitCommunityBrowserEventBatch(JSON.parse(current.body))).toMatchObject({ ok: true, events: [change] })
+ for (const contract of [1, 2, 3]) await expect(encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract })).resolves.toMatchObject({ ok: false, reason: "invalid-contract" })
+ for (const fields of [{ operationDigest: "0".repeat(64) }, { wireDigest: "0".repeat(64) }, { events: [{ ...change, present: false, schemaVersion: BUSINESS_SCHEMA_VERSION }] }]) expect(await admitCommunityBrowserEventBatch({ ...current.batch, ...fields })).toMatchObject({ ok: false })
+ expect(await admitCommunityBrowserEventBatch({ ...current.batch, events: [{ ...current.batch.events[0], extra: true }] })).toMatchObject({ ok: false })
})
- it.each([false, true])("keeps owned Block=%s in the current wire and emits the original peer shape for legacy", async (blockedByViewer) => {
+ it.each([false, true])("retains current owned Block=%s without projecting old peer shapes", async blockedByViewer => {
const event = { type: WS_EVENTS.FRIEND_BLOCK, userId: "peer", blockedByViewer } as const
const prepared = await prepareCommunityDeliveryEvents([event])
if (!prepared.ok) throw new Error("invalid block fixture")
const operationId = await deriveCommunityDeliveryOperationId("blocked-peer")
- const old = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 1 })
- const current = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 2 })
- if (!old.ok || !current.ok) throw new Error("invalid block projection")
- expect(old.batch.events).toEqual([{ type: WS_EVENTS.FRIEND_BLOCK, userId: "peer" }])
- expect(current.batch.events).toEqual([event])
- expect(await admitCommunityBrowserEventBatch(current.batch)).toMatchObject({ ok: true })
+ const current = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: BUSINESS_SCHEMA_VERSION })
+ if (!current.ok) throw new Error("invalid current fixture")
+ expect(current.batch.events).toEqual([{ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }])
+ expect(await admitCommunityBrowserEventBatch(current.batch)).toMatchObject({ ok: true, events: [event] })
})
const children: CommunityWsEvent[] = [
@@ -145,7 +124,7 @@ describe("community WS batch transport contract", () => {
expect(isCommunityDeliveryDigest("a".repeat(63))).toBe(false)
})
- it("round-trips one strict outer frame without entering the 48-event union", async () => {
+ it("round-trips one strict outer frame without entering the 46-event union", async () => {
const operationId = await deriveCommunityDeliveryOperationId("message-1")
const prepared = await prepareCommunityDeliveryEvents(children)
expect(prepared.ok).toBe(true)
@@ -158,12 +137,13 @@ describe("community WS batch transport contract", () => {
expect(encoded.ok).toBe(true)
if (!encoded.ok) return
expect(encoded.batch).toEqual(JSON.parse(encoded.body))
- expect(encoded.batch.type).toBe(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)
+ expect(encoded.batch.type).toBe(communityBrowserEventBatchType())
expect(Object.keys(encoded.batch).sort()).toEqual([
"events",
"operationDigest",
"operationId",
"type",
+ "wireDigest",
])
expect(encoded.batch.events.map((event) => event.type)).toEqual(children.map((event) => event.type))
expect(decodeCommunityBrowserEventBatch(encoded.batch, encoded.byteLength)).toEqual({
@@ -173,7 +153,7 @@ describe("community WS batch transport contract", () => {
})
expect(isCommunityBrowserEventBatchCandidate(encoded.batch)).toBe(true)
expect(Object.values(WS_EVENTS)).not.toContain(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)
- expect(Object.values(WS_EVENTS)).toHaveLength(48)
+ expect(Object.values(WS_EVENTS)).toHaveLength(46)
})
it("rejects invalid count, child, operation metadata, digest mismatch, and strict outer keys", async () => {
@@ -298,68 +278,33 @@ describe("community WS batch transport contract", () => {
})
-describe("explicit v3 delivery codec", () => {
- it.each([1, 2] as const)("projects empty attachments and full channel/identity facts to contract %s", async (contract) => {
- const events = [
- { ...communityResourceMessageFixture, message: { ...communityResourceMessageFixture.message, attachments: [] } },
- { type: WS_EVENTS.CHANNEL_CREATE, serverId: "server-1", channel: { ...communityResourceChannelFixture, name: null } },
- { type: "community:channel.child_create", parentChannelId: "channel-1", parentMessageId: "message-1", channel: {
- ...communityResourceChannelFixture, id: "thread-1", type: "thread", name: null, creatorId: null,
- parentChannelId: "channel-1", parentMessageId: "message-1",
- } },
- { type: WS_EVENTS.IDENTITY_UPDATE, userId: "user-1", avatar: null, avatarVersion: 1 },
- ]
- const prepared = await prepareCommunityDeliveryEvents(events, 3)
- if (!prepared.ok) throw new Error("invalid resource fixtures")
- const encoded = await encodeCommunityBrowserEventBatchForContract({
- operationId: await deriveCommunityDeliveryOperationId("legacy-resource-projection"), prepared: prepared.prepared, contract,
- })
- if (!encoded.ok) throw new Error("invalid legacy projection")
- const wire = JSON.parse(encoded.body)
- expect(wire.type).toBe(communityBrowserEventBatchType(contract))
- expect(wire.events[0].message).not.toHaveProperty("attachments")
- expect(wire.events[0].message).not.toHaveProperty("channelId")
- expect(wire.events[1]).toEqual({ type: WS_EVENTS.CHANNEL_CREATE, serverId: "server-1", channel: {
- id: "channel-1", name: "", type: "text", categoryId: null, topic: "Keep this topic", position: 4, createdAt: communityResourceChannelFixture.createdAt,
- } })
- expect(wire.events[2]).toEqual({ type: "community:channel.child_create", parentChannelId: "channel-1", parentMessageId: "message-1",
- channel: { id: "thread-1", name: "", type: "thread", createdAt: communityResourceChannelFixture.createdAt } })
- expect(wire.events[3]).toEqual({ ...events[3], avatar: "" })
- expect(await admitCommunityBrowserEventBatch(wire)).toMatchObject({ ok: true, events: wire.events })
- })
- it("captures original source bytes before digest and projects strict 1/2/3 frames", async () => {
- const prepared = await prepareCommunityDeliveryEvents([communityResourceMessageFixture], 3)
- if (!prepared.ok) throw new Error("invalid v3 fixture")
- expect(prepared.prepared.contract).toBe(3)
- expect(JSON.parse(prepared.prepared.bodies[0]!)).toEqual(communityResourceMessageFixture)
+describe("current full-resource delivery codec", () => {
+ it("captures current child bytes and rejects every obsolete projection", async () => {
+ const prepared = await prepareCommunityDeliveryEvents([communityResourceMessageFixture])
+ if (!prepared.ok) throw new Error("invalid current fixture")
+ expect(prepared.prepared.contract).toBe(BUSINESS_SCHEMA_VERSION)
+ expect(JSON.parse(prepared.prepared.bodies[0]!)).toEqual({ ...communityResourceMessageFixture, schemaVersion: BUSINESS_SCHEMA_VERSION })
const operationId = await deriveCommunityDeliveryOperationId("full-resource")
- for (const contract of [1, 2, 3] as const) {
- const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract })
- if (!encoded.ok) throw new Error(`invalid v${contract} projection`)
- expect(encoded.byteLength).toBe(utf8ByteLength(encoded.body))
- expect(await admitCommunityBrowserEventBatch(JSON.parse(encoded.body))).toMatchObject({ ok: true })
- if (contract === 3) {
- expect(encoded.batch.events).toEqual([communityResourceMessageFixture])
- expect(encoded.batch.operationDigest).toBe(prepared.prepared.digest)
- } else {
- const event = encoded.batch.events[0]
- if (event.type !== WS_EVENTS.MESSAGE_CREATE) throw new Error("invalid projection")
- expect(event.message).not.toHaveProperty("channelId")
- expect(event.message.attachments?.map((row) => "filename" in row ? row.filename : "invalid")).toEqual(["unknown.bin", "photo.png"])
- expect(JSON.parse(encoded.body).events[0].message).not.toHaveProperty("authorAvatar")
- }
+ for (const contract of [1, 2, 3]) {
+ await expect(prepareCommunityDeliveryEvents([communityResourceMessageFixture], contract)).resolves.toMatchObject({ ok: false })
+ await expect(encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract })).resolves.toMatchObject({ ok: false, reason: "invalid-contract" })
+ expect(encodePreparedCommunityBrowserEventBatch({ operationId, operationDigest: prepared.prepared.digest, prepared: prepared.prepared, contract })).toMatchObject({ ok: false, reason: "invalid-contract" })
}
- await expect(prepareCommunityDeliveryEvents([communityResourceMessageFixture])).resolves.toMatchObject({ ok: false })
- const old = await prepareCommunityDeliveryEvents([communityWsEventFixtures["community:message.create"]])
- if (!old.ok) throw new Error("invalid old fixture")
- expect(await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: old.prepared, contract: 3 })).toMatchObject({ ok: false })
- expect(await encodePreparedCommunityBrowserEventBatch({ operationId, operationDigest: prepared.prepared.digest, prepared: prepared.prepared, contract: 3 })).toMatchObject({ ok: false, reason: "invalid-contract" })
- const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: 3 })
- if (!encoded.ok) throw new Error("invalid full frame")
+ const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId, prepared: prepared.prepared, contract: BUSINESS_SCHEMA_VERSION })
+ if (!encoded.ok) throw new Error("invalid current frame")
+ expect(encoded.byteLength).toBe(utf8ByteLength(encoded.body))
+ expect(await admitCommunityBrowserEventBatch(JSON.parse(encoded.body))).toMatchObject({ ok: true, events: [communityResourceMessageFixture] })
const tampered = JSON.parse(encoded.body)
tampered.events[0].message.attachments.reverse()
expect(await admitCommunityBrowserEventBatch(tampered)).toMatchObject({ ok: false })
- tampered.type = "community:events.batch.v4"
- expect(await admitCommunityBrowserEventBatch(tampered)).toMatchObject({ ok: false })
+ for (const type of ["community:events.batch", "community:events.batch.v2", "community:events.batch.v3"]) expect(await admitCommunityBrowserEventBatch({ ...encoded.batch, type })).toMatchObject({ ok: false })
})
})
+
+it("projects only a validated current event with matching source and recipient contracts", () => {
+ const event = communityWsEventFixtures["community:message.create"]
+ expect(projectCommunityEventForContract(event, BUSINESS_SCHEMA_VERSION)).toEqual(event)
+ expect(projectCommunityEventForContract(event, BUSINESS_SCHEMA_VERSION - 1)).toBeNull()
+ expect(projectCommunityEventForContract(event, BUSINESS_SCHEMA_VERSION, BUSINESS_SCHEMA_VERSION - 1)).toBeNull()
+ expect(projectCommunityEventForContract({ ...event, message: { ...event.message, avatarVersion: 4 } } as never, BUSINESS_SCHEMA_VERSION)).toBeNull()
+})
diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.ts
index 449370dae..025665856 100644
--- a/src/shared/test/community-ws-events.contract.test.ts
+++ b/src/shared/test/community-ws-events.contract.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "../src/business-schema-version"
import { describe, expect, it } from "vitest"
import {
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
@@ -6,6 +7,7 @@ import {
CommunityWsEventSchema,
WS_EVENTS,
decodeCommunityBrowserEvent,
+ validateCommunityWsEvent,
encodeCommunityBrowserEvent,
isCommunityEventCandidate,
isCommunityEventType,
@@ -65,22 +67,24 @@ describe("Community browser event runtime contract", () => {
const fixtures = Object.values(communityWsEventFixtures)
const names = Object.values(WS_EVENTS).sort()
- it("locks the exact 48-event inventory", () => {
- expect(names).toHaveLength(48)
+ it("locks the exact 46-event inventory", () => {
+ expect(names).toHaveLength(46)
expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)
expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)
})
- it("decodes and canonically encodes all 48 current event fixtures", () => {
+ it("decodes and canonically encodes all 46 current event fixtures", () => {
for (const fixture of fixtures) {
- expect(decodeCommunityBrowserEvent(fixture)).toEqual({ ok: true, event: fixture })
+ expect(validateCommunityWsEvent(fixture)).toEqual({ ok: true, event: fixture })
const encoded = encodeCommunityBrowserEvent(fixture)
expect(encoded.ok).toBe(true)
if (!encoded.ok) continue
expect(encoded.event).toEqual(fixture)
expect(encoded.event).not.toHaveProperty("contractVersion")
- expect(JSON.parse(encoded.body)).toEqual(fixture)
- expect(decodeCommunityBrowserEvent(encoded.event)).toEqual({ ok: true, event: fixture })
+ expect(JSON.parse(encoded.body)).toEqual({ ...fixture, schemaVersion: BUSINESS_SCHEMA_VERSION })
+ expect(decodeCommunityBrowserEvent(JSON.parse(encoded.body))).toEqual({ ok: true, event: fixture })
+ expect(decodeCommunityBrowserEvent(encoded.envelope)).toEqual({ ok: true, event: fixture })
+ expect(decodeCommunityBrowserEvent(fixture).ok).toBe(false)
}
})
@@ -90,14 +94,14 @@ describe("Community browser event runtime contract", () => {
kind: "turn_interrupt",
payload: { status: "accepted" },
}
- expect(decodeCommunityBrowserEvent(event)).toEqual({ ok: true, event })
+ expect(validateCommunityWsEvent(event)).toEqual({ ok: true, event })
})
it("rejects missing fields or extra payload on every event", () => {
for (const fixture of fixtures) {
const path = requiredFixturePaths[fixture.type]
const corrupted = path.length ? withoutPath(fixture, path) : { ...fixture, entries: [] }
- expect(decodeCommunityBrowserEvent(corrupted)).toMatchObject({
+ expect(validateCommunityWsEvent(corrupted)).toMatchObject({
ok: false,
reason: "invalid-payload",
type: fixture.type,
@@ -106,12 +110,12 @@ describe("Community browser event runtime contract", () => {
})
it("uses a bounded read-state dirty hint instead of an account-sized frame", () => {
- expect(decodeCommunityBrowserEvent({
+ expect(validateCommunityWsEvent({
type: "community:read_state.advanced",
revision: 4,
inboxChanged: true,
})).toMatchObject({ ok: true })
- expect(decodeCommunityBrowserEvent({
+ expect(validateCommunityWsEvent({
type: "community:inbox.changed",
revision: 5,
inboxChanged: true,
@@ -131,7 +135,7 @@ describe("Community browser event runtime contract", () => {
}
expect(utf8ByteLength(JSON.stringify(accountSizedFrame)))
.toBeGreaterThan(COMMUNITY_BROWSER_EVENT_MAX_BYTES)
- expect(decodeCommunityBrowserEvent(accountSizedFrame))
+ expect(validateCommunityWsEvent(accountSizedFrame))
.toMatchObject({ ok: false, reason: "invalid-payload" })
const encodedHint = encodeCommunityBrowserEvent({
type: "community:read_state.advanced",
@@ -143,24 +147,24 @@ describe("Community browser event runtime contract", () => {
})
it("fails closed for family, removed-version, shape, and strict-key errors", () => {
- expect(decodeCommunityBrowserEvent(null)).toMatchObject({ reason: "non-object" })
- expect(decodeCommunityBrowserEvent([])).toMatchObject({ reason: "non-object" })
- expect(decodeCommunityBrowserEvent({})).toMatchObject({ reason: "missing-type" })
- expect(decodeCommunityBrowserEvent({ type: "task.messages" })).toMatchObject({ reason: "wrong-family" })
- expect(decodeCommunityBrowserEvent({ type: "community:future" })).toMatchObject({ reason: "unknown-community-type" })
- expect(decodeCommunityBrowserEvent({ ...fixtures[0], contractVersion: 1 }))
+ expect(validateCommunityWsEvent(null)).toMatchObject({ reason: "non-object" })
+ expect(validateCommunityWsEvent([])).toMatchObject({ reason: "non-object" })
+ expect(validateCommunityWsEvent({})).toMatchObject({ reason: "missing-type" })
+ expect(validateCommunityWsEvent({ type: "task.messages" })).toMatchObject({ reason: "wrong-family" })
+ expect(validateCommunityWsEvent({ type: "community:future" })).toMatchObject({ reason: "unknown-community-type" })
+ expect(validateCommunityWsEvent({ ...fixtures[0], contractVersion: 1 }))
.toMatchObject({ reason: "invalid-payload" })
expect(encodeCommunityBrowserEvent({ ...fixtures[0], contractVersion: 1 }))
.toMatchObject({ ok: false, reason: "invalid-payload" })
- expect(decodeCommunityBrowserEvent({ ...fixtures[0], contractVersion: 2 }))
+ expect(validateCommunityWsEvent({ ...fixtures[0], contractVersion: 2 }))
.toMatchObject({ reason: "invalid-payload" })
- expect(decodeCommunityBrowserEvent({ ...fixtures[0], extra: true })).toMatchObject({ reason: "invalid-payload" })
+ expect(validateCommunityWsEvent({ ...fixtures[0], extra: true })).toMatchObject({ reason: "invalid-payload" })
const nestedExtra = clone(communityWsEventFixtures["community:message.create"]) as CommunityMessageCreate & {
message: CommunityMessageCreate["message"] & { extra: boolean }
}
nestedExtra.message.extra = true
- expect(decodeCommunityBrowserEvent(nestedExtra)).toMatchObject({ reason: "invalid-payload" })
- expect(decodeCommunityBrowserEvent({
+ expect(validateCommunityWsEvent(nestedExtra)).toMatchObject({ reason: "invalid-payload" })
+ expect(validateCommunityWsEvent({
type: "community:message.edited",
channelId: "child",
messageId: "message",
@@ -184,10 +188,10 @@ describe("Community browser event runtime contract", () => {
content: "m".repeat(4000),
attachments: Array.from({ length: 10 }, (_, index) => ({
id: `attachment-${index}`,
- filename: `file-${index}.txt`,
+ name: `file-${index}.txt`, thumbnailUrl: null, width: null, height: null,
url: `/api/community/channels/channel-1/attachments/attachment-${index}`,
contentType: "text/plain",
- size: 25 * 1024 * 1024,
+ sizeBytes: 25 * 1024 * 1024,
})),
embeds: [{ padding }],
},
@@ -238,47 +242,48 @@ describe("Community browser event runtime contract", () => {
})
-describe("explicit v3 browser events", () => {
+describe("current full-resource browser events", () => {
it("admits child resources only with matching parent identities", () => {
const event = { type: "community:channel.child_create", parentChannelId: "parent", parentMessageId: "opener", channel: {
...communityResourceChannelFixture, id: "thread", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
} }
- expect(decodeCommunityBrowserEvent(event, 3)).toEqual({ ok: true, event })
+ expect(validateCommunityWsEvent(event, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event })
const { parentMessageId: _parentMessageId, ...withoutOpenerClaim } = event
- expect(decodeCommunityBrowserEvent(withoutOpenerClaim, 3)).toEqual({ ok: true, event: withoutOpenerClaim })
+ expect(validateCommunityWsEvent(withoutOpenerClaim, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: withoutOpenerClaim })
for (const fields of [{ parentChannelId: "other" }, { parentMessageId: "other" }]) {
- expect(decodeCommunityBrowserEvent({ ...event, ...fields }, 3)).toMatchObject({ ok: false, reason: "invalid-payload" })
+ expect(validateCommunityWsEvent({ ...event, ...fields }, BUSINESS_SCHEMA_VERSION)).toMatchObject({ ok: false, reason: "invalid-payload" })
}
})
- it("requires a positive avatar version on a v3 identity update", () => {
+ it("requires a positive avatar version on a current identity update", () => {
const event = { type: WS_EVENTS.IDENTITY_UPDATE, userId: "user-1", avatar: null, avatarVersion: 1 }
- expect(decodeCommunityBrowserEvent(event, 3)).toEqual({ ok: true, event })
+ expect(validateCommunityWsEvent(event, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event })
for (const avatarVersion of [0, -1, 0.5]) {
- expect(decodeCommunityBrowserEvent({ ...event, avatarVersion }, 3)).toMatchObject({ ok: false, reason: "invalid-payload" })
+ expect(validateCommunityWsEvent({ ...event, avatarVersion }, BUSINESS_SCHEMA_VERSION)).toMatchObject({ ok: false, reason: "invalid-payload" })
}
})
it("requires full resources on create and preserves partial deltas", () => {
- expect(decodeCommunityBrowserEvent(communityResourceMessageFixture, 3)).toEqual({ ok: true, event: communityResourceMessageFixture })
- expect(decodeCommunityBrowserEvent(communityResourceMessageFixture, 2).ok).toBe(false)
- expect(decodeCommunityBrowserEvent(communityWsEventFixtures["community:message.create"], 3).ok).toBe(false)
- expect(decodeCommunityBrowserEvent({ ...communityResourceMessageFixture, channelId: "other" }, 3).ok).toBe(false)
+ expect(validateCommunityWsEvent(communityResourceMessageFixture, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: communityResourceMessageFixture })
+ expect(validateCommunityWsEvent(communityResourceMessageFixture, 2).ok).toBe(false)
+ expect(validateCommunityWsEvent({ ...communityWsEventFixtures["community:message.create"], message: { id: "message-1", content: "weak" } }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
+ expect(validateCommunityWsEvent({ ...communityResourceMessageFixture, channelId: "other" }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
const create = { type: WS_EVENTS.CHANNEL_CREATE, serverId: "server-1", channel: communityResourceChannelFixture }
- expect(decodeCommunityBrowserEvent(create, 3)).toEqual({ ok: true, event: create })
- expect(decodeCommunityBrowserEvent({ ...create, serverId: "other" }, 3).ok).toBe(false)
- expect(decodeCommunityBrowserEvent({ ...create, channel: { id: "channel-1", name: "Channel", type: "text" } }, 3).ok).toBe(false)
+ expect(validateCommunityWsEvent(create, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: create })
+ expect(validateCommunityWsEvent({ ...create, serverId: "other" }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
+ expect(validateCommunityWsEvent({ ...create, channel: { id: "channel-1", name: "Channel", type: "text" } }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
const delta = { type: WS_EVENTS.CHANNEL_UPDATE, serverId: "server-1", channelId: "channel-1", changes: { name: "Renamed" } }
- expect(decodeCommunityBrowserEvent(delta, 3)).toEqual({ ok: true, event: delta })
- const encoded = encodeCommunityBrowserEvent(communityResourceMessageFixture, 3)
+ expect(validateCommunityWsEvent(delta, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: delta })
+ const encoded = encodeCommunityBrowserEvent(communityResourceMessageFixture, BUSINESS_SCHEMA_VERSION)
expect(encoded.ok).toBe(true)
if (encoded.ok) expect(encoded.byteLength).toBe(utf8ByteLength(encoded.body))
- expect(encodeCommunityBrowserEvent({ ...communityResourceMessageFixture, message: { ...communityResourceMessageFixture.message, content: "😀".repeat(COMMUNITY_BROWSER_EVENT_MAX_BYTES) } }, 3).ok).toBe(false)
+ expect(encodeCommunityBrowserEvent({ ...communityResourceMessageFixture, message: { ...communityResourceMessageFixture.message, content: "😀".repeat(COMMUNITY_BROWSER_EVENT_MAX_BYTES) } }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
})
})
-it("server rail hints carry no order or account payload in either contract", () => {
- for (const contract of [2, 3] as const) {
- const hint = { type: "community:server_rail.changed" };
- expect(decodeCommunityBrowserEvent(hint, contract)).toMatchObject({ ok: true, event: hint });
- for (const extra of [{ entries: [] }, { userId: "other" }]) expect(decodeCommunityBrowserEvent({ ...hint, ...extra }, contract)).toMatchObject({ ok: false, reason: "invalid-payload" });
- }
-});
+it("current server rail hints carry no order or account payload; old versions reject", () => {
+ const hint = { type: "community:server_rail.changed" }
+ const encoded = encodeCommunityBrowserEvent(hint)
+ if (!encoded.ok) throw new Error("invalid current fixture")
+ expect(decodeCommunityBrowserEvent(encoded.envelope)).toEqual({ ok: true, event: hint })
+ for (const version of [1, 2, 3, BUSINESS_SCHEMA_VERSION - 1]) expect(decodeCommunityBrowserEvent({ ...hint, schemaVersion: version }).ok).toBe(false)
+ for (const extra of [{ entries: [] }, { userId: "other" }]) expect(validateCommunityWsEvent({ ...hint, ...extra }).ok).toBe(false)
+})
diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.ts
index 929da93e1..b603f1f61 100644
--- a/src/shared/test/community-ws-events.fixtures.ts
+++ b/src/shared/test/community-ws-events.fixtures.ts
@@ -23,13 +23,22 @@ const machine = {
updatedAt: "2026-01-01T00:00:00.000Z",
}
+export const communityResourceChannelFixture = {
+ id: "channel-1", type: "text", serverId: "server-1", categoryId: null,
+ name: "Channel", topic: "Keep this topic", parentChannelId: null, parentMessageId: null,
+ creatorId: "user-1", position: 4, archived: false, createdAt: "2026-01-01T00:00:00.000Z",
+ lastMessageAt: null, messageCount: 0,
+} as const
+
+
export const communityWsEventFixtures = {
"community:message.create": {
type: "community:message.create",
channelId: "channel-1",
serverId: "server-1",
+ profiles: [{ id: "user-1", name: "Author", discriminator: "0001", avatar: null, avatarVersion: 0 }],
message: {
- id: "message-1",
+ id: "message-1", channelId: "channel-1", replyToId: null, clientNonce: null,
seq: 1,
authorId: "user-1",
authorName: "Author",
@@ -38,7 +47,7 @@ export const communityWsEventFixtures = {
type: "chat",
attachments: [{
id: "attachment-1",
- filename: "photo.png",
+ name: "photo.png", sizeBytes: 2048, width: 640, height: 480,
url: "/api/community/channels/channel-1/attachments/attachment-1",
thumbnailUrl: "/api/community/channels/channel-1/attachments/attachment-1/thumbnail",
contentType: "image/png",
@@ -89,12 +98,7 @@ export const communityWsEventFixtures = {
"community:channel.child_create": {
type: "community:channel.child_create",
parentChannelId: "channel-1",
- channel: {
- id: "thread-1",
- name: "Thread",
- type: "thread",
- createdAt: "2026-01-01T00:00:00.000Z",
- },
+ channel: { ...communityResourceChannelFixture, id: "thread-1", name: "Thread", type: "thread", parentChannelId: "channel-1", parentMessageId: "message-1" },
},
"community:channel.child_update": {
type: "community:channel.child_update",
@@ -112,13 +116,7 @@ export const communityWsEventFixtures = {
"community:channel.create": {
type: "community:channel.create",
serverId: "server-1",
- channel: {
- id: "channel-1",
- name: "Channel",
- type: "text",
- position: 0,
- createdAt: "2026-01-01T00:00:00.000Z",
- },
+ channel: { ...communityResourceChannelFixture, position: 0 },
},
"community:channel.update": {
type: "community:channel.update",
@@ -136,25 +134,13 @@ export const communityWsEventFixtures = {
serverId: "server-1",
channels: [{ id: "channel-1", position: 0 }],
},
- "community:channel.member_add": {
- type: "community:channel.member_add",
- serverId: "server-1",
- channelId: "channel-1",
- userId: "user-1",
- },
- "community:channel.member_remove": {
- type: "community:channel.member_remove",
- serverId: "server-1",
- channelId: "channel-1",
- userId: "user-1",
- },
"community:channel.membership.change": {
type: "community:channel.membership.change", serverId: "server-1", channelId: "channel-1", userId: "user-1", relation: "notify", present: true,
},
"community:category.create": {
type: "community:category.create",
serverId: "server-1",
- category: { id: "category-1", name: "Category", position: 0, private: false },
+ category: { id: "category-1", serverId: "server-1", creatorId: "user-1", name: "Category", position: 0, private: false },
},
"community:category.update": {
type: "community:category.update",
@@ -178,7 +164,7 @@ export const communityWsEventFixtures = {
member: {
id: "member-1",
userId: "user-1",
- name: "Member",
+ name: "Member", avatar: null,
discriminator: "0001",
avatarVersion: 0,
role: "member",
@@ -309,8 +295,6 @@ export const requiredFixturePaths = {
"community:channel.update": ["changes"],
"community:channel.delete": ["channelId"],
"community:channel.reorder": ["channels"],
- "community:channel.member_add": ["userId"],
- "community:channel.member_remove": ["userId"],
"community:channel.membership.change": ["relation"],
"community:category.create": ["category"],
"community:category.update": ["changes"],
@@ -342,12 +326,6 @@ export const requiredFixturePaths = {
"community:bot.audit_event": ["payload"],
} satisfies Record<CommunityWsEvent["type"], readonly [] | readonly [string, ...string[]]>
-export const communityResourceChannelFixture = {
- id: "channel-1", type: "text", serverId: "server-1", categoryId: null,
- name: "Channel", topic: "Keep this topic", parentChannelId: null, parentMessageId: null,
- creatorId: "user-1", position: 4, archived: false, createdAt: "2026-01-01T00:00:00.000Z",
- lastMessageAt: null, messageCount: 0,
-} as const
export const communityResourceMessageFixture = {
...communityWsEventFixtures["community:message.create"],
diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index 19f78116d..96b4457f8 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -8,7 +8,7 @@ import type {
import type { CommunityMachineSummary } from "../src/schemas";
describe("CommunityChannelDelete post-unit address contract", () => {
- it("accepts canonical post identity while preserving legacy/top-level compatibility", () => {
+ it("accepts canonical post identity while preserving current top-level addressing", () => {
const canonical: CommunityChannelDelete = {
type: "community:channel.delete",
serverId: "server_1",
@@ -52,7 +52,7 @@ describe("CommunityChannelDelete post-unit address contract", () => {
describe("isCommunityEvent", () => {
it("accepts every exact event declared by WS_EVENTS", () => {
- expect(Object.values(WS_EVENTS)).toHaveLength(48);
+ expect(Object.values(WS_EVENTS)).toHaveLength(46);
for (const type of Object.values(WS_EVENTS)) {
expect(isCommunityEvent({ type })).toBe(true);
}
diff --git a/src/shared/test/community/queue-task.test.ts b/src/shared/test/community/queue-task.test.ts
index 5a16f925b..e1800a26a 100644
--- a/src/shared/test/community/queue-task.test.ts
+++ b/src/shared/test/community/queue-task.test.ts
@@ -3,17 +3,12 @@ import { parseQueueTask, parseQueueTaskBatch } from "../../src/community/queue-t
describe("parseQueueTask", () => {
it.each([
- {
- name: "legacy",
- value: { messageId: "message-1", botUserId: "bot-1" },
- source: "legacy",
- },
{
name: "v1 bot-wake",
value: { version: 1, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" },
source: "v1",
},
- ])("normalizes a valid $name task", ({ value, source }) => {
+ ])("accepts a valid $name task", ({ value, source }) => {
expect(parseQueueTask(value)).toEqual({
ok: true,
source,
@@ -27,6 +22,7 @@ describe("parseQueueTask", () => {
})
it.each([
+ { name: "unversioned old wake", value: { messageId: "message-1", botUserId: "bot-1" } },
{ name: "null", value: null },
{ name: "array", value: [] },
{ name: "primitive", value: "wake" },
@@ -82,9 +78,9 @@ describe("parseQueueTask", () => {
})
describe("parseQueueTaskBatch", () => {
- it("normalizes the complete legacy/v1 batch", () => {
+ it("accepts the complete current versioned batch", () => {
expect(parseQueueTaskBatch([
- { messageId: "message-1", botUserId: "bot-1" },
+ { version: 1, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" },
{ version: 1, kind: "bot-wake", messageId: "message-2", botUserId: "bot-2" },
{ version: 1, kind: "mobile-push", messageId: "message-3", userId: "user-3" },
])).toEqual({
@@ -97,11 +93,18 @@ describe("parseQueueTaskBatch", () => {
})
})
+ it("rejects an unversioned member of a mixed batch without returning migrated tasks", () => {
+ expect(parseQueueTaskBatch([
+ { version: 1, kind: "bot-wake", messageId: "current", botUserId: "bot" },
+ { messageId: "old", botUserId: "bot" },
+ ])).toEqual({ ok: false, reason: "malformed", itemIndex: 1 })
+ })
+
it("reports the first rejected item without returning partial payloads", () => {
expect(parseQueueTaskBatch([
- { messageId: "message-1", botUserId: "bot-1" },
+ { version: 1, kind: "bot-wake", messageId: "message-1", botUserId: "bot-1" },
{ version: 1, kind: "email", messageId: "message-2", userId: "user-2" },
- { messageId: "message-3", botUserId: "bot-3" },
+ { version: 1, kind: "bot-wake", messageId: "message-3", botUserId: "bot-3" },
])).toEqual({ ok: false, reason: "unknown_kind", itemIndex: 1 })
})
diff --git a/src/shared/test/queries/community-attention.test.ts b/src/shared/test/queries/community-attention.test.ts
index e92ed89ea..f726dc4fa 100644
--- a/src/shared/test/queries/community-attention.test.ts
+++ b/src/shared/test/queries/community-attention.test.ts
@@ -34,8 +34,8 @@ vi.mock("../../src/db/queries/community/server", () => ({
getServersByIds: (...args: unknown[]) => mocks.serverOwners(...args),
}))
-import { getAccountAttentionSnapshot } from "../../src/db/queries/community/attention"
-import { AccountAttentionSnapshotSchema } from "../../src/community-attention"
+import { getAccountAttentionProjection } from "../../src/db/queries/community/attention"
+import { AccountAttentionProjectionSchema } from "../../src/community-attention"
describe("account attention snapshot", () => {
beforeEach(() => {
@@ -105,7 +105,7 @@ describe("account attention snapshot", () => {
})
it("caps only mention rows while keeping exact scope counts and every friend request", async () => {
- const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+ const snapshot = await getAccountAttentionProjection({} as never, "viewer", 2)
expect(snapshot.truncated).toBe(true)
expect(snapshot.scopes[0]?.attentionCount).toBe(9)
@@ -160,7 +160,7 @@ describe("account attention snapshot", () => {
openerSeq: 1,
openerUnread: false,
}])
- const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+ const snapshot = await getAccountAttentionProjection({} as never, "viewer", 2)
expect(snapshot.scopes).toEqual([{
scopeId: "c1",
@@ -183,12 +183,12 @@ describe("account attention snapshot", () => {
mocks.channels.mockResolvedValue([])
mocks.mentionScopes.mockResolvedValue([])
- const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+ const snapshot = await getAccountAttentionProjection({} 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()
+ expect(() => AccountAttentionProjectionSchema.parse(snapshot)).not.toThrow()
})
it("keeps a raced aggregate scope without requiring a bounded item row", async () => {
@@ -202,7 +202,7 @@ describe("account attention snapshot", () => {
}])
mocks.mentions.mockResolvedValue([])
- const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 2)
+ const snapshot = await getAccountAttentionProjection({} as never, "viewer", 2)
expect(snapshot.scopes).toEqual([expect.objectContaining({
scopeId: "c1",
@@ -211,7 +211,7 @@ describe("account attention snapshot", () => {
})])
expect(snapshot.items.filter((item) => item.kind !== "friend_request")).toEqual([])
expect(snapshot.truncated).toBe(true)
- expect(() => AccountAttentionSnapshotSchema.parse(snapshot)).not.toThrow()
+ expect(() => AccountAttentionProjectionSchema.parse(snapshot)).not.toThrow()
})
it("emits one explicit presentation unit for each unread forum opener", async () => {
@@ -260,7 +260,7 @@ describe("account attention snapshot", () => {
lastMessageAt: `2026-09-27T00:00:0${seq}.000Z`,
}))])
- const snapshot = await getAccountAttentionSnapshot({} as never, "viewer", 100)
+ const snapshot = await getAccountAttentionProjection({} as never, "viewer", 100)
const posts = snapshot.items.filter((entry) => entry.kind === "forum_post")
expect(posts).toEqual([
@@ -268,6 +268,6 @@ describe("account attention snapshot", () => {
expect.objectContaining({ sourceId: "post1", openerSeq: 1 }),
])
expect(snapshot.items.filter((entry) => entry.kind === "mention")).toEqual([])
- expect(() => AccountAttentionSnapshotSchema.parse(snapshot)).not.toThrow()
+ expect(() => AccountAttentionProjectionSchema.parse(snapshot)).not.toThrow()
})
})
diff --git a/src/shared/test/queries/community-dm-order.test.ts b/src/shared/test/queries/community-dm-order.test.ts
index 6bde47b4c..8efd680fc 100644
--- a/src/shared/test/queries/community-dm-order.test.ts
+++ b/src/shared/test/queries/community-dm-order.test.ts
@@ -14,13 +14,15 @@ describe("listDMs ordering", () => {
CREATE TABLE community_channel (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
+ server_id TEXT, category_id TEXT, name TEXT, topic TEXT NOT NULL DEFAULT '', position INTEGER NOT NULL DEFAULT 0,
+ parent_channel_id TEXT, parent_message_id TEXT, creator_id TEXT, message_count INTEGER NOT NULL DEFAULT 0, archived INTEGER NOT NULL DEFAULT 0,
last_message_at TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE community_channel_member (
channel_id TEXT NOT NULL,
user_id TEXT NOT NULL,
- relation TEXT NOT NULL
+ relation TEXT NOT NULL, source TEXT NOT NULL DEFAULT 'added'
);
CREATE TABLE user (
id TEXT PRIMARY KEY,
diff --git a/src/shared/test/queries/community-dm-unread-count-sqlite.test.ts b/src/shared/test/queries/community-dm-unread-count-sqlite.test.ts
index 75c7957a0..16338f0e1 100644
--- a/src/shared/test/queries/community-dm-unread-count-sqlite.test.ts
+++ b/src/shared/test/queries/community-dm-unread-count-sqlite.test.ts
@@ -3,6 +3,8 @@ import { communityWriteDb } from "../helpers/community-write-db"
import { createMessage } from "../../src/db/queries/community/message"
import { listEligibleUnreadDms } from "../../src/db/queries/community/inbox"
import { markReadToMessageBuilder } from "../../src/db/queries/community/read-state"
+import { listReadableMessageChannelsForUser } from "../../src/db/queries/community/channel"
+import { block } from "../../src/db/queries/community/friendship"
describe("DM unread counts against real SQLite", () => {
let fixture: ReturnType<typeof communityWriteDb>
@@ -14,6 +16,11 @@ describe("DM unread counts against real SQLite", () => {
ALTER TABLE user ADD COLUMN image TEXT;
ALTER TABLE user ADD COLUMN avatarVersion INTEGER NOT NULL DEFAULT 0;
CREATE TABLE community_notification_setting (user_id TEXT, server_id TEXT, channel_id TEXT, level TEXT);
+ ALTER TABLE community_friendship ADD COLUMN needs_owner_approval TEXT;
+ ALTER TABLE community_friendship ADD COLUMN blocker_id TEXT;
+ ALTER TABLE community_friendship ADD COLUMN created_at TEXT;
+ ALTER TABLE community_friendship ADD COLUMN updated_at TEXT;
+ ALTER TABLE community_friendship ADD COLUMN resolved_at TEXT;
UPDATE community_channel SET type = 'dm' WHERE id = 'channel';
INSERT INTO community_channel_member VALUES
('viewer', 'channel', 'author', 'access', 'added', NULL, 'now'),
@@ -39,4 +46,35 @@ describe("DM unread counts against real SQLite", () => {
await expect(listEligibleUnreadDms(fixture.db, "author")).resolves.toEqual([])
await expect(listEligibleUnreadDms(fixture.db, "outsider")).resolves.toEqual([])
})
+
+ it.each(["author", "peer"])("excludes the already-existing %s block using the complete read predicate", async blockerId => {
+ fixture.sqlite.exec(`
+ INSERT INTO user (id) VALUES ('allowed-peer');
+ INSERT INTO community_channel (id, type, created_at) VALUES ('allowed', 'dm', 'now');
+ INSERT INTO community_channel_member VALUES
+ ('allowed-viewer', 'allowed', 'author', 'access', 'added', NULL, 'now'),
+ ('allowed-peer', 'allowed', 'allowed-peer', 'access', 'added', NULL, 'now');
+ `)
+ await createMessage(fixture.db, { channelId: "channel", authorId: "peer", authorKind: "human", content: "Blocked unread" })
+ await createMessage(fixture.db, { channelId: "allowed", authorId: "allowed-peer", authorKind: "human", content: "Allowed unread" })
+ const result = await block(fixture.db, { blockerId, targetId: blockerId === "author" ? "peer" : "author" })
+ expect(result.row).toMatchObject({ status: "blocked", blockerId })
+ expect(result.row.createdAt).toEqual(expect.any(String))
+ expect(result.row.updatedAt).toEqual(expect.any(String))
+ expect((await listEligibleUnreadDms(fixture.db, "author")).map(row => row.channelId)).toEqual(["allowed"])
+ expect((await listReadableMessageChannelsForUser(fixture.db, "author", ["channel", "allowed"])).map(row => row.id)).toEqual(["allowed"])
+ })
+
+ it("scopes complete readable IDs before selecting and deduplicates the requested collection", async () => {
+ expect(await listReadableMessageChannelsForUser(fixture.db, "author", [])).toEqual([])
+ expect((await listReadableMessageChannelsForUser(fixture.db, "author", ["channel", "channel", "missing"])).map(row => row.id)).toEqual(["channel"])
+ expect(await listReadableMessageChannelsForUser(fixture.db, "outsider", ["channel"])).toEqual([])
+ })
+
+ it("requires a current peer for both eligible projection and full message read", async () => {
+ await createMessage(fixture.db, { channelId: "channel", authorId: "peer", authorKind: "human", content: "Unread" })
+ fixture.sqlite.prepare("DELETE FROM community_channel_member WHERE id = 'peer'").run()
+ expect(await listEligibleUnreadDms(fixture.db, "author")).toEqual([])
+ expect(await listReadableMessageChannelsForUser(fixture.db, "author", ["channel"])).toEqual([])
+ })
})
diff --git a/src/shared/test/queries/community-friendship-avatar-version.test.ts b/src/shared/test/queries/community-friendship-avatar-version.test.ts
index c617fe500..b32eb7582 100644
--- a/src/shared/test/queries/community-friendship-avatar-version.test.ts
+++ b/src/shared/test/queries/community-friendship-avatar-version.test.ts
@@ -83,6 +83,8 @@ describe("friend approval MESSAGE_CREATE identity", () => {
{ id: "bot1", name: "Bot", discriminator: "0002", image: "/bot", avatarVersion: 7, isBot: true, ownerUserId: "owner1" },
{ id: "owner1", name: "Owner", discriminator: "0003", image: null, avatarVersion: 0, isBot: false, ownerUserId: null },
],
+ [{ id: "bot1", name: "Bot", discriminator: "0002", image: "/bot", avatarVersion: 7 }],
+ [],
])
db.batch.mockResolvedValue([[], [inserted]])
@@ -123,6 +125,8 @@ describe("friend approval MESSAGE_CREATE identity", () => {
{ id: "bot2", name: "Bot Two", discriminator: "0002", image: "/bot2", avatarVersion: 9, isBot: true, ownerUserId: "owner2" },
{ id: "owner2", name: "Owner Two", discriminator: "0003", image: null, avatarVersion: 0, isBot: false, ownerUserId: null },
],
+ [{ id: "bot2", name: "Bot Two", discriminator: "0002", image: "/bot2", avatarVersion: 9 }],
+ [],
], [[updated]])
const result = await friendship.ownerDecideOnRow(db, {
diff --git a/src/shared/test/queries/community-invite.test.ts b/src/shared/test/queries/community-invite.test.ts
index d104d821a..68f82de04 100644
--- a/src/shared/test/queries/community-invite.test.ts
+++ b/src/shared/test/queries/community-invite.test.ts
@@ -16,7 +16,7 @@ describe("community invite quota consumption", () => {
image TEXT,
avatarVersion INTEGER NOT NULL DEFAULT 0,
avatarObjectKey TEXT,
- discriminator TEXT,
+ discriminator TEXT NOT NULL DEFAULT '0000',
isBot INTEGER NOT NULL DEFAULT 0,
ownerUserId TEXT,
deletedAt TEXT
@@ -108,6 +108,22 @@ describe("community invite quota consumption", () => {
.toEqual({ count: 0 });
});
+ it("does not consume capacity or create membership when the joining person is absent", async () => {
+ seedInvite(1);
+ await expect(useInvite(db as never, "token1", "missing")).resolves.toBeNull();
+ expect(sqlite.prepare("SELECT uses FROM community_server_invite WHERE id='iv1'").get()).toEqual({ uses: 0 });
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_server_member").get()).toEqual({ count: 0 });
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_funnel_analytics_event").get()).toEqual({ count: 0 });
+ });
+
+ it("rejects an invalid complete identity before member or capacity writes", async () => {
+ seedInvite(1);
+ sqlite.prepare("UPDATE user SET discriminator='' WHERE id='u1'").run();
+ await expect(useInvite(db as never, "token1", "u1")).rejects.toThrow();
+ expect(sqlite.prepare("SELECT uses FROM community_server_invite WHERE id='iv1'").get()).toEqual({ uses: 0 });
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_server_member").get()).toEqual({ count: 0 });
+ });
+
it("enforces the active invite cap inside the insert statement", async () => {
seedInvite(null);
diff --git a/src/shared/test/queries/community-user-profile.test.ts b/src/shared/test/queries/community-user-profile.test.ts
index 04075ad71..612bac357 100644
--- a/src/shared/test/queries/community-user-profile.test.ts
+++ b/src/shared/test/queries/community-user-profile.test.ts
@@ -96,11 +96,17 @@ describe("getPublicProfileForViewer", () => {
aboutMe: "",
bannerColor: null,
statusEmoji: null,
- statusText: "",
+ statusText: null,
identity: { kind: "human" },
});
});
+ it.each([null, "", "Busy"])("preserves explicit status %s through actual insert and public SQL read", async statusText => {
+ await profileQueries.updateProfile(db, "human_1", { statusEmoji: null, statusText })
+ expect(sqlite.prepare("SELECT status_text FROM community_user_profile WHERE user_id=?").get("human_1")).toEqual({ status_text: statusText })
+ expect((await profileQueries.getPublicProfileForViewer(db, "human_1", "viewer_1"))?.statusText).toBe(statusText)
+ })
+
it("returns canonical public owner navigation and SQL-derived viewer ownership", async () => {
const ownerView = await profileQueries.getPublicProfileForViewer(db, "bot_1", "owner_1");
expect(ownerView).toEqual({
diff --git a/src/shared/test/queries/param-limit.test.ts b/src/shared/test/queries/param-limit.test.ts
index 170dd5afd..7aaaac10e 100644
--- a/src/shared/test/queries/param-limit.test.ts
+++ b/src/shared/test/queries/param-limit.test.ts
@@ -1,4 +1,5 @@
-import { describe, it, expect, vi } from "vitest";
+import { afterEach, describe, it, expect, vi } from "vitest";
+import Sqlite from "better-sqlite3";
import { drizzle } from "drizzle-orm/d1";
import {
communityMention,
@@ -21,6 +22,7 @@ import * as agentQueries from "../../src/db/queries/agent";
import * as conversationQueries from "../../src/db/queries/conversation";
import * as meetingQueries from "../../src/db/queries/meeting-session";
import * as userQueries from "../../src/db/queries/user";
+import * as userProfileQueries from "../../src/db/queries/community/user-profile";
import { D1_MAX_BIND_PARAMS } from "../../src/db/queries/_chunk";
const fakeDb = drizzle({} as never);
@@ -436,3 +438,130 @@ describe("high-cardinality query bind matrix", () => {
}
});
});
+
+
+describe("resource reads through the D1 adapter and local SQLite", () => {
+ const connections: Sqlite.Database[] = [];
+ const cases = [
+ { count: 0, sizes: [] },
+ { count: 90, sizes: [90] },
+ { count: 91, sizes: [90, 1] },
+ { count: 181, sizes: [90, 90, 1] },
+ ];
+
+ afterEach(() => {
+ for (const sqlite of connections) sqlite.close();
+ connections.length = 0;
+ });
+
+ function resourceDb() {
+ const sqlite = new Sqlite(":memory:");
+ connections.push(sqlite);
+ sqlite.exec(`
+ CREATE TABLE community_channel_member (
+ channel_id TEXT, user_id TEXT, relation TEXT, source TEXT,
+ PRIMARY KEY (channel_id, user_id, relation)
+ );
+ CREATE TABLE community_user_profile (
+ user_id TEXT PRIMARY KEY, about_me TEXT, banner_color TEXT,
+ status_emoji TEXT, status_text TEXT
+ );
+ `);
+ const statements: Array<{ sql: string; params: unknown[] }> = [];
+ const client = {
+ prepare(sql: string) {
+ return {
+ bind(...params: unknown[]) {
+ statements.push({ sql, params });
+ expect(params.length).toBeLessThanOrEqual(D1_MAX_BIND_PARAMS);
+ return { raw: async () => sqlite.prepare(sql).raw(true).all(...params) };
+ },
+ };
+ },
+ };
+ return { sqlite, db: drizzle(client as never), statements };
+ }
+
+ it.each(cases)("reads all $count requested channels for only the original viewer", async ({ count, sizes }) => {
+ const { sqlite, db, statements } = resourceDb();
+ const ids = Array.from({ length: count }, (_, index) => `channel_${index}`);
+ const insert = sqlite.prepare("INSERT INTO community_channel_member VALUES (?, ?, ?, ?)");
+ for (const id of ids) {
+ insert.run(id, "viewer-a", "access", "added");
+ insert.run(id, "viewer-b", "access", "added");
+ }
+ insert.run("outside-channel", "viewer-a", "access", "added");
+ if (ids.length) insert.run(ids[0], "viewer-a", "notify", "mention");
+
+ const rows = await channelQueries.listChannelMembershipsForUserInChannels(db as never, "viewer-a", ids);
+ const expected = ids.map(channelId => ({ channelId, userId: "viewer-a", relation: "access", source: "added" }));
+ if (ids.length) expected.push({ channelId: ids[0]!, userId: "viewer-a", relation: "notify", source: "mention" });
+ const ordered = (values: typeof rows) => [...values].sort((a, b) => `${a.channelId}:${a.relation}`.localeCompare(`${b.channelId}:${b.relation}`));
+
+ expect(ordered(rows)).toEqual(ordered(expected));
+ expect(statements.map(({ params }) => params.length)).toEqual(sizes.map(size => size + 1));
+ expect(statements.flatMap(({ params }) => params.slice(1))).toEqual(ids);
+ for (const statement of statements) {
+ expect(statement.sql).toContain('"community_channel_member"."user_id" = ?');
+ expect(statement.sql).toContain('"community_channel_member"."channel_id" in');
+ expect(statement.params[0]).toBe("viewer-a");
+ }
+ console.info(JSON.stringify({ case: "resource-memberships-local-sqlite", ids: count, binds: statements.map(row => row.params.length), rows: rows.length }));
+ });
+
+ it.each(cases)("reads all $count requested public profiles without unrequested IDs", async ({ count, sizes }) => {
+ const { sqlite, db, statements } = resourceDb();
+ const ids = Array.from({ length: count }, (_, index) => `profile_${index}`);
+ const insert = sqlite.prepare("INSERT INTO community_user_profile VALUES (?, ?, ?, ?, ?)");
+ for (const id of ids) insert.run(id, `about-${id}`, null, null, `status-${id}`);
+ insert.run("outside-profile", "outside", null, null, "outside");
+
+ const rows = await userProfileQueries.getProfilesByUserIds(db as never, ids);
+
+ expect([...rows].sort((a, b) => a.userId.localeCompare(b.userId))).toEqual(ids.map(userId => ({ userId, aboutMe: `about-${userId}`, bannerColor: null, statusEmoji: null, statusText: `status-${userId}` })).sort((a, b) => a.userId.localeCompare(b.userId)));
+ expect(statements.map(({ params }) => params.length)).toEqual(sizes);
+ expect(statements.flatMap(({ params }) => params)).toEqual(ids);
+ console.info(JSON.stringify({ case: "resource-profiles-local-sqlite", ids: count, binds: statements.map(row => row.params.length), rows: rows.length }));
+ });
+
+ it("deduplicates membership IDs across slices and preserves input and both relations", async () => {
+ const { sqlite, db, statements } = resourceDb();
+ const ids = Array.from({ length: 91 }, (_, index) => `channel_${index}`);
+ const input = [...ids.slice(0, 90), ids[0]!, ids[90]!, ids[50]!];
+ const original = [...input];
+ const insert = sqlite.prepare("INSERT INTO community_channel_member VALUES (?, ?, ?, ?)");
+ for (const id of ids) insert.run(id, "viewer-a", "access", "added");
+ insert.run(ids[0], "viewer-a", "notify", "mention");
+ insert.run(ids[0], "viewer-b", "access", "added");
+ insert.run("outside-channel", "viewer-a", "access", "added");
+
+ const rows = await channelQueries.listChannelMembershipsForUserInChannels(db as never, "viewer-a", input);
+
+ expect(rows).toHaveLength(92);
+ expect(new Set(rows.map(row => `${row.channelId}:${row.userId}:${row.relation}`)).size).toBe(92);
+ expect(rows.every(row => row.userId === "viewer-a" && ids.includes(row.channelId))).toBe(true);
+ expect(rows.filter(row => row.channelId === ids[0]).map(row => row.relation).sort()).toEqual(["access", "notify"]);
+ expect(statements.map(({ params }) => params.length)).toEqual([91, 2]);
+ expect(statements.flatMap(({ params }) => params.slice(1))).toEqual(ids);
+ expect(input).toEqual(original);
+ });
+
+ it("deduplicates profile IDs across slices without changing input or nullable facts", async () => {
+ const { sqlite, db, statements } = resourceDb();
+ const ids = Array.from({ length: 91 }, (_, index) => `profile_${index}`);
+ const input = [...ids.slice(0, 90), ids[0]!, ids[90]!, ids[50]!];
+ const original = [...input];
+ const insert = sqlite.prepare("INSERT INTO community_user_profile VALUES (?, ?, ?, ?, ?)");
+ for (const id of ids) insert.run(id, null, null, null, "");
+ insert.run("outside-profile", "outside", null, null, "outside");
+
+ const rows = await userProfileQueries.getProfilesByUserIds(db as never, input);
+
+ expect(rows.map(row => row.userId).sort()).toEqual([...ids].sort());
+ expect(new Set(rows.map(row => row.userId)).size).toBe(91);
+ expect(rows.every(row => row.aboutMe === null && row.bannerColor === null && row.statusEmoji === null && row.statusText === "")).toBe(true);
+ expect(statements.map(({ params }) => params.length)).toEqual([90, 1]);
+ expect(statements.flatMap(({ params }) => params)).toEqual(ids);
+ expect(input).toEqual(original);
+ });
+});
diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.ts
index 36b9f2f8a..b9fba80b8 100644
--- a/src/web/cloudflare-env.d.ts
+++ b/src/web/cloudflare-env.d.ts
@@ -1,6 +1,6 @@
/* 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: 5e4ba6c8ad02e084794491e734aadb54)
-// Runtime types generated with [email protected] 2026-09-07 global_fetch_strictly_public,nodejs_compat
+// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 06acdb2d39ee41184aa3cd9b11551d2c)
+// Runtime types generated with [email protected] 2026-09-07 global_fetch_strictly_public,nodejs_compat
interface __BaseEnv_CloudflareEnv {
CACHE_KV: KVNamespace;
NEXT_INC_CACHE_R2_BUCKET: R2Bucket;
@@ -12,9 +12,8 @@ interface __BaseEnv_CloudflareEnv {
TASK_QUEUE: Queue;
CF_VERSION_METADATA: WorkerVersionMetadata;
ASSETS: Fetcher;
- COMMUNITY_EVENT_CONTRACT: "1";
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";
+ MIN_CLI_VERSION: "0.1.47";
BLOG_DISCOVERY_REQUIRED: "true";
JEV_PROVIDER: "openrouter";
JEV_WAKE_THRESHOLD: "0.50";
@@ -23,6 +22,7 @@ interface __BaseEnv_CloudflareEnv {
TYPESAFE_JEV_BASE_URL: "https://api.typesafe.ai";
TYPESAFE_JEV_MODEL: "jev-1.13.0";
BETTER_AUTH_SECRET: string;
+ RESEND_API_KEY: string;
BETTER_AUTH_URL: string;
ENCRYPTION_KEY: string;
GITHUB_CLIENT_ID: string;
@@ -55,9 +55,32 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "COMMUNITY_EVENT_CONTRACT" | "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "JEV_PROVIDER" | "JEV_WAKE_THRESHOLD" | "OPENROUTER_JEV_BASE_URL" | "OPENROUTER_JEV_MODEL" | "TYPESAFE_JEV_BASE_URL" | "TYPESAFE_JEV_MODEL" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "APPLE_CLIENT_ID" | "APPLE_TEAM_ID" | "APPLE_KEY_ID" | "APPLE_PRIVATE_KEY" | "DEVICE_CLIENT_IDS" | "OPENROUTER_API_KEY" | "TYPESAFE_API_KEY">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "JEV_PROVIDER" | "JEV_WAKE_THRESHOLD" | "OPENROUTER_JEV_BASE_URL" | "OPENROUTER_JEV_MODEL" | "TYPESAFE_JEV_BASE_URL" | "TYPESAFE_JEV_MODEL" | "BETTER_AUTH_SECRET" | "RESEND_API_KEY" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "APPLE_CLIENT_ID" | "APPLE_TEAM_ID" | "APPLE_KEY_ID" | "APPLE_PRIVATE_KEY" | "DEVICE_CLIENT_IDS" | "OPENROUTER_API_KEY" | "TYPESAFE_API_KEY">> {}
+}
+declare module "*.txt" {
+ const value: string;
+ export default value;
+}
+declare module "*.html" {
+ const value: string;
+ export default value;
+}
+declare module "*.sql" {
+ const value: string;
+ export default value;
+}
+declare module "*.bin" {
+ const value: ArrayBuffer;
+ export default value;
+}
+declare module "*.wasm" {
+ const value: WebAssembly.Module;
+ export default value;
+}
+declare module "*.wasm?module" {
+ const value: WebAssembly.Module;
+ export default value;
}
-
// Begin runtime types
/*! *****************************************************************************
Copyright (c) Cloudflare. All rights reserved.
@@ -491,7 +514,7 @@ type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props
type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
type ExportedHandlerTailHandler<Env = unknown, Props = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
type ExportedHandlerTraceHandler<Env = unknown, Props = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
-type ExportedHandlerTailStreamHandler<Env = unknown, Props = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext<Props>) => TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;
+type ExportedHandlerTailStreamHandler<Env = unknown, Props = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext<Props>) => TailStream.TailEventHandlerType | undefined | Promise<TailStream.TailEventHandlerType | undefined>;
type ExportedHandlerScheduledHandler<Env = unknown, Props = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
type ExportedHandlerQueueHandler<Env = unknown, Message = unknown, Props = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
type ExportedHandlerTestHandler<Env = unknown, Props = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
@@ -540,6 +563,7 @@ interface CachePurgeOptions {
}
interface CacheContext {
purge(options: CachePurgeOptions): Promise<CachePurgeResult>;
+ invalidate(options: CachePurgeOptions): Promise<CachePurgeResult>;
}
interface CloudflareAccessContext {
readonly aud: string;
@@ -1248,6 +1272,8 @@ interface JsonWebKey {
qi?: string;
oth?: RsaOtherPrimesInfo[];
k?: string;
+ pub?: string;
+ priv?: string;
}
interface RsaOtherPrimesInfo {
r?: string;
@@ -1294,6 +1320,7 @@ interface SubtleCryptoSignAlgorithm {
hash?: (string | SubtleCryptoHashAlgorithm);
dataLength?: number;
saltLength?: number;
+ context?: ArrayBuffer | ArrayBufferView;
}
interface CryptoKeyKeyAlgorithm {
name: string;
@@ -1473,7 +1500,7 @@ interface MessageEventInit {
data?: any;
origin?: string;
lastEventId?: string;
- source?: MessagePort;
+ source?: (MessagePort | null);
ports?: MessagePort[];
}
/**
@@ -3338,13 +3365,7 @@ declare abstract class SqlStorageStatement {
}
type SqlStorageValue = ArrayBuffer | string | number | null;
declare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {
- next(): {
- done?: false;
- value: T;
- } | {
- done: true;
- value?: never;
- };
+ next(): IteratorResult<T, undefined>;
toArray(): T[];
one(): T;
raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
@@ -3472,7 +3493,7 @@ interface Container {
setInactivityTimeout(durationMs: number | bigint): Promise<void>;
interceptOutboundHttp(addr: string, binding: Fetcher): Promise<void>;
interceptAllOutboundHttp(binding: Fetcher): Promise<void>;
- snapshotContainer(options: ContainerSnapshotOptions): Promise<ContainerSnapshot>;
+ snapshotContainer(options?: ContainerSnapshotOptions): Promise<ContainerSnapshot>;
interceptOutboundHttps(addr: string, binding: Fetcher): Promise<void>;
exec(cmd: string[], options?: ContainerExecOptions): Promise<ExecProcess>;
inspect(): Promise<ContainerInfo | null>;
@@ -3505,7 +3526,7 @@ type ContainerStartupOptions = {
entrypoint?: string[];
enableInternet: boolean;
env?: Record<string, string>;
- instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;
+ instance?: "lite" | "basic" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;
labels?: Record<string, string>;
directorySnapshots?: ContainerDirectorySnapshotRestoreParams[];
} & ({
@@ -3574,7 +3595,7 @@ declare class MessageChannel {
interface MessagePortPostMessageOptions {
transfer?: any[];
}
-type LoopbackForExport<T extends (new (...args: any[]) => Rpc.EntrypointBranded) | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub<InstanceType<T>> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass<InstanceType<T>> : T extends ExportedHandler<any, any, any> ? LoopbackServiceStub<undefined> : undefined;
+type LoopbackForExport<T extends (new (...args: any[]) => Rpc.EntrypointBranded) | ExportedHandler<any, any, any> | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub<InstanceType<T>> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass<InstanceType<T>> : T extends new (...args: any[]) => CloudflareWorkersModule.WorkflowEntrypoint<any, infer Params> ? Workflow<Params> : T extends ExportedHandler<any, any, any> ? LoopbackServiceStub<undefined> : undefined;
type LoopbackServiceStub<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T> & (T extends CloudflareWorkersModule.WorkerEntrypoint<any, infer Props> ? (opts: {
props?: Props;
}) => Fetcher<T> : (opts: {
@@ -3670,6 +3691,7 @@ interface Tracing {
}
declare abstract class Span {
get isTraced(): boolean;
+ spanContext(): TracingSpanContext;
setAttribute(key: string, value: boolean | number | string): this;
setAttributes(attributes: Record<string, boolean | number | string | undefined>): this;
recordException(exception: string | {
@@ -3688,8 +3710,20 @@ declare abstract class Span {
message: string;
stack?: string;
}): void;
+ updateName(name: string): this;
+ setStatus(status: TracingSpanStatus): this;
end(): void;
}
+type TracingSpanStatusCode = "unset" | "ok" | "error";
+interface TracingSpanStatus {
+ code: TracingSpanStatusCode;
+ message?: string;
+}
+interface TracingSpanContext {
+ traceId: string;
+ spanId: string;
+ traceFlags: number;
+}
/**
* Represents the identity of a user authenticated via Cloudflare Access.
* This matches the result of calling /cdn-cgi/access/get-identity.
@@ -5202,8 +5236,13 @@ type WebSearchOptions = {
search_context_size?: "low" | "medium" | "high";
user_location?: WebSearchUserLocation;
};
+// Source of truth for per-model reasoning types: each model's `reasoning_effort` metadata
+// in Workers AI ConfigAPI (supported efforts, aliases, defaults, and whether reasoning can
+// be turned off). The Workers AI SDK type generator (cloudflare/ai/sdk,
+// apps/worker-constellation-entry/scripts/build-types) turns it into the per-model
+// `inputs` types below; the developer docs model schemas come from the same metadata.
type ChatTemplateKwargs = {
- /** Whether to enable reasoning, enabled by default. */
+ /** Whether to enable reasoning. Support and defaults depend on the model. */
enable_thinking?: boolean;
/** If false, preserves reasoning context between turns. */
clear_thinking?: boolean;
@@ -5224,6 +5263,7 @@ type ChatCompletionsCommonOptions = {
parallel_tool_calls?: boolean;
prediction?: PredictionContent;
presence_penalty?: number | null;
+ /** Reasoning effort. Supported levels depend on the model. */
reasoning_effort?: "low" | "medium" | "high" | null;
chat_template_kwargs?: ChatTemplateKwargs;
response_format?: ResponseFormat;
@@ -9239,11 +9279,59 @@ declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {
postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;
}
declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {
- inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;
+ inputs: XOR<Omit<ResponsesInput, "reasoning"> & {
+ reasoning?: (Omit<Reasoning, "effort"> & {
+ /**
+ * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
+ *
+ * @default "medium"
+ */
+ effort?: "low" | "medium" | "high" | null;
+ }) | null;
+ }, Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
+ *
+ * @default "medium"
+ */
+ reasoning_effort?: "low" | "medium" | "high" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Reasoning is always enabled for this model and cannot be disabled.
+ *
+ * @default true
+ */
+ enable_thinking?: true;
+ };
+ }>;
postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
}
declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {
- inputs: XOR<ResponsesInput, ChatCompletionsMessagesInput>;
+ inputs: XOR<Omit<ResponsesInput, "reasoning"> & {
+ reasoning?: (Omit<Reasoning, "effort"> & {
+ /**
+ * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
+ *
+ * @default "medium"
+ */
+ effort?: "low" | "medium" | "high" | null;
+ }) | null;
+ }, Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
+ *
+ * @default "medium"
+ */
+ reasoning_effort?: "low" | "medium" | "high" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Reasoning is always enabled for this model and cannot be disabled.
+ *
+ * @default true
+ */
+ enable_thinking?: true;
+ };
+ }>;
postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
}
interface Ai_Cf_Leonardo_Phoenix_1_0_Input {
@@ -10212,7 +10300,16 @@ declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B {
postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output;
}
declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Whether to enable reasoning for this model. This model has no reasoning effort levels.
+ *
+ * @default true
+ */
+ enable_thinking?: boolean;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {
@@ -10220,23 +10317,146 @@ declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {
postProcessedOutputs: ChatCompletionsOutput;
}
declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: high, none. Compatibility aliases (accepted by the API, not by these types): low maps to high; medium maps to high; max maps to high.
+ *
+ * @default "high"
+ */
+ reasoning_effort?: "high" | "none" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Whether to enable reasoning for this model.
+ *
+ * @default true
+ */
+ enable_thinking?: boolean;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
+type Ai_Cf_Nvidia_Nemotron_3_120B_A12B_Input = Omit<ChatCompletionsInput, "model" | "max_tokens" | "metadata" | "modalities" | "chat_template_kwargs" | "store" | "reasoning_effort"> & {
+ /**
+ * ID of the model to use (for example, '@cf/nvidia/nemotron-3-120b-a12b').
+ */
+ model?: ChatCompletionsInput["model"];
+ /**
+ * The maximum number of tokens to generate.
+ */
+ max_tokens?: ChatCompletionsInput["max_tokens"];
+ /**
+ * Set of key-value pairs that can be attached to the object.
+ */
+ metadata?: ChatCompletionsInput["metadata"];
+ /**
+ * Output types requested from the model.
+ */
+ modalities?: ChatCompletionsInput["modalities"];
+ /**
+ * Nemotron chat-template controls for normal reasoning, low-effort reasoning, and non-reasoning responses.
+ */
+ chat_template_kwargs?: {
+ /**
+ * Whether to enable reasoning. Reasoning is enabled by default.
+ */
+ enable_thinking?: boolean;
+ /**
+ * When reasoning is enabled, use Nemotron's low-effort reasoning mode, which uses significantly fewer reasoning tokens.
+ */
+ low_effort?: boolean;
+ /**
+ * For coding agent use, Nvidia suggests setting force_nonempty_content=true
+ */
+ force_nonempty_content?: boolean;
+ };
+ /**
+ * Whether to store the output for model distillation or evaluation.
+ *
+ * @default false
+ */
+ store?: ChatCompletionsInput["store"];
+};
declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B {
- inputs: ChatCompletionsInput;
+ inputs: Ai_Cf_Nvidia_Nemotron_3_120B_A12B_Input;
postProcessedOutputs: ChatCompletionsOutput;
}
-declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT {
- inputs: ChatCompletionsInput;
+type Ai_Cf_Google_Gemma_4_26B_A4B_It_Input = Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Whether to enable reasoning for this model. This model has no reasoning effort levels.
+ *
+ * @default true
+ */
+ enable_thinking?: boolean;
+ };
+} & {
+ /**
+ * @default false
+ */
+ skip_special_tokens?: boolean;
+};
+declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_It {
+ inputs: Ai_Cf_Google_Gemma_4_26B_A4B_It_Input;
postProcessedOutputs: ChatCompletionsOutput;
}
+/** @deprecated Use Base_Ai_Cf_Google_Gemma_4_26B_A4B_It. */
+declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT extends Base_Ai_Cf_Google_Gemma_4_26B_A4B_It {
+}
+type Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Input = {
+ /**
+ * readable stream with audio data and content-type specified for that data
+ */
+ audio: {
+ body: object;
+ contentType: string;
+ };
+} | {
+ /**
+ * base64 encoded audio data
+ */
+ audio: string;
+ encoding?: "wav" | "flac" | "ogg" | "linear16";
+ sample_rate?: number;
+ channels?: number;
+};
+interface Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Output {
+ text?: string;
+ duration?: number;
+}
+declare abstract class Base_Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B {
+ inputs: Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Input;
+ postProcessedOutputs: Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Output;
+}
declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Reasoning is always enabled for this model and cannot be disabled. This model has no reasoning effort levels.
+ *
+ * @default true
+ */
+ enable_thinking?: true;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_2 {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: max, high, none. Compatibility aliases (accepted by the API, not by these types): low maps to high; medium maps to high; xhigh maps to max; minimal maps to none.
+ *
+ * @default "max"
+ */
+ reasoning_effort?: "max" | "high" | "none" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Whether to enable reasoning for this model.
+ *
+ * @default true
+ */
+ enable_thinking?: boolean;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input {
@@ -10373,26 +10593,104 @@ declare abstract class Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B {
postProcessedOutputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output;
}
declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731 {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: max, high, low, none. Compatibility aliases (accepted by the API, not by these types): minimal maps to low; medium maps to high; xhigh maps to high.
+ *
+ * @default "high"
+ */
+ reasoning_effort?: "max" | "high" | "low" | "none" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Whether to enable reasoning for this model.
+ *
+ * @default true
+ */
+ enable_thinking?: boolean;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813 {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: max, high, low, none. Compatibility aliases (accepted by the API, not by these types): minimal maps to low; medium maps to high; xhigh maps to high.
+ *
+ * @default "high"
+ */
+ reasoning_effort?: "max" | "high" | "low" | "none" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Whether to enable reasoning for this model.
+ *
+ * @default true
+ */
+ enable_thinking?: boolean;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
declare abstract class Base_Ai_Cf_Qwen_Qwen3_8_27B {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: low, medium, xhigh.
+ *
+ * @default "xhigh"
+ */
+ reasoning_effort?: "low" | "medium" | "xhigh" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Whether to enable reasoning for this model.
+ *
+ * @default true
+ */
+ enable_thinking?: boolean;
+ };
+ };
+ postProcessedOutputs: ChatCompletionsOutput;
+}
+declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3 {
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: max, high, low. Reasoning cannot be disabled. Compatibility aliases (accepted by the API, not by these types): none maps to max; minimal maps to max; medium maps to max; xhigh maps to max.
+ *
+ * @default "max"
+ */
+ reasoning_effort?: "max" | "high" | "low" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Reasoning is always enabled for this model and cannot be disabled.
+ *
+ * @default true
+ */
+ enable_thinking?: true;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3_Flash {
- inputs: ChatCompletionsInput;
+ inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
+ /**
+ * Reasoning effort. Supported levels: max, high, low. Reasoning cannot be disabled. Compatibility aliases (accepted by the API, not by these types): none maps to max; minimal maps to max; medium maps to max; xhigh maps to max.
+ *
+ * @default "max"
+ */
+ reasoning_effort?: "max" | "high" | "low" | null;
+ chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
+ /**
+ * Reasoning is always enabled for this model and cannot be disabled.
+ *
+ * @default true
+ */
+ enable_thinking?: true;
+ };
+ };
postProcessedOutputs: ChatCompletionsOutput;
}
interface AiModels {
"@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification;
"@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage;
"@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage;
- "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage;
"@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage;
"@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage;
"@cf/myshell-ai/melotts": BaseAiTextToSpeech;
@@ -10479,13 +10777,15 @@ interface AiModels {
"@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5;
"@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6;
"@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B;
- "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT;
+ "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_It;
+ "@cf/nvidia/nemotron-speech-streaming-en-0.6b": Base_Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B;
"@cf/moonshotai/kimi-k2.7-code": Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code;
"@cf/zai-org/glm-5.2": Base_Ai_Cf_Zai_Org_Glm_5_2;
"@cf/moondream/moondream3.1-9B-A2B": Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B;
"@cf/deepseek-ai/deepseek-v4-flash-0731": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731;
"@cf/deepseek-ai/deepseek-v4-pro-0813": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813;
"@cf/qwen/qwen3.8-27b": Base_Ai_Cf_Qwen_Qwen3_8_27B;
+ "@cf/zai-org/glm-5.3": Base_Ai_Cf_Zai_Org_Glm_5_3;
"@cf/zai-org/glm-5.3-flash": Base_Ai_Cf_Zai_Org_Glm_5_3_Flash;
}
type AiOptions = {
@@ -10549,9 +10849,22 @@ type AiModelListType = Record<string, any>;
type AiAsyncBatchResponse = {
request_id: string;
};
+type AiWebSearchRequest = {
+ /** AI Gateway configuration used for this request. */
+ gatewayId: string;
+ /** Search query. */
+ query: string;
+ /** Maximum number of results. Defaults to 10 and is capped at 20. */
+ limit?: number;
+ /** Optional BYOK web-search provider configured on the gateway. */
+ provider?: string;
+ /** Optional BYOK key alias. Defaults to `default`. */
+ byokAlias?: string;
+};
declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {
aiGatewayLogId: string | null;
gateway(gatewayId: string): AiGateway;
+ websearch(request: AiWebSearchRequest): Promise<Response>;
/**
* @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.
* See https://developers.cloudflare.com/ai-search/usage/workers-binding/
@@ -10695,6 +11008,29 @@ declare abstract class AiGateway {
}): Promise<Response>;
getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line
}
+/** A parameter accepted by an Analytics SQL query. */
+type AnalyticsSQLParameter = string | number | boolean | null;
+/** An Analytics SQL query and its optional positional or named parameters. */
+interface AnalyticsSQLQuery {
+ query: string;
+ params?: readonly AnalyticsSQLParameter[] | Readonly<Record<string, AnalyticsSQLParameter>>;
+}
+/** Execution statistics returned by Analytics SQL. */
+interface AnalyticsSQLStatistics {
+ elapsed_ms: number;
+ rows_read: number;
+ bytes_read: number;
+}
+/** The rows and execution statistics returned by an Analytics SQL query. */
+interface AnalyticsSQLResult<T extends Record<string, unknown> = Record<string, unknown>> {
+ data: T[];
+ rows: number;
+ statistics: AnalyticsSQLStatistics;
+}
+/** An Analytics SQL binding. */
+interface AnalyticsSQLBinding {
+ query<T extends Record<string, unknown> = Record<string, unknown>>(request: AnalyticsSQLQuery): Promise<AnalyticsSQLResult<T>>;
+}
// Copyright (c) 2022-2025 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0
@@ -10741,8 +11077,6 @@ interface ArtifactsCreateRepoResult {
remote: string;
/** Plaintext access token (only returned at creation time). */
token: string;
- /** ISO 8601 token expiry timestamp. */
- tokenExpiresAt: string;
}
/** Paginated list of repositories. */
interface ArtifactsRepoListResult {
@@ -10785,11 +11119,62 @@ interface ArtifactsTokenListResult {
total: number;
}
/**
- * Handle for a single repository. Returned by Artifacts.get().
+ * Classification of a Git tree entry derived from its mode.
*
+ * `tree` is a directory, `blob` is a regular file, `symlink` is a symbolic link,
+ * `gitlink` is a submodule reference, and `exec` is an executable file.
+ */
+type ArtifactsTreeEntryType = 'tree' | 'blob' | 'symlink' | 'gitlink' | 'exec';
+/** An immediate child of a Git tree returned by {@link ArtifactsRepo.readTree}. */
+interface ArtifactsTreeEntry {
+ /** Name relative to the tree being read. */
+ name: string;
+ /** Canonical Git mode, such as `100644` for a file or `40000` for a tree. */
+ mode: string;
+ /** Lowercase, 40-character SHA-1 object ID. */
+ hash: string;
+ /** Classification derived from `mode`. */
+ type: ArtifactsTreeEntryType;
+}
+/** Decoded metadata returned by {@link ArtifactsRepo.readCommit} and {@link ArtifactsRepo.log}. */
+interface ArtifactsCommitMetadata {
+ /** Lowercase, 40-character SHA-1 commit ID. */
+ hash: string;
+ /** Lowercase, 40-character SHA-1 ID of the commit's root tree. */
+ treeHash: string;
+ /** Commit message with one trailing newline removed, if present. */
+ message: string;
+ /** Author identity from the commit. */
+ author: {
+ /** Author name. */
+ name: string;
+ /** Author email address. */
+ email: string;
+ };
+ /** Committer identity from the commit. */
+ committer: {
+ /** Committer name. */
+ name: string;
+ /** Committer email address. */
+ email: string;
+ };
+ /** Parent commit IDs in Git order; empty for a root commit. */
+ parents: string[];
+ /** Author timestamp in Unix seconds. */
+ authoredAt: number;
+ /** Committer timestamp in Unix seconds. */
+ committedAt: number;
+}
+/**
+ * Repository capability returned by {@link Artifacts.get}.
+ *
+ * Metadata is available through {@link info}, not as properties on the capability.
* Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.
+ *
+ * The capability is an RPC stub. Dispose of it when finished, for example with
+ * `using repo = await env.ARTIFACTS.get(name);`, to release it before the request ends.
*/
-interface ArtifactsRepo extends ArtifactsRepoInfo {
+interface ArtifactsRepo extends Disposable {
/**
* Create an access token for this repo.
* @param scope Token scope: "write" (default) or "read".
@@ -10806,6 +11191,69 @@ interface ArtifactsRepo extends ArtifactsRepoInfo {
* @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty.
*/
revokeToken(tokenOrId: string): Promise<boolean>;
+ /**
+ * Retrieve current repository metadata. Each call performs a fresh lookup.
+ * @returns Current public repository metadata.
+ * @throws {ArtifactsError} `NOT_FOUND` if the repository was deleted, or `INTERNAL_ERROR` on
+ * an unexpected lookup failure.
+ */
+ info(): Promise<ArtifactsRepoInfo>;
+ /**
+ * Read the raw bytes of a Git blob by object ID.
+ * @param hash Lowercase, 40-character SHA-1 object ID.
+ * @returns An untyped {@link Blob}, or `null` if the object is missing or is not a Git blob.
+ * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, `MEMORY_LIMIT` if the object
+ * cannot be buffered safely, or `INTERNAL_ERROR` on an unexpected read failure.
+ * @see {@link ArtifactsRepo.readFile} to resolve a file by ref and path.
+ */
+ readBlob(hash: string): Promise<Blob | null>;
+ /**
+ * Read the immediate children of a Git tree by object ID.
+ * @param hash Lowercase, 40-character SHA-1 tree ID.
+ * @returns Tree entries, or `null` if the object is missing.
+ * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, or `INTERNAL_ERROR` if the
+ * object is not a valid tree or the read fails unexpectedly.
+ * @see {@link ArtifactsTreeEntry}
+ */
+ readTree(hash: string): Promise<ArtifactsTreeEntry[] | null>;
+ /**
+ * Decode a Git commit by object ID.
+ * @param hash Lowercase, 40-character SHA-1 commit ID.
+ * @returns Commit metadata, or `null` if the object is missing.
+ * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, or `INTERNAL_ERROR` if the
+ * object is not a valid commit or the read fails unexpectedly.
+ * @see {@link ArtifactsCommitMetadata}
+ */
+ readCommit(hash: string): Promise<ArtifactsCommitMetadata | null>;
+ /**
+ * Resolve a file from a branch, tag, or commit ID and return its bytes with a browser-safe
+ * content type in {@link Blob.type}.
+ * @param args File lookup options.
+ * @param args.ref Branch, tag, or commit ID to resolve.
+ * @param args.path Non-empty repository-relative path.
+ * @returns A MIME-typed {@link Blob}, or `null` if the ref or path cannot resolve to a file.
+ * @throws {ArtifactsError} `INVALID_INPUT` if either argument is empty, `MEMORY_LIMIT` if the
+ * file cannot be buffered safely, or `INTERNAL_ERROR` on an unexpected read failure.
+ */
+ readFile(args: {
+ ref: string;
+ path: string;
+ }): Promise<Blob | null>;
+ /**
+ * List commits along the first-parent chain, newest first.
+ * @param opts History options. All fields are optional.
+ * @param opts.ref Branch, tag, or commit ID; defaults to `HEAD`.
+ * @param opts.limit Maximum results; defaults to `50` and is capped at `1000`.
+ * @param opts.offset Number of matching commits to skip; defaults to `0`.
+ * @returns Commit metadata, or an empty array if the ref cannot be resolved.
+ * @throws {ArtifactsError} `INTERNAL_ERROR` on an unexpected traversal failure.
+ * @see {@link ArtifactsCommitMetadata}
+ */
+ log(opts?: {
+ ref?: string;
+ limit?: number;
+ offset?: number;
+ }): Promise<ArtifactsCommitMetadata[]>;
// ── Fork ──
/**
* Fork this repo to a new repo.
@@ -10827,7 +11275,7 @@ interface ArtifactsRepo extends ArtifactsRepoInfo {
*
* Each code maps to a numeric code available on `ArtifactsError.numericCode`.
*/
-type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR';
+type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'CREATE_IN_PROGRESS' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR';
/**
* Error thrown by Artifacts binding operations.
*
@@ -10867,6 +11315,7 @@ interface Artifacts {
* @param name Repository name.
* @returns Repo handle.
* @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist.
+ * @throws {ArtifactsError} with code `CREATE_IN_PROGRESS` if the repo is still being created.
* @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing.
* @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking.
*/
@@ -11153,20 +11602,16 @@ interface BrowserRunBaseOptions {
*/
cacheTTL?: number;
}
-/**
- * Backend selection, mixed into the options of the quick actions that support it.
- * Deliberately not part of `BrowserRunBaseOptions`: `scrape`, `links` and `snapshot`
- * reject an alternate backend, so they must not accept the field.
- */
+/** Backend selection for quick actions. */
interface BrowserRunAlternateBackendOptions {
/** Render with an alternate browser backend instead of the default one. */
browser?: 'kitesurf';
}
/** Common options shared by all quick actions. Exactly one of `url` or `html` must be provided.*/
-type BrowserRunCommonOptions = (BrowserRunBaseOptions & {
+type BrowserRunCommonOptions = BrowserRunBaseOptions & BrowserRunAlternateBackendOptions & ({
/** URL to navigate to, e.g. `"https://example.com"`. */
url: string;
-}) | (BrowserRunBaseOptions & {
+} | {
/** Set the HTML content of the page directly. */
html: string;
});
@@ -11196,7 +11641,7 @@ type BrowserRunScreenshotOptions = BrowserRunCommonOptions & {
scrollPage?: boolean;
/** @see https://pptr.dev/api/puppeteer.screenshotoptions */
screenshotOptions?: BrowserRunPuppeteerScreenshotOptions;
-} & BrowserRunAlternateBackendOptions;
+};
type BrowserRunPDFOptions = BrowserRunCommonOptions & {
/** @see https://pptr.dev/api/puppeteer.pdfoptions */
pdfOptions?: {
@@ -11232,7 +11677,7 @@ type BrowserRunPDFOptions = BrowserRunCommonOptions & {
/** @default 30000 */
timeout?: number;
};
-} & BrowserRunAlternateBackendOptions;
+};
type BrowserRunScrapeOptions = BrowserRunCommonOptions & {
/** CSS selectors to scrape. At least one element is required. */
elements: Array<{
@@ -11267,7 +11712,7 @@ type BrowserRunAccessibilityTreeOptions = BrowserRunCommonOptions & {
* HTTP 200; a malformed selector is an error.
*/
root?: string;
-} & BrowserRunAlternateBackendOptions;
+};
interface BrowserRunJsonBaseOptions {
/** Custom AI models to try in order. Max 3. Falls back to next on error. */
custom_ai?: Array<{
@@ -11281,7 +11726,7 @@ interface BrowserRunJsonBaseOptions {
* Options for the `json` quick action.
* At least one of `prompt` or `response_format` must be provided.
*/
-type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions & BrowserRunJsonBaseOptions & ({
+type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunJsonBaseOptions & ({
/** Natural-language prompt describing what data to extract. */
prompt: string;
/** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
@@ -11292,8 +11737,8 @@ type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunAlternateBacken
/** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
response_format: AiTextGenerationResponseFormat;
});
-type BrowserRunContentOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
-type BrowserRunMarkdownOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
+type BrowserRunContentOptions = BrowserRunCommonOptions;
+type BrowserRunMarkdownOptions = BrowserRunCommonOptions;
type BrowserRunRedirectHop = {
/** URL that returned the redirect. */
url: string;
@@ -11468,6 +11913,162 @@ type BrowserRunJsonErrorResponse = BrowserRunErrorResponse & {
/** Raw AI response text for debugging */
rawAiResponse?: string;
};
+/** Session-scoped guardrails applied when acquiring a browser session. */
+type BrowserRunAcquireGuardrails = {
+ /** Domains that the browser may access. An empty list denies all domains. */
+ allowedDomains?: string[];
+ /** Named domain sets that the browser may access. */
+ allowedDomainSets?: string[];
+};
+/** Options for acquiring a new browser session. */
+type BrowserRunAcquireOptions = {
+ /** Idle session lifetime in milliseconds. */
+ keepAlive?: number;
+ /** Record the browser session. */
+ recording?: boolean;
+ /** Geoegress hint as an ISO-3166 alpha-2 country code. */
+ location?: string;
+ /** Map hostnames to caller-provided Workers that handle outbound requests. */
+ outboundByHost?: Record<string, Fetcher>;
+ /** Session-scoped network guardrails. */
+ guardrails?: BrowserRunAcquireGuardrails;
+ /** Include the session's DevTools targets in the result. */
+ targets?: boolean;
+ /** Lifetime of target live-view URLs in milliseconds. */
+ liveViewUrlExpiresInMs?: number;
+};
+/** Metadata returned when a browser session is acquired. */
+type BrowserRunAcquireResult = {
+ sessionId: string;
+ targets?: BrowserRunDevToolsTarget[];
+};
+/** Options for connecting to an already-acquired browser session. */
+type BrowserRunConnectOptions = {
+ /** Connect to a specific page target instead of the browser-level CDP endpoint. */
+ targetId?: string;
+};
+/** Connection capability returned by `connectSession()` and `launch()`. */
+type BrowserRunConnection = {
+ sessionId: string;
+ /** A session-pinned Fetcher. Use its `fetch()` method for a WebSocket upgrade. */
+ webSocket: Fetcher;
+ targets?: BrowserRunDevToolsTarget[];
+};
+/** The UI mode for a live-view link. */
+type BrowserRunLiveViewMode = 'devtools' | 'tab' | 'full';
+/** Connection-scoped guardrails applied to a live-view link. */
+type BrowserRunConnectionGuardrails = {
+ mode: 'readonly';
+};
+/** Options for minting a live-view link. */
+type BrowserRunLiveViewOptions = {
+ mode?: BrowserRunLiveViewMode;
+ targetId?: string;
+ expiresInMs?: number;
+ guardrails?: BrowserRunConnectionGuardrails;
+};
+/** Live-view link metadata. */
+type BrowserRunLiveView = {
+ webSocketDebuggerUrl: string;
+ devtoolsFrontendUrl: string;
+ id: string;
+ options: {
+ mode: BrowserRunLiveViewMode;
+ guardrails?: BrowserRunConnectionGuardrails;
+ };
+};
+/** Options for listing active browser sessions. */
+type BrowserRunListSessionsOptions = {
+ limit?: number;
+ offset?: number;
+};
+/** Options for listing session history. */
+type BrowserRunHistoryOptions = {
+ limit?: number;
+ offset?: number;
+};
+/** A browser session returned by the session-management methods. */
+type BrowserRunSession = {
+ sessionId: string;
+ startTime?: number;
+ endTime?: number;
+ closeReason?: number;
+ closeReasonText?: string;
+ connectionId?: string;
+ connectionStartTime?: number;
+ connectionEndTime?: number;
+ lastUpdated?: number;
+ webSocketDebuggerUrl?: string;
+ devtoolsFrontendUrl?: string;
+};
+/** Account browser-session and browser-time limits. */
+type BrowserRunLimits = {
+ activeSessions: Array<{
+ id: string;
+ }>;
+ maxConcurrentSessions: number;
+ allowedBrowserAcquisitions: number;
+ timeUntilNextAllowedBrowserAcquisition: number;
+ usedBrowserTimeSeconds?: number;
+};
+/** A browser target returned by the DevTools JSON methods. */
+type BrowserRunDevToolsTarget = {
+ id: string;
+ type: string;
+ url: string;
+ title?: string;
+ description?: string;
+ webSocketDebuggerUrl?: string;
+ devtoolsFrontendUrl?: string;
+};
+/** Browser and protocol version metadata. */
+type BrowserRunDevToolsVersion = {
+ Browser: string;
+ 'Protocol-Version': string;
+ 'User-Agent': string;
+ 'V8-Version': string;
+ 'WebKit-Version': string;
+ webSocketDebuggerUrl: string;
+};
+/** A DevTools protocol domain. Protocol definitions may gain additional fields over time. */
+interface BrowserRunDevToolsProtocolDomain extends Record<string, unknown> {
+ domain: string;
+ experimental?: boolean;
+ dependencies?: string[];
+ types?: Array<Record<string, any>>;
+ commands?: Array<Record<string, any>>;
+ events?: Array<Record<string, any>>;
+}
+/** The DevTools protocol definition. Additional protocol fields may be returned by Chrome. */
+interface BrowserRunDevToolsProtocol extends Record<string, any> {
+ domains: BrowserRunDevToolsProtocolDomain[];
+ version?: {
+ major: string;
+ minor: string;
+ };
+}
+/** Options shared by DevTools target-listing and target-creation methods. */
+type BrowserRunTargetOptions = {
+ liveViewUrlExpiresInMs?: number;
+};
+/** Result returned by DevTools target activation and close methods. */
+type BrowserRunTargetActionResult = {
+ message: string;
+};
+/** Methods exposed by the nested `devtools` binding target. */
+type BrowserRunDevtools = {
+ getVersion(sessionId: string): Promise<BrowserRunDevToolsVersion>;
+ getProtocol(sessionId: string): Promise<BrowserRunDevToolsProtocol>;
+ listTargets(sessionId: string, options?: BrowserRunTargetOptions): Promise<BrowserRunDevToolsTarget[]>;
+ getTarget(sessionId: string, targetId: string): Promise<BrowserRunDevToolsTarget>;
+ newTarget(sessionId: string, url?: string, options?: BrowserRunTargetOptions): Promise<BrowserRunDevToolsTarget>;
+ activateTarget(sessionId: string, targetId: string): Promise<BrowserRunTargetActionResult>;
+ closeTarget(sessionId: string, targetId: string): Promise<BrowserRunTargetActionResult>;
+};
+/** Result returned when closing a browser session. */
+type BrowserRunCloseSessionResult = {
+ status: 'closing' | 'closed';
+};
/**
* Browser Run API binding for automating headless browsers.
* @see https://developers.cloudflare.com/browser-run/
@@ -11632,6 +12233,26 @@ declare abstract class BrowserRun {
* - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
*/
quickAction(action: 'accessibilityTree', options: BrowserRunAccessibilityTreeOptions): Promise<Response>;
+ /** Acquire a new browser session and return its metadata. */
+ acquire(options?: BrowserRunAcquireOptions): Promise<BrowserRunAcquireResult>;
+ /** Acquire a browser session and return a session-pinned WebSocket capability. */
+ launch(options?: BrowserRunAcquireOptions): Promise<BrowserRunConnection>;
+ /** Return a session-pinned WebSocket capability for an existing session. */
+ connectSession(sessionId: string, options?: BrowserRunConnectOptions): Promise<BrowserRunConnection>;
+ /** Mint an authenticated live-view link for a browser session. */
+ getLiveView(sessionId: string, options?: BrowserRunLiveViewOptions): Promise<BrowserRunLiveView>;
+ /** List the caller's active browser sessions. */
+ listSessions(options?: BrowserRunListSessionsOptions): Promise<BrowserRunSession[]>;
+ /** List recent active and closed browser sessions. */
+ history(options?: BrowserRunHistoryOptions): Promise<BrowserRunSession[]>;
+ /** Return the caller's browser-session and browser-time limits. */
+ limits(): Promise<BrowserRunLimits>;
+ /** Return details for one browser session, or `null` when it does not exist. */
+ getSession(sessionId: string): Promise<BrowserRunSession | null>;
+ /** Close a browser session. */
+ closeSession(sessionId: string): Promise<BrowserRunCloseSessionResult>;
+ /** DevTools JSON methods exposed through one nested binding target. */
+ get devtools(): BrowserRunDevtools;
}
/**
* In addition to the properties you can set in the RequestInit dict
@@ -12653,6 +13274,33 @@ declare abstract class D1PreparedStatement {
// ignored when `Disposable` is included in the standard lib.
interface Disposable {
}
+declare module 'cloudflare:durable-objects' {
+ /**
+ * Marks Durable Object methods as safe to run more than once. The runtime may then retry calls
+ * to them after a disconnect that might have happened after the method started. It does not
+ * enable retries or change how many are made.
+ *
+ * Mark methods on the class prototype, for example from a static block:
+ *
+ * ```ts
+ * class Counter extends DurableObject {
+ * static {
+ * retryable(this.prototype.reset);
+ * }
+ * async reset() {}
+ * }
+ * ```
+ *
+ * The mark is on the function itself. A subclass inherits it, but an override, a bound copy, or
+ * a wrapper is not marked unless it is also passed to `retryable()`.
+ *
+ * Each attempt creates its own return value, so if the method returns an `RpcTarget`, its
+ * `[Symbol.dispose]()` may run once per attempt.
+ *
+ * @throws TypeError if an argument is not a function.
+ */
+ export function retryable(...methods: ((...args: never[]) => unknown)[]): void;
+}
/**
* The returned data after sending an email
*/
@@ -12793,7 +13441,10 @@ declare module "cloudflare:email" {
* Evaluation context for targeting rules.
* Keys are attribute names (e.g. "userId", "country"), values are the attribute values.
*/
-type FlagshipEvaluationContext = Record<string, string | number | boolean>;
+type FlagshipEvaluationContextValue = string | number | boolean | null | FlagshipEvaluationContextValue[] | {
+ [key: string]: FlagshipEvaluationContextValue;
+};
+type FlagshipEvaluationContext = Record<string, FlagshipEvaluationContextValue>;
interface FlagshipEvaluationDetails<T> {
flagKey: string;
value: T;
@@ -12802,6 +13453,7 @@ interface FlagshipEvaluationDetails<T> {
errorCode?: string | undefined;
errorMessage?: string | undefined;
}
+type FlagshipWidenedValue<T> = T extends boolean ? boolean : T extends string ? string : T extends number ? number : T;
interface FlagshipEvaluationError extends Error {
}
/**
@@ -12829,8 +13481,23 @@ declare abstract class Flagship {
* @param flagKey The key of the flag to evaluate.
* @param defaultValue Optional default value returned when evaluation fails.
* @param context Optional evaluation context for targeting rules.
+ * @deprecated Use getValue() instead.
*/
get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise<unknown>;
+ /**
+ * Get a flag value, inferring its expected type from the default value.
+ * @param flagKey The key of the flag to evaluate.
+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
+ * @param context Optional evaluation context for targeting rules.
+ */
+ getValue<T extends boolean | string | number | Record<string, unknown> | unknown[]>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipWidenedValue<T>>;
+ /**
+ * Get a flag value with full evaluation details, inferring its expected type from the default value.
+ * @param flagKey The key of the flag to evaluate.
+ * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
+ * @param context Optional evaluation context for targeting rules.
+ */
+ getDetails<T extends boolean | string | number | Record<string, unknown> | unknown[]>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<FlagshipWidenedValue<T>>>;
/**
* Get a boolean flag value.
* @param flagKey The key of the flag to evaluate.
@@ -13631,7 +14298,7 @@ declare namespace Rpc {
// Structured cloneables
BaseType
// Structured cloneable composites
- | Map<T extends Map<infer U, unknown> ? Serializable<U> : never, T extends Map<unknown, infer U> ? Serializable<U> : never> | Set<T extends Set<infer U> ? Serializable<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never> | {
+ | Map<T extends Map<infer U, unknown> ? Serializable<U> : never, T extends Map<unknown, infer U> ? Serializable<U> : never> | Set<T extends Set<infer U> ? Serializable<U> : never> | ReadonlyMap<T extends ReadonlyMap<infer U, unknown> ? Serializable<U> : never, T extends ReadonlyMap<unknown, infer U> ? Serializable<U> : never> | ReadonlySet<T extends ReadonlySet<infer U> ? Serializable<U> : never> | ReadonlyArray<T extends ReadonlyArray<infer U> ? Serializable<U> : never> | {
[K in keyof T]: K extends number | string ? Serializable<T[K]> : never;
}
// Special types
@@ -13649,7 +14316,7 @@ declare namespace Rpc {
type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;
// Recursively rewrite all `Stubable` types with `Stub`s
// prettier-ignore
- type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T : T extends {
+ type Stubify<T> = T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Stubify<K>, Stubify<V>> : T extends ReadonlySet<infer V> ? ReadonlySet<Stubify<V>> : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T : T extends {
[key: string | number]: any;
} ? {
[K in keyof T]: Stubify<T[K]>;
@@ -13658,7 +14325,7 @@ declare namespace Rpc {
// Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
// `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
// prettier-ignore
- type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {
+ type Unstubify<T> = T extends StubBase<infer V> ? V : T extends Map<infer K, infer V> ? Map<Unstubify<K>, Unstubify<V>> : T extends Set<infer V> ? Set<Unstubify<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Unstubify<K>, Unstubify<V>> : T extends ReadonlySet<infer V> ? ReadonlySet<Unstubify<V>> : T extends Array<infer V> ? Array<Unstubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Unstubify<V>> : T extends BaseType ? T : T extends {
[key: string | number]: unknown;
} ? {
[K in keyof T]: Unstubify<T[K]>;
@@ -13758,7 +14425,7 @@ declare namespace CloudflareWorkersModule {
queue?(batch: MessageBatch): void | Promise<void>;
scheduled?(controller: ScheduledController): void | Promise<void>;
tail?(events: TraceItem[]): void | Promise<void>;
- tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | Promise<TailStream.TailEventHandlerType>;
+ tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | undefined | Promise<TailStream.TailEventHandlerType | undefined>;
test?(controller: TestController): void | Promise<void>;
trace?(traces: TraceItem[]): void | Promise<void>;
}
@@ -14808,6 +15475,12 @@ declare namespace TailStream {
readonly cpuTime: number;
readonly wallTime: number;
}
+ type SpanStatusCode = "unset" | "ok" | "error";
+ interface SpanStatus {
+ readonly code: SpanStatusCode;
+ /** A developer-facing error message, present only when code is "error". */
+ readonly message?: string;
+ }
interface SpanOpen {
readonly type: "spanOpen";
readonly name: string;
@@ -14819,6 +15492,17 @@ declare namespace TailStream {
readonly type: "spanClose";
readonly outcome: EventOutcome;
}
+ type SpanUpdateInfo = {
+ readonly type: "name";
+ readonly name: string;
+ } | {
+ readonly type: "status";
+ readonly status: SpanStatus;
+ };
+ interface SpanUpdate {
+ readonly type: "spanUpdate";
+ readonly info: SpanUpdateInfo;
+ }
interface DiagnosticChannelEvent {
readonly type: "diagnosticChannel";
readonly channel: string;
@@ -14872,7 +15556,7 @@ declare namespace TailStream {
readonly type: "attributes";
readonly info: Attribute[];
}
- type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes;
+ type EventType = Onset | Outcome | SpanOpen | SpanClose | SpanUpdate | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes;
// Context in which this trace event lives.
interface SpanContext {
// Single id for the entire top-level invocation
@@ -14907,6 +15591,7 @@ declare namespace TailStream {
outcome?: TailEventHandler<Outcome>;
spanOpen?: TailEventHandler<SpanOpen>;
spanClose?: TailEventHandler<SpanClose>;
+ spanUpdate?: TailEventHandler<SpanUpdate>;
diagnosticChannel?: TailEventHandler<DiagnosticChannelEvent>;
exception?: TailEventHandler<Exception>;
log?: TailEventHandler<Log>;
@@ -15318,10 +16003,16 @@ declare abstract class Workflow<PARAMS = unknown> {
*/
public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;
/**
- * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.
+ * Create a batch of instances and return handles for the created instances and any per-instance errors.
* `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.
- * @param batch List of Options when creating an instance including name and params
- * @returns A promise that resolves with a list of handles for the created instances.
+ * @param options Options for creating instances by count or from a list of instance options
+ * @returns A promise that resolves with the created instance handles and any per-instance errors.
+ */
+ public createBatch(options: WorkflowBatchCreateOptions<PARAMS>): Promise<WorkflowBatchCreateResult>;
+ /**
+ * Create a batch of instances and return handles for the ones that were created.
+ * Instances that could not be created, for example because their ID already exists, are omitted from the result without an error.
+ * @deprecated Use the object form of `createBatch` instead of the array form.
*/
public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;
/**
@@ -15333,6 +16024,31 @@ declare abstract class Workflow<PARAMS = unknown> {
*/
public deleteBatch(instanceIds: string[]): Promise<WorkflowBatchDeleteResult>;
}
+type WorkflowBatchCreateOptions<PARAMS = unknown> = {
+ count: number;
+ params?: PARAMS;
+ retention?: {
+ successRetention?: WorkflowRetentionDuration;
+ errorRetention?: WorkflowRetentionDuration;
+ };
+ locationHint?: WorkflowInstanceLocationHint;
+ instances?: never;
+} | {
+ instances: WorkflowInstanceCreateOptions<PARAMS>[];
+ count?: never;
+ params?: never;
+ retention?: never;
+ locationHint?: never;
+};
+type WorkflowBatchCreateResult = {
+ created: WorkflowInstance[];
+ errors: {
+ index: number;
+ id?: string;
+ code: number;
+ message: string;
+ }[];
+};
type WorkflowBatchDeleteResult = {
deleted: {
id: string;
diff --git a/src/web/scripts/dev-zone-processes.mjs b/src/web/scripts/dev-zone-processes.mjs
index b57c87fe6..534dec035 100644
--- a/src/web/scripts/dev-zone-processes.mjs
+++ b/src/web/scripts/dev-zone-processes.mjs
@@ -228,11 +228,27 @@ export function builtPrecacheEntries(source) {
const parent = consumer.parent
if (!(ts.isVariableDeclaration(parent) && parent.initializer === consumer) && !(ts.isExpressionStatement(parent) && parent.expression === consumer)) return fail()
if (!linearScope(statement(consumer)?.parent)) return fail()
+ const unwrap = node => ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node
+ const guards = new Set()
+ const guardBinding = node => {
+ if (!ts.isIfStatement(node) || node.elseStatement) return undefined
+ const condition = unwrap(node.expression)
+ if (!ts.isBinaryExpression(condition) || ![ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken].includes(condition.operatorToken.kind)) return undefined
+ const operands = [unwrap(condition.left), unwrap(condition.right)]
+ const length = operands.find(value => ts.isPropertyAccessExpression(value) && value.name.text === "length" && ts.isIdentifier(value.expression))
+ if (!length || !operands.some(value => ts.isNumericLiteral(value) && value.text === "1")) return undefined
+ const body = ts.isBlock(node.thenStatement) && node.thenStatement.statements.length === 1 ? node.thenStatement.statements[0] : node.thenStatement
+ if (!ts.isThrowStatement(body) || !body.expression) return undefined
+ const error = unwrap(body.expression)
+ if (!ts.isNewExpression(error) || !ts.isIdentifier(error.expression) || error.expression.text !== "Error"
+ || checker.getSymbolAtLocation(error.expression)?.declarations?.length || error.arguments?.length !== 1 || !ts.isStringLiteral(error.arguments[0])) return undefined
+ return length.expression
+ }
const linearBefore = node => {
const current = statement(node), scope = current?.parent
if (!scope || (!ts.isSourceFile(scope) && !ts.isBlock(scope))) return false
const index = scope.statements.indexOf(current)
- return index >= 0 && scope.statements.slice(0, index).every(value => ts.isVariableStatement(value) || ts.isExpressionStatement(value) || ts.isClassDeclaration(value) || ts.isFunctionDeclaration(value) || ts.isEmptyStatement(value))
+ return index >= 0 && scope.statements.slice(0, index).every(value => ts.isVariableStatement(value) || ts.isExpressionStatement(value) || ts.isClassDeclaration(value) || ts.isFunctionDeclaration(value) || ts.isEmptyStatement(value) || (guardBinding(value) && (guards.add(value), true)))
}
if (!linearBefore(consumer)) return fail()
if (nodes.some(node => ts.isWithStatement(node) || (ts.isIdentifier(node) && node.text === "eval"))) return fail()
@@ -273,12 +289,43 @@ export function builtPrecacheEntries(source) {
if (!calls.length || !calls.every(node => ts.isCallExpression(node.parent) && node.parent.expression === node && !node.parent.arguments.length)) return false
return calls.some(node => node.pos > initialized.end && node.pos < use.pos && directAssignment(node.parent) && statement(node)?.parent === scope && linearBefore(node))
}
+ const catalogueSymbols = new Set()
+ const pureUrlMap = call => {
+ if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression) || call.expression.name.text !== "map" || call.arguments.length !== 1) return false
+ const callback = unwrap(call.arguments[0])
+ if (!ts.isArrowFunction(callback) || callback.modifiers?.length || callback.parameters.length !== 1) return false
+ const parameter = callback.parameters[0]
+ if (!ts.isIdentifier(parameter.name) || parameter.initializer || parameter.dotDotDotToken || ts.isBlock(callback.body)) return false
+ const symbol = symbolFor(parameter.name)
+ const isParameter = node => ts.isIdentifier(unwrap(node)) && symbolFor(unwrap(node)) === symbol
+ const isUrl = node => ts.isPropertyAccessExpression(unwrap(node)) && unwrap(node).name.text === "url" && isParameter(unwrap(node).expression)
+ const body = unwrap(callback.body)
+ if (isUrl(body)) return true
+ if (!ts.isConditionalExpression(body)) return false
+ const condition = unwrap(body.condition)
+ if (!ts.isBinaryExpression(condition)) return false
+ const equals = [ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken].includes(condition.operatorToken.kind)
+ const differs = [ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken].includes(condition.operatorToken.kind)
+ if (!equals && !differs) return false
+ const values = [unwrap(condition.left), unwrap(condition.right)]
+ if (!values.some(node => ts.isTypeOfExpression(node) && isParameter(node.expression)) || !values.some(node => ts.isStringLiteral(node) && node.text === "string")) return false
+ return equals ? isParameter(body.whenTrue) && isUrl(body.whenFalse) : isUrl(body.whenTrue) && isParameter(body.whenFalse)
+ }
+ const mapRead = node => ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node && pureUrlMap(node.parent.parent)
+ const readOnly = node => {
+ const parent = node.parent
+ return !(ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment)
+ && !ts.isPrefixUnaryExpression(parent) && !ts.isPostfixUnaryExpression(parent) && !ts.isDeleteExpression(parent)
+ }
const arrayFor = (input, seen = new Set()) => {
if (ts.isParenthesizedExpression(input)) return arrayFor(input.expression, seen)
if (ts.isArrayLiteralExpression(input)) return input
+ if (ts.isBinaryExpression(input) && input.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
+ && ts.isArrayLiteralExpression(unwrap(input.right)) && !unwrap(input.right).elements.length) return arrayFor(input.left, seen)
if (!ts.isIdentifier(input)) return fail()
const symbol = symbolFor(input)
if (!symbol || seen.has(symbol) || symbol.declarations?.length !== 1) return fail()
+ catalogueSymbols.add(symbol)
const declaration = symbol.declarations[0]
if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name)) return fail()
const scope = statement(declaration)?.parent
@@ -289,12 +336,30 @@ export function builtPrecacheEntries(source) {
const parent = node.parent
if (ts.isBinaryExpression(parent) && parent.left === node && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && directAssignment(parent)
&& (statement(parent)?.parent === scope || emittedInitialization(parent, scope, input))) writes.push({ value: parent.right, position: parent.pos })
- else return fail()
+ else if (!mapRead(node)) return fail()
}
if (writes.length !== 1 || writes[0].position >= input.pos) return fail()
return arrayFor(writes[0].value, new Set([...seen, symbol]))
}
const array = arrayFor(candidate.initializer)
+ for (const guard of guards) {
+ const symbol = symbolFor(guardBinding(guard))
+ const declaration = symbol?.declarations?.length === 1 ? symbol.declarations[0] : undefined
+ if (!declaration || !ts.isVariableDeclaration(declaration) || statement(declaration)?.parent !== statement(guard)?.parent || declaration.end >= guard.pos || !declaration.initializer) return fail()
+ const filter = unwrap(declaration.initializer)
+ if (!ts.isCallExpression(filter) || !ts.isPropertyAccessExpression(filter.expression) || filter.expression.name.text !== "filter" || filter.arguments.length !== 1) return fail()
+ const map = unwrap(filter.expression.expression)
+ if (!pureUrlMap(map)) return fail()
+ const receiver = unwrap(map.expression.expression)
+ if (!ts.isIdentifier(receiver) || !catalogueSymbols.has(symbolFor(receiver))) return fail()
+ for (const reference of references(symbol)) {
+ if (reference === declaration.name) continue
+ const access = reference.parent
+ if (!(ts.isPropertyAccessExpression(access) && access.expression === reference && access.name.text === "length" && readOnly(access))
+ && !(ts.isElementAccessExpression(access) && access.expression === reference && ts.isNumericLiteral(access.argumentExpression) && access.argumentExpression.text === "0" && readOnly(access))) return fail()
+ }
+ }
+ if (nodes.some(node => ts.isPropertyAccessExpression(node) && node.name.text === "prototype" && ts.isIdentifier(node.expression) && node.expression.text === "Array")) return fail()
const entries = array.elements.map(element => {
if (!ts.isObjectLiteralExpression(element)) return fail()
const fields = new Map()
diff --git a/src/web/scripts/service-worker-entry.bundle.test.ts b/src/web/scripts/service-worker-entry.bundle.test.ts
new file mode 100644
index 000000000..6394018d5
--- /dev/null
+++ b/src/web/scripts/service-worker-entry.bundle.test.ts
@@ -0,0 +1,50 @@
+import { createRequire } from "node:module"
+import { runInNewContext } from "node:vm"
+import { webcrypto } from "node:crypto"
+import { resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+import { builtPrecacheEntries } from "./dev-zone-processes.mjs"
+import { describe, expect, it } from "vitest"
+
+const webRoot = fileURLToPath(new URL("../", import.meta.url))
+const { build } = createRequire(import.meta.resolve("@serwist/turbopack"))("esbuild") as {
+ build: (options: Record<string, unknown>) => Promise<{ outputFiles: Array<{ text: string }>; metafile: { inputs: Record<string, unknown> } }>
+}
+const shell = `/community-shell/${"a".repeat(64)}`
+const options = {
+ absWorkingDir: webRoot, bundle: true, write: false, metafile: true, platform: "browser", format: "iife", minify: true, sourcemap: false, logLevel: "silent",
+ define: { "process.env.NODE_ENV": JSON.stringify("production"), "self.__SW_MANIFEST": JSON.stringify([{ url: shell, revision: "unit-shell" }]) },
+}
+function workerGlobal() {
+ const listeners: string[] = []
+ const addEventListener = (type: string) => { listeners.push(type) }
+ const location = new URL("https://worker.example.test/sw.js")
+ const worker = { location, addEventListener, removeEventListener: () => {}, skipWaiting: async () => {},
+ registration: { scope: "https://worker.example.test/", navigationPreload: { enable: async () => {} } },
+ clients: { claim: async () => {}, matchAll: async () => [] },
+ }
+ return { listeners, context: { self: worker, location, addEventListener, URL, Request, Response, Headers, console, crypto: webcrypto, setTimeout, clearTimeout, caches: {} } }
+}
+
+describe("actual SW entry isolated browser dependency bundle", () => {
+ it("loads the unique version leaf and registers worker listeners without Node globals", async () => {
+ const output = await build({ ...options, entryPoints: [resolve(webRoot, "src/app/sw.ts")] })
+ const inputs = Object.keys(output.metafile.inputs).map(path => path.replaceAll("\\", "/"))
+ expect(inputs.some(path => path.endsWith("shared/src/business-schema-version.ts"))).toBe(true)
+ expect(inputs.some(path => /shared\/src\/(index\.ts|constants\.ts|db\/)/.test(path))).toBe(false)
+ expect(builtPrecacheEntries(output.outputFiles[0]!.text)).toEqual([{ url: shell, revision: "unit-shell" }])
+ const fixture = workerGlobal()
+ expect(fixture.context).not.toHaveProperty("process")
+ expect(fixture.context).not.toHaveProperty("Buffer")
+ expect(() => runInNewContext(output.outputFiles[0]!.text, fixture.context, { timeout: 1000 })).not.toThrow()
+ for (const name of ["install", "activate", "fetch", "message"]) expect(fixture.listeners).toContain(name)
+ console.info(JSON.stringify({ case: "isolated-actual-sw-entry-browser-global", bytes: output.outputFiles[0]!.text.length, listeners: fixture.listeners, sharedInputs: inputs.filter(path => path.includes("shared/src/")) }))
+ })
+ it("detects the old broad version dependency rather than supplying a process shim", async () => {
+ const output = await build({ ...options, stdin: { contents: 'import { BUSINESS_SCHEMA_VERSION } from "@alook/shared";self.addEventListener("message",()=>BUSINESS_SCHEMA_VERSION)', resolveDir: webRoot, sourcefile: "old-root-version-dependency.ts" } })
+ expect(Object.keys(output.metafile.inputs).some(path => path.endsWith("shared/src/constants.ts"))).toBe(true)
+ const fixture = workerGlobal()
+ expect(() => runInNewContext(output.outputFiles[0]!.text, fixture.context, { timeout: 1000 })).toThrow("process is not defined")
+ expect(fixture.listeners).toEqual([])
+ })
+})
diff --git a/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.protocol.dom.test.tsx b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.protocol.dom.test.tsx
new file mode 100644
index 000000000..f571159ba
--- /dev/null
+++ b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.protocol.dom.test.tsx
@@ -0,0 +1,104 @@
+import React from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { act, fireEvent, render, screen, waitFor } from "@/test/react-dom-harness"
+import { ApplicationOwnerProvider, createApplicationOwner, type ApplicationOwner } from "@/lib/application-owner"
+import { InviteAcceptClient } from "./invite-accept-client"
+
+const mocks = vi.hoisted(() => ({ push: vi.fn(), toast: vi.fn(), update: vi.fn(), autojoin: false }))
+let owner: ApplicationOwner
+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.push }), useSearchParams: () => new URLSearchParams(mocks.autojoin ? "autojoin=1" : "") }))
+vi.mock("sonner", () => ({ toast: mocks.toast }))
+vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: vi.fn(async () => undefined) }))
+vi.mock("@/lib/observability/regions", () => ({ useObservedRegion: vi.fn() }))
+vi.mock("@/lib/business-schema-lifecycle", async importOriginal => {
+ const actual = await importOriginal<typeof import("@/lib/business-schema-lifecycle")>()
+ mocks.update.mockImplementation((expected = BUSINESS_SCHEMA_VERSION) => new actual.BusinessSchemaMismatch(expected))
+ return { ...actual, requestBusinessSchemaUpdate: mocks.update }
+})
+vi.mock("@/lib/application-owner", async importOriginal => ({
+ ...await importOriginal<typeof import("@/lib/application-owner")>(),
+ PublicQueryProvider: ({ children }: { children: React.ReactNode }) => <ApplicationOwnerProvider owner={owner}><QueryClientProvider client={owner.queryClient}>{children}</QueryClientProvider></ApplicationOwnerProvider>,
+}))
+
+function current(body: unknown, status = 200) {
+ return Response.json(body, { status, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+}
+function info() {
+ return current({ serverId: "s1", serverName: "Example", serverIcon: null, serverDescription: "", memberCount: 0, memberPreview: [], inviter: null })
+}
+function error(message: string, status: number) {
+ return current({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: status === 401 ? "unauthenticated" : "invalid_input", message, retryable: false } }, status)
+}
+async function join() {
+ fireEvent.click(await screen.findByRole("button", { name: "Join server" }))
+}
+beforeEach(() => {
+ vi.clearAllMocks(); mocks.autojoin = false
+ owner = createApplicationOwner("visitor", new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }))
+})
+afterEach(() => { owner.queryClient.clear(); vi.unstubAllGlobals() })
+
+describe("actual public invite join caller", () => {
+ it("sends the current contract, consumes the current navigation target and joins once", async () => {
+ const fetchMock = vi.fn().mockResolvedValueOnce(info()).mockResolvedValueOnce(current({ serverId: "s1", member: { id: "current-operation-row" } }))
+ vi.stubGlobal("fetch", fetchMock)
+ render(<InviteAcceptClient token="invite" />)
+ await join()
+ await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/c/channels/s1"))
+ expect(mocks.toast).toHaveBeenCalledWith("Joined server")
+ const [path, options] = fetchMock.mock.calls[1]
+ expect(path).toBe("/api/community/invites/invite/join")
+ expect(options.method).toBe("POST")
+ expect(new Headers(options.headers).get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+ it("keeps anonymous401 on the invite sign-in return path", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(info()).mockResolvedValueOnce(error("unauthorized", 401)))
+ render(<InviteAcceptClient token="invite" />)
+ await join()
+ await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/sign-in?redirect=%2Fc%2Finvite%2Finvite%3Fautojoin%3D1"))
+ expect(mocks.update).not.toHaveBeenCalled(); expect(mocks.toast).not.toHaveBeenCalled()
+ })
+ it("reads the current error message rather than an error object", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(info()).mockResolvedValueOnce(error("Already a member", 400)))
+ render(<InviteAcceptClient token="invite" />)
+ await join()
+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("Already a member"))
+ expect(mocks.push).not.toHaveBeenCalled(); expect(mocks.update).not.toHaveBeenCalled()
+ })
+ it("autojoin performs only one current operation", async () => {
+ mocks.autojoin = true
+ const fetchMock = vi.fn().mockResolvedValueOnce(info()).mockResolvedValueOnce(current({ serverId: "s1" }))
+ vi.stubGlobal("fetch", fetchMock)
+ const mounted = render(<InviteAcceptClient token="invite" />)
+ await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/c/channels/s1"))
+ mounted.rerender(<InviteAcceptClient token="invite" />)
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 5)) })
+ expect(fetchMock.mock.calls.filter(([path]) => path.endsWith("/join"))).toHaveLength(1)
+ })
+ it.each(["bad-json", "bad-target"])("only an active %s body may request an update", async kind => {
+ const bad = () => kind === "bad-json" ? new Response("{", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }) : current({ serverId: null })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(info()).mockResolvedValueOnce(bad()))
+ const mounted = render(<InviteAcceptClient token="invite" />)
+ await join()
+ await waitFor(() => expect(mocks.update).toHaveBeenCalledOnce())
+ mounted.unmount(); mocks.update.mockClear(); mocks.toast.mockClear()
+ let release!: (value: Response) => void
+ const pending = new Promise<Response>(resolve => { release = resolve })
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(info()).mockReturnValueOnce(pending))
+ const next = render(<InviteAcceptClient token="invite" />)
+ await join()
+ next.rerender(<output>New screen</output>)
+ await act(async () => { release(bad()); await pending })
+ expect(mocks.update).not.toHaveBeenCalled(); expect(mocks.toast).not.toHaveBeenCalled(); expect(mocks.push).not.toHaveBeenCalled()
+ })
+ it("rejects a lower confirmation without consuming its target", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(info()).mockResolvedValueOnce(Response.json({ serverId: "old" }, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION - 1) } })))
+ render(<InviteAcceptClient token="invite" />)
+ await join()
+ await waitFor(() => expect(mocks.update).toHaveBeenCalledWith(BUSINESS_SCHEMA_VERSION - 1))
+ expect(mocks.push).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx
index 5b5aacc0a..3db8ab5ad 100644
--- a/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx
+++ b/src/web/src/app/(public-community)/c/invite/[token]/invite-accept-client.tsx
@@ -13,6 +13,9 @@ import { Button } from "@/components/ui/button"
import { avatarInitial } from "@/lib/community/avatar"
import { Skeleton } from "@/components/ui/skeleton"
import { apiFetch } from "@/lib/api/client"
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION, CommunityReadErrorSchema, CommunityInviteJoinTargetSchema } from "@alook/shared"
+import { requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
+import { isAbortError } from "@/lib/errors"
import { ApiError } from "@/lib/errors"
import { ServerIcon } from "@/components/community/server-icon"
import { Avatar } from "@/components/community/avatar"
@@ -67,18 +70,28 @@ function InviteAcceptInner({ token }: { token: string }) {
try {
const res = await fetch(`/api/community/invites/${token}/join`, {
signal: original.signal,
- method: "POST", credentials: "include", headers: { "Content-Type": "application/json" },
+ method: "POST", credentials: "include", headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
})
original.assert()
if (res.status === 401) return { kind: "sign-in" as const }
- if (!res.ok) {
- const body = (await res.json().catch(() => null)) as { error?: string } | null
+ if (res.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) {
+ throw requestBusinessSchemaUpdate(Number(res.headers.get(COMMUNITY_CONTRACT_HEADER)))
+ }
+ let body: unknown
+ try {
+ body = await res.json()
+ original.assert()
+ if (res.ok) {
+ const result = CommunityInviteJoinTargetSchema.parse(body)
+ return { kind: "joined" as const, serverId: result.serverId }
+ }
+ const error = CommunityReadErrorSchema.parse(body)
+ throw new ApiError(error.error.message, res.status, error.error.details)
+ } catch (error) {
original.assert()
- throw new Error(body?.error || "Couldn't join the server — try the invite again")
+ if (isAbortError(error) || error instanceof ApiError) throw error
+ throw requestBusinessSchemaUpdate()
}
- const result = await res.json() as { serverId: string }
- original.assert()
- return { kind: "joined" as const, serverId: result.serverId }
} catch (error) { original.assert(); throw error }
},
})
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 1201e1c9f..d55f0b8b6 100644
--- a/src/web/src/app/api/community/billing/routes.test.ts
+++ b/src/web/src/app/api/community/billing/routes.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
import { createAnalyticsConsentProof } from "@/lib/analytics-consent-server"
@@ -39,7 +40,7 @@ const owner = { id: "owner", email: "[email protected]", isBot: false, delete
const request = (body?: string, headers: Record<string, string> = {}) => new NextRequest("https://alook.ai/api/billing", {
method: "POST", body, headers: { origin: "https://alook.ai", ...headers },
})
-const getRequest = (headers: Record<string, string> = {}) => new NextRequest("https://alook.ai/api/community/billing", { headers })
+const getRequest = (headers: Record<string, string> = {}) => new NextRequest("https://alook.ai/api/community/billing", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), ...headers } })
beforeEach(() => {
vi.resetAllMocks()
@@ -62,7 +63,7 @@ describe("billing HTTP route boundaries", () => {
})
const response = await GET(getRequest())
expect(response.status).toBe(200)
- expect(response.headers.get("cache-control")).toBe("no-store")
+ expect(response.headers.get("cache-control")).toBe("private, no-store, max-age=0")
expect(await response.json()).toEqual(summary)
expect(mocks.summary).toHaveBeenCalledWith(mocks.db, expect.any(Function), mocks.env, owner.id)
})
@@ -206,7 +207,7 @@ describe("billing HTTP route boundaries", () => {
mocks.owner.mockRejectedValue(new Error("private database detail"))
const response = await GET(getRequest())
expect(response.status).toBe(503)
- expect(await response.json()).toEqual({ error: "BILLING_UNAVAILABLE" })
+ expect(await response.json()).toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: "temporarily_unavailable", message: "BILLING_UNAVAILABLE", retryable: true } })
})
})
diff --git a/src/web/src/app/api/community/bots/[id]/pii/route.test.ts b/src/web/src/app/api/community/bots/[id]/pii/route.test.ts
index 8db1c9c65..cba2af260 100644
--- a/src/web/src/app/api/community/bots/[id]/pii/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/pii/route.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, CommunityReadErrorSchema } from "@alook/shared"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
const mocks = vi.hoisted(() => ({ session: vi.fn(), liveUser: vi.fn(), bot: vi.fn(), machine: vi.fn(), dispatch: vi.fn() }))
@@ -16,7 +17,7 @@ vi.mock("@alook/shared", async (original) => ({
import { POST } from "./route"
const body = { requestId: "request", operation: { action: "list" } }
const request = (value: unknown = body, headers: Record<string, string> = {}) => new NextRequest("https://alook.ai/api/community/bots/bot/pii", {
- method: "POST", headers: { Origin: "https://alook.ai", "content-type": "application/json", ...headers }, body: JSON.stringify(value),
+ method: "POST", headers: { Origin: "https://alook.ai", "content-type": "application/json", "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION), ...headers }, body: JSON.stringify(value),
})
const context = { params: Promise.resolve({ id: "bot" }) }
describe("human-only PII management", () => {
@@ -60,7 +61,7 @@ describe("human-only PII management", () => {
const value = { requestId: "r", operation: { action: "setEnabled", pluginId: "p", enabled: false, expectedRevision: 2 } }
const response = await POST(request(value), context)
expect(response.status).toBe(202)
- expect(response.headers.get("Cache-Control")).toBe("no-store")
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")
expect(await response.json()).toEqual({ dispatched: true, requestId: "r" })
expect(mocks.dispatch.mock.calls[0][1]).toBe("/community-machine/by-id/machine/pii")
expect(JSON.parse(mocks.dispatch.mock.calls[0][2].body)).toEqual({ type: "pii:manage", botId: "bot", ...value })
@@ -69,7 +70,7 @@ describe("human-only PII management", () => {
const preview = { requestId: "preview", operation: { action: "preview", text: "private-test-input", expectedRevision: 0 } }
const response = await POST(request(preview), context)
expect(response.status).toBe(202)
- expect(response.headers.get("Cache-Control")).toBe("no-store")
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")
expect(await response.json()).toEqual({ dispatched: true, requestId: "preview" })
expect(JSON.parse(mocks.dispatch.mock.calls[0][2].body)).toEqual({ type: "pii:manage", botId: "bot", ...preview })
for (const operation of [{ ...preview.operation, text: "中".repeat(400) }, { ...preview.operation, text: " " }, { action: "preview", text: "text" }]) {
@@ -84,17 +85,17 @@ describe("human-only PII management", () => {
mocks.dispatch.mockResolvedValueOnce(response)
const result = await POST(request(), context)
expect(result.status).toBe(503)
- expect(await result.json()).toEqual({ error: "PII_UNAVAILABLE" })
+ expect(CommunityReadErrorSchema.parse(await result.json())).toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: "temporarily_unavailable", message: "PII_UNAVAILABLE", retryable: true } })
}
mocks.dispatch.mockRejectedValueOnce(new Error("PRIVATE_EXCEPTION"))
const result = await POST(request(), context)
expect(result.status).toBe(503)
- expect(await result.json()).toEqual({ error: "PII_UNAVAILABLE" })
+ expect(CommunityReadErrorSchema.parse(await result.json())).toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: "temporarily_unavailable", message: "PII_UNAVAILABLE", retryable: true } })
})
it.each([[{ sent: 0, unsupported: 1 }, 409, "UPGRADE_REQUIRED"], [{ sent: 0, unsupported: 0 }, 409, "MACHINE_OFFLINE"], [{ sent: "1" }, 503, "PII_UNAVAILABLE"]])("reports %j without claiming application", async (receipt, status, error) => {
mocks.dispatch.mockResolvedValue(Response.json(receipt))
const response = await POST(request(), context)
expect(response.status).toBe(status)
- expect(await response.json()).toEqual({ error })
+ expect(CommunityReadErrorSchema.parse(await response.json())).toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: status === 409 ? "idempotency_conflict" : "temporarily_unavailable", message: error, retryable: status >= 500 } })
})
})
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index c143e2338..f3dacfa6a 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -76,6 +76,10 @@ function getReq() {
return new NextRequest("http://localhost/api/community/bots", { method: "GET" })
}
+function catalogBot(id: string, runtime = "claude") {
+ return { id, name: id, discriminator: "0042", ownerUserId: "u1", image: null, avatarVersion: 0, description: "", presence: "offline", machineId: "m1", runtime, modelName: null }
+}
+
function postReq(body: unknown) {
return new NextRequest("http://localhost/api/community/bots", {
method: "POST",
@@ -351,8 +355,8 @@ describe("GET /api/community/bots — heatmap activity", () => {
})
it("attaches each bot's 30-day dailyActivity from the batched owner read", async () => {
mockListBotsForOwner.mockResolvedValue([
- { id: "bot_1", name: "A", machineId: "m1", runtime: "claude", modelName: null },
- { id: "bot_2", name: "B", machineId: "m1", runtime: "claude", modelName: null },
+ { ...catalogBot("bot_1"), name: "A" },
+ { ...catalogBot("bot_2"), name: "B" },
])
const byBot = new Map<string, unknown[]>([
["bot_1", [{ day: "2026-07-31", handledCount: 3, sentCount: 1 }]],
@@ -393,15 +397,15 @@ describe("GET /api/community/bots — heatmap activity", () => {
it("returns 30 oldest-to-newest usage days with nullable metrics and capability", async () => {
const today = new Date().toISOString().slice(0, 10)
mockListBotsForOwner.mockResolvedValue([
- { id: "bot_claude", runtime: "claude" },
- { id: "bot_codex", runtime: "codex" },
- { id: "bot_cursor", runtime: "cursor" },
- { id: "bot_antigravity", runtime: "antigravity" },
- { id: "bot_agy", runtime: "agy" },
- { id: "bot_grok", runtime: "grok" },
- { id: "bot_opencode", runtime: "opencode" },
- { id: "bot_pi", runtime: "pi" },
- { id: "bot_unknown", runtime: "custom" },
+ catalogBot("bot_claude", "claude"),
+ catalogBot("bot_codex", "codex"),
+ catalogBot("bot_cursor", "cursor"),
+ catalogBot("bot_antigravity", "antigravity"),
+ catalogBot("bot_agy", "agy"),
+ catalogBot("bot_grok", "grok"),
+ catalogBot("bot_opencode", "opencode"),
+ catalogBot("bot_pi", "pi"),
+ catalogBot("bot_unknown", "custom"),
])
mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())
mockGetBotDailyTokenUsageForOwner.mockResolvedValue(new Map([
@@ -469,8 +473,7 @@ describe("GET /api/community/bots — heatmap activity", () => {
vi.setSystemTime(new Date("2026-08-29T16:00:01Z"))
try {
mockListBotsForOwner.mockResolvedValue([{
- id: "bot_1",
- runtime: "codex",
+ ...catalogBot("bot_1", "codex"),
tokenUsageTimeZone: "Asia/Shanghai",
}])
mockGetBotDailyActivityForOwner.mockResolvedValue(new Map())
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 2d5a882c0..6e3e21a0d 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -93,7 +94,7 @@ function botReq(target: string | null, headers: Record<string, string> = {}): Ne
const q = target !== null ? `?target=${encodeURIComponent(target)}` : ""
return new NextRequest(`http://localhost/api/community/channels/resolve/attachments${q}`, {
method: "POST",
- headers,
+ headers: { ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
const botCtx = { params: { id: "resolve" } } as any
@@ -304,7 +305,7 @@ describe("POST /api/community/channels/[id]/attachments — human arm (re-homes
},
})
- const req = new NextRequest("http://localhost/api/community/channels/c1/attachments", { method: "POST" })
+ const req = new NextRequest("http://localhost/api/community/channels/c1/attachments", { method: "POST", headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
const res = await POST(req, { params: { id: "c1" } } as any)
expect(res).toBe(helperResponse)
expect(mockRunAttachmentUpload).toHaveBeenCalledOnce()
diff --git a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
index fe062db28..b9a0909e7 100644
--- a/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/[userId]/route.ts
@@ -16,8 +16,6 @@ const REF_PLACEHOLDER_ID = "resolve"
* else is the creator's call; admins have no content privilege here).
* - A creator may self-leave after deterministic creator handoff. Removing
* another current creator remains out of scope.
- * The removed user gets a CHANNEL_MEMBER_REMOVE so their sidebar drops the
- * channel + evicts its caches.
*/
export const DELETE = withCommunityActor(async (req: NextRequest, ctx) => {
const pathChannelId = ctx.params?.id
diff --git a/src/web/src/app/api/community/channels/[id]/members/route.test.ts b/src/web/src/app/api/community/channels/[id]/members/route.test.ts
index c3fc25a51..627a6ea10 100644
--- a/src/web/src/app/api/community/channels/[id]/members/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/route.test.ts
@@ -1,3 +1,5 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -7,6 +9,8 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockResolveChannelAccessContext = vi.fn()
const mockGetMember = vi.fn()
+const mockGetChannel = vi.fn()
+const mockGetChannelForMember = vi.fn()
const mockCreateChannelMember = vi.fn()
const mockListChannelMembers = vi.fn()
const mockGetPrivateChannelAudienceUserIds = vi.fn()
@@ -45,6 +49,8 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: {
communityChannel: {
+ getChannel: (...a: unknown[]) => mockGetChannel(...a),
+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),
createChannelMember: (...a: unknown[]) => mockCreateChannelMember(...a),
listChannelMembers: (...a: unknown[]) => mockListChannelMembers(...a),
@@ -101,6 +107,9 @@ vi.mock("@/lib/middleware/helpers", () => {
import { GET, POST } from "./route"
const ctx = { params: { id: "c1" } } as any
+function getReq(channelId = "c1", relation = "access") {
+ return new NextRequest(`http://localhost/api/community/channels/${channelId}/members?relation=${relation}`, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+}
function postReq(body: unknown) {
return new NextRequest("http://localhost/api/community/channels/c1/members", {
method: "POST",
@@ -124,6 +133,10 @@ describe("GET /channels/[id]/members", () => {
beforeEach(() => {
vi.clearAllMocks()
mockResolveChannelAccessContext.mockResolvedValue(managerCtx())
+ const channel = channelResourceFixture({ id: "c1", serverId: "s1", creatorId: "u1" })
+ mockGetChannel.mockResolvedValue(channel)
+ mockGetChannelForMember.mockResolvedValue(channel)
+ mockGetUsersByIds.mockResolvedValue(["Ann", "Bob", "Cy"].map((name, i) => ({ id: `u${i + 1}`, name, discriminator: `000${i + 1}`, image: null, avatarVersion: 0 })))
// Full resolved audience: creator (u1), an added member (u2), an admin (u3).
mockResolveScopeMembers.mockResolvedValue([
{ userId: "u1", role: "member", source: "explicit" },
@@ -138,7 +151,7 @@ describe("GET /channels/[id]/members", () => {
})
it("lists the full audience with role + source + isCreator", async () => {
- const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)
+ const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.members).toHaveLength(3)
@@ -153,30 +166,30 @@ describe("GET /channels/[id]/members", () => {
expect(admin.role).toBe("admin")
})
- it("retries a BUSY scope resolution and preserves the resolved member result", async () => {
+ it("retries a BUSY scoped channel access and preserves the resolved member result", async () => {
vi.spyOn(Math, "random").mockReturnValue(0)
- mockResolveScopeMembers
- .mockRejectedValueOnce(new Error("D1_ERROR: database is locked"))
- .mockResolvedValueOnce([{ userId: "u1", role: "member", source: "explicit" }])
- const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)
+ mockGetChannelForMember.mockRejectedValueOnce(new Error("D1_ERROR: database is locked"))
+ mockResolveScopeMembers.mockResolvedValueOnce([{ userId: "u1", role: "member", source: "explicit" }])
+ const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
expect((await res.json()).members.map((member: { userId: string }) => member.userId)).toEqual(["u1"])
- expect(mockResolveScopeMembers).toHaveBeenCalledTimes(2)
- expect(mockResolveChannelAccessContext).toHaveBeenCalledTimes(1)
+ expect(mockResolveScopeMembers).toHaveBeenCalledTimes(1)
+ expect(mockGetChannelForMember).toHaveBeenCalledTimes(3)
})
it("rethrows a non-BUSY scope-resolution failure without retrying", async () => {
const error = new Error("programmer bug")
mockResolveScopeMembers.mockRejectedValueOnce(error)
- await expect(GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)).rejects.toBe(error)
+ await expect(GET(getReq(), ctx)).rejects.toBe(error)
expect(mockResolveScopeMembers).toHaveBeenCalledTimes(1)
})
- it("drops audience members with no hydrated (non-deleted) server row", async () => {
+ it("drops audience members without a non-deleted full user profile", async () => {
+ mockGetUsersByIds.mockResolvedValue([{ id: "u1", name: "Ann", discriminator: "0001", image: null, avatarVersion: 0 }])
mockGetMembersByUserIds.mockResolvedValue([
{ id: "m1", serverId: "s1", userId: "u1", role: "member", nickname: null, userName: "Ann", userImage: null, discriminator: "0001", statusEmoji: null, statusText: null, userIsBot: false, userOwnerUserId: null },
])
- const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)
+ const res = await GET(getReq(), ctx)
const body = await res.json()
expect(body.members).toHaveLength(1)
expect(body.members[0].userId).toBe("u1")
@@ -188,10 +201,11 @@ describe("GET /channels/[id]/members", () => {
anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
role: "admin", isPrivate: true, isChannelMember: true, isCreator: true,
})
+ mockGetChannelForMember.mockResolvedValue(channelResourceFixture({ id: "t1", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", creatorId: "u1" }))
mockListThreadParticipants.mockResolvedValue([
{ userId: "u1", source: "spoke", userName: "Ann", userImage: null, discriminator: "0001", addedAt: "" },
])
- const res = await GET(new NextRequest("http://localhost/api/community/channels/t1/members"), { params: { id: "t1" } } as any)
+ const res = await GET(getReq("t1", "notify"), { params: { id: "t1" } } as any)
expect(res.status).toBe(200)
// A thread reads participants, NOT the access audience.
expect(mockListThreadParticipants).toHaveBeenCalledWith(expect.anything(), "t1")
@@ -207,11 +221,12 @@ describe("GET /channels/[id]/members", () => {
anchor: { id: "f1", serverId: "s1", parentChannelId: null, creatorId: "u1" },
role: "member", isPrivate: false, isChannelMember: false, isCreator: false,
})
+ mockGetChannelForMember.mockResolvedValue(channelResourceFixture({ id: "p1", serverId: "s1", type: "thread", parentChannelId: "f1", parentMessageId: "m1", creatorId: "u2" }))
mockListThreadParticipants.mockResolvedValue([
{ userId: "u2", source: "spoke", userName: "Bob", userImage: null, discriminator: "0002", addedAt: "" },
{ userId: "u1", source: "added", userName: "Ann", userImage: null, discriminator: "0001", addedAt: "" },
])
- const res = await GET(new NextRequest("http://localhost/api/community/channels/p1/members"), { params: { id: "p1" } } as any)
+ const res = await GET(getReq("p1", "notify"), { params: { id: "p1" } } as any)
const body = await res.json()
expect(mockListThreadParticipants).toHaveBeenCalledWith(expect.anything(), "p1")
expect(mockResolveScopeMembers).not.toHaveBeenCalled()
@@ -221,8 +236,8 @@ describe("GET /channels/[id]/members", () => {
})
it("403 for a caller without access", async () => {
- mockResolveChannelAccessContext.mockResolvedValue(null)
- const res = await GET(new NextRequest("http://localhost/api/community/channels/c1/members"), ctx)
+ mockGetChannelForMember.mockResolvedValue(null)
+ const res = await GET(getReq(), ctx)
expect(res.status).toBe(403)
})
})
diff --git a/src/web/src/app/api/community/channels/[id]/members/route.ts b/src/web/src/app/api/community/channels/[id]/members/route.ts
index 370929c9d..4a9b78ebe 100644
--- a/src/web/src/app/api/community/channels/[id]/members/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/members/route.ts
@@ -2,30 +2,20 @@ import { NextRequest } from "next/server"
import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import {
- queries,
- WS_EVENTS,
- isForum,
- isThread,
- DM_SERVER,
- formatHandle,
- parseRef,
- withD1Retry,
-} from "@alook/shared"
+import { queries, WS_EVENTS, isThread, DM_SERVER, formatHandle, parseRef, withD1Retry } from "@alook/shared"
import type { CommunityCliServerMember as ServerMember } from "@alook/shared"
import { broadcastToUserSafe } from "@/lib/community/fanout"
import { requireChannelAccess } from "@/lib/community/permissions"
import { resolveTargetForMember } from "@/lib/community/resolve-ref"
-import { mapMemberForApi } from "@/lib/community/member-payload"
+
import { fetchOnlineUserIds, toMemberStatus } from "@/lib/community/member-presence"
-import { requestsCommunityContract, requestedCommunityContract } from "@alook/shared"
+import { requestsCommunityContract, COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { readCommunityMembers } from "@/lib/community/member-read"
import { resolveMessageTarget } from "@/lib/community/message-door"
// A bot addresses by ref-in-query (`?ref=`, the folded `channelMember` verb);
// the path `[id]` is then the `resolve` placeholder (a ref carries `/`). A
// human/web caller puts the real channelId in the path.
-const REF_PLACEHOLDER_ID = "resolve"
/**
* GET /api/community/channels/[id]/members — the canonical "who is in this
@@ -44,82 +34,14 @@ const REF_PLACEHOLDER_ID = "resolve"
export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
- if (requestsCommunityContract(req.headers)) {
- const ref = req.nextUrl.searchParams.get("ref")
- const target = ctx.actor.kind === "bot" && ref ? { ref } : { id: ctx.params?.id ?? "" }
- const resolved = await resolveMessageTarget(db, ctx.actor.userId, target, ctx.actor.kind)
- if (!resolved.ok) return writeError(resolved.error, resolved.status)
- return readCommunityMembers(db, resolved.value.target.channelId, ctx.actor.userId, req.nextUrl.searchParams.get("relation"), requestedCommunityContract(req.headers) === 3 ? 3 : 2)
- }
-
- if (ctx.actor.kind === "bot") {
+ if (ctx.actor.kind === "bot" && !requestsCommunityContract(req.headers)) {
return handleBotChannelMember(db, ctx.env, ctx.actor.userId, req)
}
-
- const channelId = ctx.params?.id
- if (!channelId || channelId === REF_PLACEHOLDER_ID) return writeError("missing channel id", 400)
-
- const access = await requireChannelAccess(db, channelId, ctx.actor.userId)
- if (!access.ok) return writeError(access.error, access.status)
- const userId = ctx.actor.userId
-
- const { anchor, channel } = access.value
-
- // Thread: the NOTIFY dimension. The panel == the participant set (not the
- // access audience), so a public thread lists only its participants, never
- // the whole server. The row's `isCreator` locks the UNIT's own author
- // (`channel.creatorId`), NOT the access anchor. NOTE: the live /c UI reads
- // `/participants` for these units; this branch is API/agent parity so a
- // direct GET of a thread's `/members` agrees.
- if (isThread(channel.type)) {
- const participants = await queries.communityThread.listThreadParticipants(db, channelId)
- const userIds = participants.map((p) => p.userId)
- const rows = await queries.communityMember.getMembersByUserIds(db, channel.serverId, userIds)
- const rowByUser = new Map(rows.map((r) => [r.userId, r]))
- const members = participants
- .map((p) => {
- const row = rowByUser.get(p.userId)
- if (!row) return null
- return mapMemberForApi(row, userId, {
- isCreator: p.userId === channel.creatorId,
- source: p.source,
- })
- })
- .filter((m): m is NonNullable<typeof m> => m !== null)
- return writeJSON({ members })
- }
-
- // Channel / forum: the ACCESS dimension. Resolve the audience (public → all
- // server members; private → own roster ∪ creator). The anchor IS the roster
- // for these top-level units, so the roster creator is `anchor.creatorId`.
- const scopeMembers = await withD1Retry(
- () => queries.communityMembersResolver.resolveScopeMembers(db, {
- scope: isForum(channel.type) ? "forum" : "channel",
- scopeId: channelId,
- }),
- { route: "community/channel-members:resolve-scope" },
- )
- const rows = await queries.communityMember.getMembersByUserIds(
- db,
- anchor.serverId,
- scopeMembers.map((m) => m.userId),
- )
- const rowByUser = new Map(rows.map((r) => [r.userId, r]))
-
- // `resolveScopeMembers` order is the source of truth for membership; hydrate
- // display via the server-member rows (soft-deleted users drop out — expected).
- const members = scopeMembers
- .map((sm) => {
- const row = rowByUser.get(sm.userId)
- if (!row) return null
- return mapMemberForApi(row, userId, {
- isCreator: sm.userId === anchor.creatorId,
- source: sm.source,
- })
- })
- .filter((m): m is NonNullable<typeof m> => m !== null)
-
- return writeJSON({ members })
+ const ref = req.nextUrl.searchParams.get("ref")
+ const target = ctx.actor.kind === "bot" && ref ? { ref } : { id: ctx.params?.id ?? "" }
+ const resolved = await resolveMessageTarget(db, ctx.actor.userId, target, ctx.actor.kind)
+ if (!resolved.ok) return writeError(resolved.error, resolved.status)
+ return readCommunityMembers(db, resolved.value.target.channelId, ctx.actor.userId, req.nextUrl.searchParams.get("relation"), COMMUNITY_RESOURCE_CONTRACT_VERSION)
})
/**
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
index e688dd6d9..03650a339 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.atomic-replay.test.ts
@@ -69,7 +69,15 @@ describe("message HTTP route — concurrent nonce with real SQL writes", () => {
ALTER TABLE user ADD COLUMN name TEXT;
ALTER TABLE user ADD COLUMN email TEXT;
ALTER TABLE user ADD COLUMN image TEXT;
+ ALTER TABLE user ADD COLUMN emailVerified INTEGER;
+ ALTER TABLE user ADD COLUMN createdAt TEXT;
+ ALTER TABLE user ADD COLUMN updatedAt TEXT;
+ ALTER TABLE user ADD COLUMN discriminator TEXT NOT NULL DEFAULT '0000';
+ UPDATE user SET discriminator='0042',email=id || '@example.test',createdAt='2026-10-28T00:00:00Z',updatedAt='2026-10-28T00:00:00Z';
+ CREATE TABLE community_user_profile (user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE,about_me TEXT DEFAULT '',banner_color TEXT,status_emoji TEXT,status_text TEXT DEFAULT '');
ALTER TABLE user ADD COLUMN avatarVersion INTEGER DEFAULT 0;
+ UPDATE user SET name='Author' WHERE id='author';
+ UPDATE user SET name='Peer' WHERE id='peer';
CREATE TABLE community_bot_daily_activity (bot_id TEXT NOT NULL, day TEXT NOT NULL, handled_count INTEGER NOT NULL DEFAULT 0, sent_count INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(bot_id, day));
INSERT INTO community_attachment(id, uploader_id, r2_key, filename, created_at) VALUES ('a', 'author', 'original', 'a.png', 'now');
`)
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 593f0ecae..4551b4c69 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, queries } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -133,7 +134,9 @@ vi.mock("@alook/shared", async () => {
communityReaction: {
listReactionsByMessageIds: (...a: unknown[]) => mockListReactionsByMessageIds(...a),
},
+ communityUserProfile: { getResourceProfiles: vi.fn(async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: id === "peer" ? "Peer" : "Author", discriminator: "0042", avatar: null, avatarVersion: id === "peer" ? 5 : 0 }))), getProfilesByUserIds: vi.fn(async () => []) },
user: {
+ getUsersByIds: vi.fn(async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "Author", discriminator: "0042", image: null, avatarVersion: 0 }))),
getUserPublic: (...a: unknown[]) => mockGetUserPublic(...a),
getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),
@@ -228,7 +231,7 @@ function postReq(body: unknown) {
return new NextRequest("http://localhost/api/community/channels/c1/messages", {
method: "POST",
body: JSON.stringify(body),
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) },
})
}
@@ -241,7 +244,7 @@ function botPostReq(body: unknown) {
}
function getReq() {
- return new NextRequest("http://localhost/api/community/channels/c1/messages", { method: "GET" })
+ return new NextRequest("http://localhost/api/community/channels/c1/messages", { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } })
}
const ctx = { params: { id: "c1" } } as any
@@ -263,6 +266,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
authorId: "u1",
authorName: "Alice",
authorImage: null,
+ authorAvatarVersion: 0,
authorEmail: "[email protected]",
content: "hello",
type: "default",
@@ -302,13 +306,13 @@ describe("POST /api/community/channels/[id]/messages", () => {
mockGetMessage.mockResolvedValue(row)
mockGetMessageByAuthorAndNonce.mockResolvedValue(replay ? row : null)
const request = postReq({ content: "hello", nonce: "v3-nonce" })
- request.headers.set("x-alook-community-contract", "3")
+ request.headers.set("x-alook-community-contract", String(BUSINESS_SCHEMA_VERSION))
request.headers.set("cookie", "_ga=GA1.1.123.456")
const response = await POST(request, ctx)
expect(response.status).toBe(replay ? 200 : 201)
- expect(response.headers.get("x-alook-community-contract")).toBe("3")
+ expect(response.headers.get("x-alook-community-contract")).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(response.cookies.get("alook_ga_session")).toBeUndefined()
- expect(await response.json()).toEqual({ contractVersion: 3, channelId: "c1", deduped: replay, message: {
+ expect(await response.json()).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }], contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", deduped: replay, message: {
id: "m1", channelId: "c1", seq: 12, authorId: "u1", authorName: "Alice", authorAvatar: null, authorAvatarVersion: 0,
content: "hello", type: "chat", mentionType: null, replyToId: null, clientNonce: "v3-nonce", createdAt: "now", attachments: [],
} })
@@ -436,7 +440,7 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(mockDuplicateCheck).not.toHaveBeenCalled()
})
- it.each([1, 3])("accepts a forum opener with contract %s without server analytics cookies", async (contract) => {
+ it.each([BUSINESS_SCHEMA_VERSION])("accepts a forum opener with current contract %s without server analytics cookies", async (contract) => {
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "forum", parentChannelId: null })
const request = postReq({ content: "a post's opener message" })
@@ -445,10 +449,9 @@ describe("POST /api/community/channels/[id]/messages", () => {
expect(res.status).toBe(201)
expect(mockCreateMessage).toHaveBeenCalled()
expect(res.cookies.get("alook_ga_session")).toBeUndefined()
- expect(res.headers.get("x-alook-community-contract")).toBe(contract === 3 ? "3" : null)
+ expect(res.headers.get("x-alook-community-contract")).toBe(String(BUSINESS_SCHEMA_VERSION))
const confirmation = await res.json()
- expect(confirmation).toMatchObject({ message: { id: "m1" }, threadId: "thread_1", ...(contract === 3 ? { contractVersion: 3, channelId: "c1", deduped: false } : {}) })
- if (contract === 1) expect(confirmation).not.toHaveProperty("deduped")
+ expect(confirmation).toMatchObject({ message: { id: "m1" }, threadId: "thread_1", contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", deduped: false })
})
it("a DM id via the door routes to the DM arm — the block gate runs (blocked peer → 403, not a silent channel-route bypass)", async () => {
@@ -519,7 +522,8 @@ describe("POST /api/community/channels/[id]/messages", () => {
const body = await res.json() as { message: { id: string; seq: number; clientNonce?: string }; deduped?: boolean }
expect(res.status).toBe(201)
- expect(body).toEqual({
+ expect(body).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", deduped: false,
message: expect.objectContaining({ id: "m1", seq: 12, clientNonce: "n1" }),
})
})
@@ -571,16 +575,19 @@ describe("POST /api/community/channels/[id]/messages", () => {
const body = await res.json() as { message: { id: string; seq: number; clientNonce?: string }; deduped: boolean }
expect(res.status).toBe(200)
- expect(body).toEqual({
+ expect(body).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1",
message: expect.objectContaining({ id: "m-existing", seq: 8, clientNonce: "n1" }),
deduped: true,
})
expect(mockCreateMessage).not.toHaveBeenCalled()
})
- it("returns the full raw message row for human POST convergence", async () => {
+ it("returns the full current message resource for human POST convergence", async () => {
const row = {
id: "m_full",
+ clientNonce: "client-1",
+ authorAvatarVersion: 0,
authorId: "u1",
authorName: "Canonical Author",
authorImage: "https://avatar.test/u1.png",
@@ -599,9 +606,17 @@ describe("POST /api/community/channels/[id]/messages", () => {
const response = await POST(postReq({ content: "canonical content", nonce: "client-1" }), ctx)
expect(response.status).toBe(201)
- expect(response.headers.get("x-alook-community-contract")).toBeNull()
+ expect(response.headers.get("x-alook-community-contract")).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(response.cookies.get("alook_ga_session")).toBeUndefined()
- expect(await response.json()).toEqual({ message: row })
+ expect(await response.json()).toEqual({ profiles: [{ id: "u1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }],
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", deduped: false,
+ message: {
+ id: "m_full", channelId: "c1", seq: 42, clientNonce: "client-1",
+ authorId: "u1", authorName: "Canonical Author", authorAvatar: "https://avatar.test/u1.png", authorAvatarVersion: 0,
+ content: "canonical content", type: "chat", mentionType: null, replyToId: null,
+ attachments: [], embeds: [{ title: "Canonical embed" }], createdAt: "2026-08-07T10:00:00.000Z",
+ },
+ })
})
it("rejects content longer than MAX_MESSAGE_CONTENT_LENGTH with 400", async () => {
@@ -663,6 +678,8 @@ describe("POST /api/community/channels/[id]/messages", () => {
])
mockGetMessage.mockResolvedValue({
id: "m1",
+ seq: 12,
+ authorAvatarVersion: 0,
authorId: "u1",
authorName: "Alice",
authorImage: null,
@@ -1072,16 +1089,16 @@ describe("GET /api/community/channels/[id]/messages", () => {
// m-d → replies to r-in-scope again → resolves.
// m-e → no reply.
mockListMessages.mockResolvedValue([
- { id: "m-a", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hey", type: "default", mentionType: null, replyToId: "r-in-scope", channelId: "c1", embeds: null, createdAt: "t1" },
- { id: "m-b", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "leak?", type: "default", mentionType: null, replyToId: "r-out-of-scope", channelId: "c1", embeds: null, createdAt: "t2" },
- { id: "m-c", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "gone", type: "default", mentionType: null, replyToId: "r-missing", channelId: "c1", embeds: null, createdAt: "t3" },
- { id: "m-d", authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, content: "again", type: "default", mentionType: null, replyToId: "r-in-scope", channelId: "c1", embeds: null, createdAt: "t4" },
- { id: "m-e", authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, content: "no reply", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "t5" },
+ { id: "m-a", seq: 1, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "hey", type: "default", mentionType: null, replyToId: "r-in-scope", channelId: "c1", embeds: null, createdAt: "t1" },
+ { id: "m-b", seq: 2, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "leak?", type: "default", mentionType: null, replyToId: "r-out-of-scope", channelId: "c1", embeds: null, createdAt: "t2" },
+ { id: "m-c", seq: 3, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "gone", type: "default", mentionType: null, replyToId: "r-missing", channelId: "c1", embeds: null, createdAt: "t3" },
+ { id: "m-d", seq: 4, authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "again", type: "default", mentionType: null, replyToId: "r-in-scope", channelId: "c1", embeds: null, createdAt: "t4" },
+ { id: "m-e", seq: 5, authorId: "u2", authorName: "B", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "no reply", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "t5" },
])
// The (mocked) scoped query only ever returns in-scope rows — "r-out-of-scope"
// and "r-missing" are absent, simulating the real WHERE-clause scoping.
mockGetMessagesByIdsInScope.mockResolvedValue([
- { id: "r-in-scope", authorName: "Zed", content: "original", channelId: "c1", dmConversationId: null },
+ { id: "r-in-scope", authorId: "zed", authorName: "Zed", content: "original", channelId: "c1", dmConversationId: null },
])
const res = await GET(getReq(), ctx)
@@ -1089,10 +1106,10 @@ describe("GET /api/community/channels/[id]/messages", () => {
const body = await res.json() as { messages: Array<{ id: string; replyTo?: { id: string; authorName: string; text: string; deleted?: boolean } }> }
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-a")?.replyTo).toEqual({ id: "r-in-scope", authorId: "zed", authorName: "Zed", text: "original" })
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-d")?.replyTo).toEqual({ id: "r-in-scope", authorId: "zed", authorName: "Zed", text: "original" })
expect(byId.get("m-e")?.replyTo).toBeUndefined()
expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)
@@ -1104,16 +1121,16 @@ describe("GET /api/community/channels/[id]/messages", () => {
it("retries BUSY reply enrichment and preserves the paginated response", async () => {
vi.spyOn(Math, "random").mockReturnValue(0)
mockListMessages.mockResolvedValue([
- { id: "m1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "reply", type: "default", mentionType: null, replyToId: "r1", channelId: "c1", embeds: null, createdAt: "t1" },
+ { id: "m1", seq: 1, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "reply", type: "default", mentionType: null, replyToId: "r1", channelId: "c1", embeds: null, createdAt: "t1" },
])
mockGetMessagesByIdsInScope
.mockRejectedValueOnce(new Error("D1_ERROR: database is locked"))
- .mockResolvedValueOnce([{ id: "r1", authorName: "B", content: "root", channelId: "c1", dmConversationId: null }])
+ .mockResolvedValueOnce([{ id: "r1", authorId: "reply-author", authorName: "B", content: "root", channelId: "c1", dmConversationId: null }])
const res = await GET(getReq(), ctx)
const body = await res.json()
expect(body.messages).toHaveLength(1)
- expect(body.messages[0].replyTo).toEqual({ id: "r1", authorName: "B", text: "root" })
- expect(body.hasMore).toBe(false)
+ expect(body.messages[0].replyTo).toEqual({ id: "r1", authorId: "reply-author", authorName: "B", text: "root" })
+ expect(body.page.hasMoreOlder).toBe(false)
expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(2)
expect(mockListMessages).toHaveBeenCalledTimes(1)
})
@@ -1121,7 +1138,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
it("rethrows a non-BUSY reply-enrichment failure without retrying", async () => {
const error = new Error("bad projection")
mockListMessages.mockResolvedValue([
- { id: "m1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "reply", type: "default", mentionType: null, replyToId: "r1", channelId: "c1", embeds: null, createdAt: "t1" },
+ { id: "m1", seq: 1, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "reply", type: "default", mentionType: null, replyToId: "r1", channelId: "c1", embeds: null, createdAt: "t1" },
])
mockGetMessagesByIdsInScope.mockRejectedValueOnce(error)
await expect(GET(getReq(), ctx)).rejects.toBe(error)
@@ -1135,6 +1152,8 @@ describe("GET /api/community/channels/[id]/messages", () => {
mockListMessages.mockResolvedValue([
{
id: "m-1",
+ seq: 1,
+ authorAvatarVersion: 0,
authorId: "u1",
authorName: "Alice",
authorEmail: "[email protected]",
@@ -1151,12 +1170,13 @@ describe("GET /api/community/channels/[id]/messages", () => {
const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
const body = (await res.json()) as {
- messages: Array<{ authorName: string; authorAvatar: string }>
+ messages: Array<{ authorName: string; authorAvatar: string | null; authorEmail?: string }>
}
expect(body.messages[0]?.authorName).toBe("Alice")
expect(body.messages[0]?.authorName).not.toBe("Deleted user")
expect(body.messages[0]?.authorName).not.toContain("@")
- expect(body.messages[0]?.authorAvatar).toBe("A")
+ expect(body.messages[0]?.authorAvatar).toBeNull()
+ expect(body.messages[0]).not.toHaveProperty("authorEmail")
})
it("runs attachment, reaction, reply-target, child-channel, and latest-seq fetches in parallel", async () => {
@@ -1164,7 +1184,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
// concurrently (Promise.all), not sequentially. We prove concurrency by
// observing the in-flight count of the mocked queries.
mockListMessages.mockResolvedValue([
- { id: "m-1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hi", type: "default", mentionType: null, replyToId: "r-1", channelId: "c1", embeds: null, createdAt: "t1" },
+ { id: "m-1", seq: 1, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "hi", type: "default", mentionType: null, replyToId: "r-1", channelId: "c1", embeds: null, createdAt: "t1" },
])
let inFlight = 0
@@ -1200,8 +1220,8 @@ describe("GET /api/community/channels/[id]/messages", () => {
// a parsed array render as-is (no double-parse, no re-stringify).
const parsed = [{ url: "https://x/y", title: "hi" }]
mockListMessages.mockResolvedValue([
- { id: "m-1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "with embed", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: parsed, createdAt: "t1" },
- { id: "m-2", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "no embed", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: undefined, createdAt: "t2" },
+ { id: "m-1", seq: 1, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "with embed", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: parsed, createdAt: "t1" },
+ { id: "m-2", seq: 2, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "no embed", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: undefined, createdAt: "t2" },
])
const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
@@ -1211,21 +1231,19 @@ describe("GET /api/community/channels/[id]/messages", () => {
expect(byId.get("m-2")?.embeds).toBeUndefined()
})
- it("always includes latestSeq in the legacy-mode envelope", async () => {
- // The client (A2) reads latestSeq unconditionally — it must be present in
- // every mode's envelope, including the legacy path.
+ it("always includes latestSeq in the current page envelope", async () => {
mockListMessages.mockResolvedValue([])
mockGetLatestMessageSeq.mockResolvedValue(17)
const res = await GET(getReq(), ctx)
expect(res.status).toBe(200)
- const body = await res.json() as { latestSeq: number }
- expect(body.latestSeq).toBe(17)
+ const body = await res.json() as { page: { latestSeq: number } }
+ expect(body.page.latestSeq).toBe(17)
expect(mockGetLatestMessageSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "c1" })
})
it("passes a normalized tag into the channel-scoped message query before pagination", async () => {
mockListMessages.mockResolvedValue([])
- const req = new NextRequest("http://localhost/api/community/channels/c1/messages?tag=%20Bug%20&cursor=2026-01-01T00%3A00%3A00.000Z%7Cm1", { method: "GET" })
+ const req = new NextRequest("http://localhost/api/community/channels/c1/messages?tag=%20Bug%20&cursor=2026-01-01T00%3A00%3A00.000Z%7Cm1", { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } })
const res = await GET(req, ctx)
expect(res.status).toBe(200)
expect(mockListMessages).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
@@ -1236,7 +1254,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
})
it.each(["", " "])("rejects an explicitly empty tag %j instead of widening to all messages", async (tag) => {
- const req = new NextRequest(`http://localhost/api/community/channels/c1/messages?tag=${encodeURIComponent(tag)}`, { method: "GET" })
+ const req = new NextRequest(`http://localhost/api/community/channels/c1/messages?tag=${encodeURIComponent(tag)}`, { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } })
const res = await GET(req, ctx)
expect(res.status).toBe(400)
expect(mockListMessages).not.toHaveBeenCalled()
@@ -1244,7 +1262,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
it("rejects a tag longer than the public message-tag limit", async () => {
const tag = "x".repeat(MAX_FORUM_TAG_LENGTH + 1)
- const req = new NextRequest(`http://localhost/api/community/channels/c1/messages?tag=${tag}`, { method: "GET" })
+ const req = new NextRequest(`http://localhost/api/community/channels/c1/messages?tag=${tag}`, { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } })
const res = await GET(req, ctx)
expect(res.status).toBe(400)
expect(mockListMessages).not.toHaveBeenCalled()
@@ -1258,11 +1276,11 @@ describe("GET /api/community/channels/[id]/messages", () => {
})
mockListMessagesAround.mockResolvedValue({
older: [
- { id: "m_o1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "o1", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:02.000Z" },
+ { id: "m_o1", seq: 2, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "o1", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:02.000Z" },
],
newer: [
- { id: "m_anchor", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "anchor", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:03.000Z" },
- { id: "m_n1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "n1", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:04.000Z" },
+ { id: "m_anchor", seq: 3, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "anchor", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:03.000Z" },
+ { id: "m_n1", seq: 4, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "n1", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:04.000Z" },
],
hasMoreOlder: true,
hasMoreNewer: false,
@@ -1270,25 +1288,27 @@ describe("GET /api/community/channels/[id]/messages", () => {
mockGetLatestMessageSeq.mockResolvedValue(9)
const url = "http://localhost/api/community/channels/c1/messages?anchor=m_anchor"
- const req = new NextRequest(url, { method: "GET" })
+ const req = new NextRequest(url, { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } })
const res = await GET(req, ctx)
expect(res.status).toBe(200)
const body = (await res.json()) as {
messages: Array<{ id: string }>
- hasMoreOlder: boolean
- hasMoreNewer: boolean
- olderCursor?: string
- newerCursor?: string
- latestSeq: number
+ page: {
+ hasMoreOlder: boolean
+ hasMoreNewer: boolean
+ olderCursor: string | null
+ newerCursor: string | null
+ latestSeq: number
+ }
}
// Order is chronological ASC: older-reversed then newer.
expect(body.messages.map((m) => m.id)).toEqual(["m_o1", "m_anchor", "m_n1"])
- expect(body.hasMoreOlder).toBe(true)
- expect(body.hasMoreNewer).toBe(false)
+ expect(body.page.hasMoreOlder).toBe(true)
+ expect(body.page.hasMoreNewer).toBe(false)
// olderCursor points at the oldest returned row; newerCursor only when hasMoreNewer.
- expect(body.olderCursor).toBe(`2026-06-30T00:00:02.000Z|m_o1`)
- expect(body.newerCursor).toBeUndefined()
- expect(body.latestSeq).toBe(9)
+ expect(body.page.olderCursor).toBe(`2026-06-30T00:00:02.000Z|m_o1`)
+ expect(body.page.newerCursor).toBeNull()
+ expect(body.page.latestSeq).toBe(9)
// Scope-first resolve: anchor lookup passes the channel scope.
expect(mockGetMessageInScope).toHaveBeenCalledWith(expect.anything(), "m_anchor", { channelId: "c1" })
})
@@ -1297,6 +1317,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
mockGetMessageInScope.mockResolvedValue(null)
const req = new NextRequest("http://localhost/api/community/channels/c1/messages?anchor=m_missing", {
method: "GET",
+ headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) },
})
const res = await GET(req, ctx)
expect(res.status).toBe(404)
@@ -1306,7 +1327,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
it("applies tag to the same channel-scoped anchor window", async () => {
mockGetMessageInScope.mockResolvedValue({ id: "m_anchor", createdAt: "2026-06-30T00:00:03.000Z" })
mockListMessagesAround.mockResolvedValue({ older: [], newer: [], hasMoreOlder: false, hasMoreNewer: false })
- const req = new NextRequest("http://localhost/api/community/channels/c1/messages?anchor=m_anchor&tag=%20Bug%20", { method: "GET" })
+ const req = new NextRequest("http://localhost/api/community/channels/c1/messages?anchor=m_anchor&tag=%20Bug%20", { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } })
const res = await GET(req, ctx)
expect(res.status).toBe(200)
expect(mockListMessagesAround).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
@@ -1320,32 +1341,34 @@ describe("GET /api/community/channels/[id]/messages", () => {
describe("?since mode", () => {
it("returns rows strictly newer than the cursor with hasMoreNewer + newerCursor + latestSeq", async () => {
mockListMessagesSince.mockResolvedValue([
- { id: "m_1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "1", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:01.000Z" },
- { id: "m_2", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "2", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:02.000Z" },
+ { id: "m_1", seq: 1, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "1", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:01.000Z" },
+ { id: "m_2", seq: 2, authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, authorAvatarVersion: 0, content: "2", type: "default", mentionType: null, replyToId: null, channelId: "c1", embeds: null, createdAt: "2026-06-30T00:00:02.000Z" },
])
mockGetLatestMessageSeq.mockResolvedValue(2)
const req = new NextRequest(
"http://localhost/api/community/channels/c1/messages?since=2026-06-30T00:00:00.000Z%7Cm_0",
- { method: "GET" },
+ { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } },
)
const res = await GET(req, ctx)
expect(res.status).toBe(200)
const body = (await res.json()) as {
messages: Array<{ id: string }>
- hasMoreNewer: boolean
- newerCursor?: string
- hasMoreOlder: boolean
- olderCursor?: string
- latestSeq: number
+ page: {
+ hasMoreNewer: boolean
+ newerCursor: string | null
+ hasMoreOlder: boolean
+ olderCursor: string | null
+ latestSeq: number
+ }
}
expect(body.messages.map((m) => m.id)).toEqual(["m_1", "m_2"])
- expect(body.hasMoreNewer).toBe(false)
- expect(body.latestSeq).toBe(2)
+ expect(body.page.hasMoreNewer).toBe(false)
+ expect(body.page.latestSeq).toBe(2)
// A since delta must carry an older-side signal so it can be paged back
// through if it lands as the sole/oldest cache page (the DM-history bug).
- expect(body.hasMoreOlder).toBe(true)
- expect(body.olderCursor).toBe("2026-06-30T00:00:01.000Z|m_1")
+ expect(body.page.hasMoreOlder).toBe(true)
+ expect(body.page.olderCursor).toBe("2026-06-30T00:00:01.000Z|m_1")
// Anchor-mode paths must not fire.
expect(mockGetMessageInScope).not.toHaveBeenCalled()
expect(mockListMessagesAround).not.toHaveBeenCalled()
@@ -1355,7 +1378,7 @@ describe("GET /api/community/channels/[id]/messages", () => {
mockListMessagesSince.mockResolvedValue([])
const req = new NextRequest(
"http://localhost/api/community/channels/c1/messages?since=2026-06-30T00:00:00.000Z%7Cm_0&tag=%20Bug%20",
- { method: "GET" },
+ { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } },
)
const res = await GET(req, ctx)
expect(res.status).toBe(200)
@@ -1462,7 +1485,7 @@ describe("GET explicit conversation entry", () => {
createdAt: "2026-10-15T00:00:05.000Z",
}
const pointer = { lastReadMessageId: "read", lastReadAt: message.createdAt, lastReadSeq: 5 }
- const request = (search = "entry=1", contract = "3", bot = false) => new NextRequest(`http://localhost/api/community/channels/c1/messages?${search}`, {
+ const request = (search = "entry=1", contract = String(BUSINESS_SCHEMA_VERSION), bot = false) => new NextRequest(`http://localhost/api/community/channels/c1/messages?${search}`, {
headers: { "x-alook-community-contract": contract, ...(bot ? { Authorization: "Bearer crk_entry_fixture" } : {}) },
})
@@ -1526,9 +1549,9 @@ describe("GET explicit conversation entry", () => {
it("returns qualified identity, pointer and confirmed empty first window through the existing door", async () => {
const response = await GET(request(), ctx)
expect(response.status).toBe(200)
- expect(response.headers.get("x-alook-community-contract")).toBe("3")
+ expect(response.headers.get("x-alook-community-contract")).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(await response.json()).toMatchObject({
- contractVersion: 3, readStateRevision: 0, viewerId: "u1", channelId: "c1", channel: { id: "c1", type: "text", archived: false },
+ contractVersion: BUSINESS_SCHEMA_VERSION, readStateRevision: 0, viewerId: "u1", channelId: "c1", channel: { id: "c1", type: "text", archived: false },
access: { channelId: "c1", canRead: true, canSend: true, canCreateDiscussion: true },
readState: { channelId: "c1", lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },
selection: { reason: "tail", anchorMessageId: null }, messages: [],
@@ -1603,8 +1626,8 @@ describe("GET explicit conversation entry", () => {
})
it.each([
- ["entry=0", "3", false], ["entry=1", "2", false], ["entry=1", "3", true],
- ["entry=1&window=before&cursor=2026-10-15T00%3A00%3A00.000Z%7Cm1", "3", false],
+ ["entry=0", String(BUSINESS_SCHEMA_VERSION), false], ["entry=1", "2", false], ["entry=1", String(BUSINESS_SCHEMA_VERSION), true],
+ ["entry=1&window=before&cursor=2026-10-15T00%3A00%3A00.000Z%7Cm1", String(BUSINESS_SCHEMA_VERSION), false],
])("rejects an unsupported entry before reading a pointer or messages: %s/%s/%s", async (search, contract, bot) => {
const response = await GET(request(String(search), String(contract), Boolean(bot)), ctx)
expect(response.status).toBe(400)
@@ -1622,7 +1645,7 @@ describe("GET explicit conversation entry", () => {
const body = await response.json()
expect(body).toMatchObject({ channel: { type: "dm", serverId: null }, access: { canRead: true, canSend: false, canCreateDiscussion: false }, peer: { id: "peer", name: "Peer", avatarVersion: 5 } })
expect(body.peer).not.toHaveProperty("email")
- expect(mockGetUserPublic).toHaveBeenCalledWith(expect.anything(), "peer")
+ expect(queries.communityUserProfile.getResourceProfiles).toHaveBeenCalledWith(expect.anything(), ["peer"])
expect(mockAreFriends).toHaveBeenCalledWith(expect.anything(), "u1", "peer")
expect(mockGetChannelForMember).not.toHaveBeenCalled()
expect(mockCreateOrGetDM).not.toHaveBeenCalled()
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index 2d30e6e7a..9e6559813 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts
@@ -1,16 +1,12 @@
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { flattenError } from "zod"
import { NextRequest, NextResponse } from "next/server"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeError } from "@/lib/middleware/helpers"
import { getDb, getPrimaryDb } from "@/lib/db"
import { queries, withD1Retry, CommunityAgentSendRequestSchema, MAX_FORUM_TAG_LENGTH, utcDayKey, WS_EVENTS, PARTICIPANT_SOURCE } from "@alook/shared"
-import {
- parseCursor,
- parseAnchor,
- parsePageSize,
- parseCommunityMessageWindow,
-} from "@/lib/community/messages"
-import { mapPostedMessageForApi } from "@/lib/community/message-payload"
+import { parseCommunityMessageWindow } from "@/lib/community/messages"
+import { mapPostedMessageForApi, readCommunityMessageProfiles } from "@/lib/community/message-payload"
import { readCommunityMessageWindow } from "@/lib/community/message-window.server"
import { readCommunityConversationEntry } from "@/lib/community/conversation-entry.server"
import { requestsCommunityContract, requestedCommunityContract, COMMUNITY_CONTRACT_HEADER, CommunityMessagePostedSchema, type CommunityContract } from "@alook/shared"
@@ -79,8 +75,8 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
)
}
const channelId = resolved.value.target.channelId
- if (params.has("entry") && (params.get("entry") !== "1" || ctx.actor.kind !== "human" || requestedCommunityContract(req.headers) !== 3)) {
- return writeError("entry requires human resource contract 3", 400)
+ if (params.has("entry") && (params.get("entry") !== "1" || ctx.actor.kind !== "human" || requestedCommunityContract(req.headers) !== COMMUNITY_RESOURCE_CONTRACT_VERSION)) {
+ return writeError("entry requires current human resource contract", 400)
}
// TODO(route-disc): unify the two response projections.
// Auth/pagination-scope already single-source (one mask, one channel-scoped set);
@@ -111,10 +107,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
// ── human arm: createdAt-anchored window → enrich → {messages} ──
const userId = ctx.actor.userId
let window
- try { window = requestsCommunityContract(req.headers) ? parseCommunityMessageWindow(params) : {
- anchorId: parseAnchor(params.get("anchor")), since: parseCursor(params.get("since")),
- cursor: parseCursor(params.get("cursor")), pageSize: parsePageSize(params.get("limit")),
- } } catch (error) { return writeError(error instanceof Error ? error.message : "invalid message window", 400) }
+ try { window = parseCommunityMessageWindow(params) } catch (error) { return writeError(error instanceof Error ? error.message : "invalid message window", 400) }
const rawTag = params.get("tag")
const tag = rawTag?.trim().toLowerCase()
if (rawTag !== null && !tag) return writeError("tag must not be empty", 400)
@@ -129,7 +122,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
}
const result = await readCommunityMessageWindow(db, {
- viewerId: userId, target: resolved.value, window, tag, contract: requestedCommunityContract(req.headers) ?? 1,
+ viewerId: userId, target: resolved.value, window, tag, contract: COMMUNITY_RESOURCE_CONTRACT_VERSION,
})
if (!result.ok) return NextResponse.json({ error: result.error, details: result.details }, { status: result.status })
return writeCommunityMessagesRead(req, channelId, result.page)
@@ -173,7 +166,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
if (ctx.actor.kind === "bot") {
return handleBotSend(db, ctx.actor.userId, ctx.env, raw)
}
- return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw, requestedCommunityContract(req.headers) ?? 1)
+ return handleHumanSend(db, ctx.actor.userId, ctx.env, ctx.params?.id, raw, COMMUNITY_RESOURCE_CONTRACT_VERSION)
})
/**
@@ -231,8 +224,8 @@ async function handleHumanSend(
source: "web",
})
if (!created.ok) return NextResponse.json({ error: created.error }, { status: created.status })
- const response = humanMessageConfirmation(contract, target.channelId, {
- message: contract === 3 ? await mapPostedMessageForApi(db, target.channelId, created.message, contract) : created.message,
+ const response = humanMessageConfirmation(db, contract, target.channelId, {
+ message: await mapPostedMessageForApi(db, target.channelId, created.message, contract),
threadId: created.thread.id,
deduped: created.deduped,
}, created.deduped ? 200 : 201)
@@ -246,7 +239,7 @@ async function handleHumanSend(
clientNonce,
})
if (replay) {
- return humanMessageConfirmation(contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, replay.row, contract), deduped: true }, 200)
+ return humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, replay.row, contract), deduped: true }, 200)
}
const result = await createCommunityMessage({
@@ -260,14 +253,15 @@ async function handleHumanSend(
attachmentIds: attachmentIds.length > 0 ? attachmentIds : undefined,
})
if (!result.ok) return NextResponse.json({ error: result.error }, { status: result.status })
- const response = humanMessageConfirmation(contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, result.row, contract), deduped: result.deduped }, 201)
+ const response = humanMessageConfirmation(db, contract, target.channelId, { message: await mapPostedMessageForApi(db, target.channelId, result.row, contract), deduped: result.deduped }, 201)
return response
}
-function humanMessageConfirmation(contract: CommunityContract, channelId: string, payload: { message: unknown; deduped?: boolean; threadId?: string }, status: number): NextResponse {
- if (contract !== 3) return NextResponse.json(payload, { status })
- return NextResponse.json(CommunityMessagePostedSchema.parse({ contractVersion: 3, channelId, ...payload, deduped: payload.deduped === true }), {
- status, headers: { [COMMUNITY_CONTRACT_HEADER]: "3" },
+async function humanMessageConfirmation(db: ReturnType<typeof getDb>, contract: CommunityContract, channelId: string, payload: { message: unknown; deduped?: boolean; threadId?: string }, status: number): Promise<NextResponse> {
+ const message = CommunityMessagePostedSchema.shape.message.parse(payload.message)
+ const profiles = await readCommunityMessageProfiles(db, [message])
+ return NextResponse.json(CommunityMessagePostedSchema.parse({ contractVersion: contract, channelId, ...payload, profiles, deduped: payload.deduped === true }), {
+ status, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) },
})
}
diff --git a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
index c246e3269..90ec93946 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/[userId]/route.test.ts
@@ -1,3 +1,4 @@
+import { currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
import { decodeCommunityBrowserEvent } from "@alook/shared"
@@ -95,7 +96,7 @@ describe("DELETE /channels/[id]/participants/[userId] — leave", () => {
expect(res.status).toBe(204)
for (const [, event] of mockBroadcastToUserSafe.mock.calls) {
expect(Object.keys(event).sort()).toEqual(["channelId", "present", "relation", "serverId", "type", "userId"])
- expect(decodeCommunityBrowserEvent(event).ok).toBe(true)
+ expect(decodeCommunityBrowserEvent(currentCommunityEventFixture(event)).ok).toBe(true)
}
expect(mockDeleteThreadParticipantWithCreatorHandoff).toHaveBeenCalledWith(
expect.anything(),
diff --git a/src/web/src/app/api/community/channels/[id]/participants/route.test.ts b/src/web/src/app/api/community/channels/[id]/participants/route.test.ts
index 03c3ebf31..40cc59e21 100644
--- a/src/web/src/app/api/community/channels/[id]/participants/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/participants/route.test.ts
@@ -1,3 +1,4 @@
+import { currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
import { decodeCommunityBrowserEvent } from "@alook/shared"
@@ -92,7 +93,7 @@ describe("POST /channels/[id]/participants", () => {
expect(res.status).toBe(201)
for (const [, event] of mockBroadcastToUserSafe.mock.calls) {
expect(Object.keys(event).sort()).toEqual(["channelId", "present", "relation", "serverId", "type", "userId"])
- expect(decodeCommunityBrowserEvent(event).ok).toBe(true)
+ expect(decodeCommunityBrowserEvent(currentCommunityEventFixture(event)).ok).toBe(true)
}
expect(mockAddThreadParticipant).toHaveBeenCalledWith(expect.anything(), {
threadChannelId: "t1", userId: "u2", source: "added",
diff --git a/src/web/src/app/api/community/channels/[id]/pins/access.test.ts b/src/web/src/app/api/community/channels/[id]/pins/access.test.ts
index 613eea5d5..e19045fcc 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/access.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/access.test.ts
@@ -1,3 +1,4 @@
+import * as currentCommunityTables from "../../../../../../../../shared/src/db/community-schema"
import { DatabaseSync, type SQLInputValue } from "node:sqlite"
import { createRequire } from "node:module"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -15,9 +16,12 @@ import {
import type { AuthenticatedHandler } from "@/lib/middleware/auth"
const { getTableConfig } = createRequire(import.meta.resolve("@alook/shared"))("drizzle-orm/sqlite-core") as {
- getTableConfig: (table: object) => { name: string; columns: Array<{ name: string; getSQLType: () => string }> }
+ getTableConfig: (table: object) => { name: string; columns: Array<{ name: string; getSQLType: () => string; default?: unknown }> }
}
+const { is } = createRequire(import.meta.resolve("@alook/shared"))("drizzle-orm") as { is: (value: unknown, type: unknown) => boolean }
+const { SQLiteTable } = createRequire(import.meta.resolve("@alook/shared"))("drizzle-orm/sqlite-core") as { SQLiteTable: unknown }
+
const { state, fanOut } = vi.hoisted(() => ({
state: { binding: null as unknown as D1Database, userId: "admin" },
fanOut: vi.fn(),
@@ -45,13 +49,18 @@ let sessions: string[]
function seedDatabase() {
const sqlite = new DatabaseSync(":memory:")
- for (const table of [user, communityChannel, communityChannelMember, communityMessage, communityServerMember, communityCategory, communityPin]) {
+ for (const table of [user, ...Object.values(currentCommunityTables).filter(table => is(table, SQLiteTable))]) {
const config = getTableConfig(table)
- sqlite.exec(`CREATE TABLE "${config.name}" (${config.columns.map((column) => `"${column.name}" ${column.getSQLType()}`).join(", ")})`)
+ sqlite.exec(`CREATE TABLE "${config.name}" (${config.columns.map(column => {
+ const value = column.default
+ const defaultSql = typeof value === "string" ? " DEFAULT '" + value.replaceAll("'", "''") + "'" : typeof value === "number" ? ` DEFAULT ${value}` : typeof value === "boolean" ? ` DEFAULT ${Number(value)}` : ""
+ return `"${column.name}" ${column.getSQLType()}${defaultSql}`
+ }).join(", ")})`)
}
sqlite.exec(`
INSERT INTO user (id,name,discriminator,"avatarVersion","isBot") VALUES
('admin','Administrator','0001',0,0),('creator','Creator','0002',0,0),('member','Member','0003',0,0);
+ INSERT INTO community_server (id,name,discriminator,description,icon,official,owner_id,created_at) VALUES ('server','Server','0042','',NULL,0,'creator','2026-10-19T00:00:00Z');
INSERT INTO community_server_member (id,server_id,user_id,role) VALUES
('admin-row','server','admin','admin'),('creator-row','server','creator','member'),('member-row','server','member','member');
INSERT INTO community_category (id,server_id,private) VALUES ('private-category','server',1),('public-category','server',0);
@@ -61,6 +70,7 @@ function seedDatabase() {
('private-thread','server',NULL,'thread','admin','private'),
('private-forum','server','private-category','forum','creator',NULL),
('private-post','server',NULL,'thread','admin','private-forum');
+ UPDATE community_channel SET name=id,topic='',position=0,archived=0,message_count=0,created_at='2026-10-19T00:00:00Z';
INSERT INTO community_message (id,author_id,content,channel_id,seq,created_at) VALUES
('private-message','creator','Private example','private',1,'2026-10-19T00:00:00Z'),
('public-message','creator','Public example','public',1,'2026-10-19T00:00:00Z'),
@@ -80,6 +90,7 @@ function seedDatabase() {
function session(view: DatabaseSync) {
let current = view
return {
+ async batch(statements: Array<{ all: () => Promise<unknown> }>) { return Promise.all(statements.map(statement => statement.all())) },
prepare(sql: string) {
let values: SQLInputValue[] = []
const statement = () => {
diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
index 4ee2eaa70..b4c9a6e96 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture, messageResourceFixture, serverResourceFixture, fullResourceBundleFixture } from "@/test/community-resource-fixtures";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
@@ -5,6 +6,8 @@ vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}));
+const mockReadBundle = vi.fn();
+vi.mock("@/lib/community/attention-resources.server", () => ({ readCommunityResourceBundle: (...args: unknown[]) => mockReadBundle(...args) }));
const mockGetChannel = vi.fn();
const mockGetChannelForMember = vi.fn();
const mockGetMember = vi.fn();
@@ -189,7 +192,8 @@ describe("POST /api/community/channels/[id]/pins", () => {
describe("GET /api/community/channels/[id]/pins", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" });
+ mockGetChannelForMember.mockResolvedValue(channelResourceFixture({ id: "c1", serverId: "s1" }));
+ mockReadBundle.mockResolvedValue(fullResourceBundleFixture("u1", [serverResourceFixture({ id: "s1", ownerId: "u1", isOwner: true })], [channelResourceFixture({ id: "c1", serverId: "s1" })], [messageResourceFixture({ id: "m1", channelId: "c1", seq: 42, content: "hi", authorId: "u42", authorName: "Ada" })], [{ id: "u42", name: "Ada", discriminator: "0042", avatar: null, avatarVersion: 0 }]));
});
it("returns each pin's authorId so the client can derive a beam avatar", async () => {
@@ -207,14 +211,16 @@ describe("GET /api/community/channels/[id]/pins", () => {
const res = await GET(getReq(), ctx);
expect(res.status).toBe(200);
- const body = (await res.json()) as { pins: Array<{ id: string; seq: number; authorId: string; authorName: string }> };
+ const body = (await res.json()) as { pins: Array<{ id: string }>; resources: { messages: Array<{ id: string; seq: number; authorId: string; authorName: string }> } };
expect(body.pins).toHaveLength(1);
- expect(body.pins[0].authorId).toBe("u42");
+ expect(body.resources.messages[0].authorId).toBe("u42");
expect(body.pins[0].id).toBe("m1");
- expect(body.pins[0].authorName).toBe("Ada");
+ expect(body.resources.messages[0].authorName).toBe("Ada");
// seq lets the client jumpToSeq to the pinned message (scroll+highlight, or
// open the context sheet if it's outside the loaded window).
- expect(body.pins[0].seq).toBe(42);
+ expect(body.resources.messages[0].seq).toBe(42);
+ expect(body.pins).toEqual([{ id: "m1" }]);
+ expect(mockReadBundle).toHaveBeenCalledExactlyOnceWith(expect.anything(), "u1", { channelIds: ["c1"], messageIds: ["m1"] });
});
it("returns 403 when the caller can't see the channel", async () => {
diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.ts b/src/web/src/app/api/community/channels/[id]/pins/route.ts
index 56cb283e8..a826e3c59 100644
--- a/src/web/src/app/api/community/channels/[id]/pins/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/pins/route.ts
@@ -1,3 +1,4 @@
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
@@ -6,8 +7,8 @@ import { queries, isUniqueConstraintError, WS_EVENTS } from "@alook/shared"
import { fanOutToChannel } from "@/lib/community/fanout"
import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"
import { requirePinnableSurface } from "@/lib/community/channel-write-guard"
-import { avatarInitial } from "@/lib/community/avatar"
-import { canonicalUserImage } from "@/lib/community/storage"
+
+
export const GET = withAuth(async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
@@ -18,27 +19,9 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
if (!auth.ok) return writeError(auth.error, auth.status)
const rows = await queries.communityPin.listPins(db, channelId)
- const pins = rows.map((r) => ({
- id: r.message.id,
- // seq is the per-channel sequence the client needs to JUMP to a pinned
- // message (jumpToSeq: scroll+highlight if in the loaded window, else open
- // the context sheet). A pin is usually an OLD message outside the window,
- // so a scroll-only path silently no-ops without seq. listPins selects the
- // whole message row, so seq is already here.
- seq: r.message.seq,
- // authorId lets the client derive a stable beam avatar when the author
- // has no uploaded image — same shape mapMessageForApi feeds the message
- // list. Omitting it (and pre-flattening authorAvatar to an initial) is
- // why the pinned panel showed no avatar for image-less authors.
- authorId: r.author.id,
- authorName: r.author.name,
- authorAvatar: canonicalUserImage(r.author.id, r.author.image, r.author.avatarVersion)
- ?? avatarInitial(r.author.name),
- authorAvatarVersion: r.author.avatarVersion,
- content: r.message.content,
- createdAt: r.message.createdAt,
- }))
- return writeJSON({ pins })
+ const pins = rows.map(row => ({ id: row.message.id }))
+ const resources = await readCommunityResourceBundle(db, ctx.userId, { channelIds: [channelId], messageIds: pins.map(row => row.id) })
+ return writeJSON({ pins, resources })
})
export const POST = withAuth(async (req: NextRequest, ctx) => {
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.test.ts b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
index 4149954a2..b84b84065 100644
--- a/src/web/src/app/api/community/channels/[id]/read/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
@@ -90,6 +91,7 @@ import { PUT } from "./route"
function putReq(body?: unknown) {
return new NextRequest("http://localhost/api/community/channels/c1/read", {
method: "PUT",
+ headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION), "Content-Type": "application/json" },
...(body !== undefined
? { body: typeof body === "string" ? body : JSON.stringify(body) }
: {}),
@@ -118,7 +120,7 @@ describe("PUT /api/community/channels/[id]/read", () => {
mockIsBlocked.mockResolvedValue(false)
})
- it.each([2, 3] as const)("confirms contract %s with the committed exact target and revision", async (contract) => {
+ it.each([BUSINESS_SCHEMA_VERSION])("confirms contract %s with the committed exact target and revision", async (contract) => {
allow()
mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1", createdAt: "now", seq: 6 })
const request = putReq({ lastReadMessageId: "m1" })
@@ -182,7 +184,7 @@ describe("PUT /api/community/channels/[id]/read", () => {
{ __builder: "current" },
])
expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(1)
- await expect(res.json()).resolves.toEqual({ changed: true, targetSeq: 42, revision: 7 })
+ await expect(res.json()).resolves.toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", changed: true, targetSeq: 42, revision: 7 })
},
)
@@ -193,7 +195,7 @@ describe("PUT /api/community/channels/[id]/read", () => {
const res = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
- await expect(res.json()).resolves.toEqual({ changed: false, targetSeq: 42, revision: 9 })
+ await expect(res.json()).resolves.toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", changed: false, targetSeq: 42, revision: 9 })
expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
@@ -204,7 +206,7 @@ describe("PUT /api/community/channels/[id]/read", () => {
const res = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
- await expect(res.json()).resolves.toEqual({ changed: false, targetSeq: 42, revision: 9 })
+ await expect(res.json()).resolves.toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", changed: false, targetSeq: 42, revision: 9 })
expect(mockCanonicalReadTargetExistsCondition).toHaveBeenCalledOnce()
expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.ts b/src/web/src/app/api/community/channels/[id]/read/route.ts
index 2a316174f..e0a977eaf 100644
--- a/src/web/src/app/api/community/channels/[id]/read/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/read/route.ts
@@ -1,8 +1,8 @@
-import { requestsCommunityContract, requestedCommunityContract, communityReadSchemas } from "@alook/shared"
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION, communityReadSchemas } from "@alook/shared"
import { writeCommunityContractJSON } from "@/lib/community/read-contract"
import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
-import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { writeError } from "@/lib/middleware/helpers"
import { getPrimaryDb } from "@/lib/db"
import { queries, WS_EVENTS, withD1Retry } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
@@ -123,9 +123,6 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
})
}
- if (requestsCommunityContract(req.headers)) {
- const contract = requestedCommunityContract(req.headers) === 3 ? 3 : 2
- return writeCommunityContractJSON(communityReadSchemas(contract).readAdvance.parse({ contractVersion: contract, channelId, changed, targetSeq: target.seq, revision }), contract)
- }
- return writeJSON({ changed, targetSeq: target.seq, revision })
+ const contract = COMMUNITY_RESOURCE_CONTRACT_VERSION
+ return writeCommunityContractJSON(communityReadSchemas(contract).readAdvance.parse({ contractVersion: contract, channelId, changed, targetSeq: target.seq, revision }), contract)
})
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
index 13887dd19..6f7021ee2 100644
--- a/src/web/src/app/api/community/channels/[id]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, communityReadSchemas } from "@alook/shared"
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -155,12 +157,13 @@ describe("GET /channels/[id] — channel meta", () => {
})
it("returns the channel row when the caller is a member", async () => {
- const channel = { id: "c1", serverId: "s1", type: "thread", parentChannelId: "p1", parentMessageId: "m1", creatorId: "u1" }
+ const channel = channelResourceFixture({ id: "c1", serverId: "s1", type: "thread", parentChannelId: "p1", parentMessageId: "m1", creatorId: "u1" })
mockGetChannel.mockResolvedValue(channel)
mockGetChannelForMember.mockResolvedValue(channel)
const res = await GET(getReq(), { params: { id: "c1" } } as any)
expect(res.status).toBe(200)
- expect(await res.json()).toEqual(channel)
+ expect(res.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(communityReadSchemas().channel.parse(await res.json())).toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", channel, access: { channelId: "c1", canRead: true, canSend: true, canCreateDiscussion: false } })
})
it("returns 400 when the id is missing", async () => {
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
index c3a581438..efcd5d92f 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.test.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -27,6 +29,7 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
+ communityUserProfile: { getResourceProfiles: async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "User", discriminator: "0042", avatar: null, avatarVersion: 0 })) },
communityChannel: {
getChannelForMember: async () => {
const scope = await mockResolveChannelAccessContext()
@@ -42,9 +45,12 @@ vi.mock("@alook/shared", async () => {
communityMessage: {
getMessage: (...a: unknown[]) => mockGetMessage(...a),
getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIds(...a),
+ getMessagesByIdsInChannels: vi.fn(async () => []),
getFirstMessageResourcesByChannelIds: (...a: unknown[]) => mockGetFirstMessageByChannelIds(...a),
listMessages: (...a: unknown[]) => mockListMessages(...a),
},
+ communityAttachment: { listByMessageIds: vi.fn(async () => []) },
+ communityReaction: { listReactionsByMessageIds: vi.fn(async () => []) },
communityMessageTag: {
filterMessageIdsByTag: (...a: unknown[]) => mockFilterMessageIdsByTag(...a),
listTagsForMessages: (...a: unknown[]) => mockListTagsForMessages(...a),
@@ -79,7 +85,22 @@ vi.mock("@/lib/middleware/helpers", () => {
import { GET } from "./route"
function req(url = "http://localhost/api/community/channels/c1/threads") {
- return new NextRequest(url, { method: "GET" })
+ return new NextRequest(url, { method: "GET", headers: { "x-alook-community-contract": String(BUSINESS_SCHEMA_VERSION) } })
+}
+
+function parentRow(fields: Record<string, unknown>) {
+ return channelResourceFixture({ id: "c1", serverId: "s1", type: "forum", creatorId: null, ...fields })
+}
+function childRow(fields: Record<string, unknown>) {
+ const { activityAt, ...core } = fields
+ return { ...channelResourceFixture({ id: String(core.id), serverId: "s1", type: "thread", parentChannelId: "c1", ...core }), ...(activityAt === undefined ? {} : { activityAt }) }
+}
+function messageRow(fields: Record<string, unknown>) {
+ return { id: fields.id ?? "first-" + fields.channelId, channelId: "c1", seq: 1, authorId: "u1", authorName: "User", authorImage: null, authorAvatarVersion: 0,
+ content: "Body", type: "default", mentionType: null, replyToId: null, clientNonce: null, embeds: null, createdAt: "2026-10-01T00:00:00.000Z", ...fields }
+}
+function participantRow(fields: Record<string, unknown>) {
+ return { userName: "User", discriminator: "0042", userImage: null, userAvatarVersion: 0, ...fields }
}
const ctx = { params: { id: "c1" } } as any
@@ -87,14 +108,18 @@ const ctx = { params: { id: "c1" } } as any
describe("GET /api/community/channels/[id]/threads", () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockGetMessagesByIds.mockResolvedValue([])
+ mockGetFirstMessageByChannelIds.mockResolvedValue([])
+ mockListTagsForMessages.mockResolvedValue([])
+ mockListParticipantsForChannels.mockResolvedValue([])
mockFilterMessageIdsByTag.mockResolvedValue([])
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
+ mockGetChannel.mockResolvedValue(parentRow({ id: "c1", serverId: "s1" }))
mockGetMember.mockResolvedValue({ id: "m1", userId: "u1", serverId: "s1" })
// requireChannelAccess resolves through resolveChannelAccessContext — a
// public channel the caller is a member of.
mockResolveChannelAccessContext.mockResolvedValue({
- channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "forum" },
- anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "forum" },
+ channel: parentRow({ id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "forum" }),
+ anchor: parentRow({ id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "forum" }),
role: "member",
isPrivate: false,
isChannelMember: false,
@@ -107,7 +132,7 @@ describe("GET /api/community/channels/[id]/threads", () => {
// thread-B: creator only, has a first message
// thread-C: creator only, no first message
mockListChildChannels.mockResolvedValue([
- {
+ childRow({
id: "t-A",
name: "A",
type: "thread",
@@ -116,8 +141,8 @@ describe("GET /api/community/channels/[id]/threads", () => {
createdAt: "2026-06-30T00:00:00.000Z",
parentMessageId: "msg-p",
creatorId: null,
- },
- {
+ }),
+ childRow({
id: "t-B",
name: "B",
type: "thread",
@@ -126,8 +151,8 @@ describe("GET /api/community/channels/[id]/threads", () => {
createdAt: "2026-06-30T00:00:00.000Z",
parentMessageId: null,
creatorId: "u-b",
- },
- {
+ }),
+ childRow({
id: "t-C",
name: "C",
type: "thread",
@@ -136,19 +161,19 @@ describe("GET /api/community/channels/[id]/threads", () => {
createdAt: "2026-06-30T00:00:00.000Z",
parentMessageId: null,
creatorId: "u-c",
- },
+ }),
])
const res = await GET(req(), ctx)
expect(res.status).toBe(200)
const body = await res.json() as { threads: Array<{ id: string; parentMessageId: string | null }> }
- expect((body as typeof body & { parentType: string }).parentType).toBe("forum")
- expect((body as typeof body & { serverId: string }).serverId).toBe("s1")
+ expect((body as typeof body & { channel: { type: string } }).channel.type).toBe("forum")
+ expect((body as typeof body & { channel: { serverId: string } }).channel.serverId).toBe("s1")
expect(body.threads).toEqual([
- { id: "t-A", name: "A", type: "thread", messageCount: 3, lastMessageAt: "2026-06-30T01:00:00.000Z", createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: "msg-p", creatorId: null },
- { id: "t-B", name: "B", type: "thread", messageCount: 2, lastMessageAt: null, createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: null, creatorId: "u-b" },
- { id: "t-C", name: "C", type: "thread", messageCount: 1, lastMessageAt: null, createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: null, creatorId: "u-c" },
+ childRow({ id: "t-A", name: "A", type: "thread", messageCount: 3, lastMessageAt: "2026-06-30T01:00:00.000Z", createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: "msg-p", creatorId: null }),
+ childRow({ id: "t-B", name: "B", type: "thread", messageCount: 2, lastMessageAt: null, createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: null, creatorId: "u-b" }),
+ childRow({ id: "t-C", name: "C", type: "thread", messageCount: 1, lastMessageAt: null, createdAt: "2026-06-30T00:00:00.000Z", parentMessageId: null, creatorId: "u-c" }),
])
expect(mockGetMessagesByIds).not.toHaveBeenCalled()
expect(mockGetUsersByIds).not.toHaveBeenCalled()
@@ -161,16 +186,16 @@ describe("GET /api/community/channels/[id]/threads", () => {
})
it("loads requested included resources for the regular child collection through the same scoped batches", async () => {
- mockListChildChannels.mockResolvedValue([{ id: "t1", parentMessageId: "opener1" }])
- mockGetMessagesByIds.mockResolvedValue([{ id: "opener1", channelId: "c1" }])
- mockGetFirstMessageByChannelIds.mockResolvedValue([{ channelId: "t1", content: "first" }])
+ mockListChildChannels.mockResolvedValue([childRow({ id: "t1", parentMessageId: "opener1" })])
+ mockGetMessagesByIds.mockResolvedValue([messageRow({ id: "opener1", channelId: "c1" })])
+ mockGetFirstMessageByChannelIds.mockResolvedValue([messageRow({ channelId: "t1", content: "first" })])
mockListTagsForMessages.mockResolvedValue([{ messageId: "opener1", tag: "bug" }])
- mockListParticipantsForChannels.mockResolvedValue([{ channelId: "t1", userId: "u1" }])
+ mockListParticipantsForChannels.mockResolvedValue([participantRow({ channelId: "t1", userId: "u1" })])
const response = await GET(req("http://localhost/api/community/channels/c1/threads?include=parentMessage,firstMessage,tags,participants"), ctx)
expect(response.status).toBe(200)
- expect(await response.json()).toMatchObject({ threads: [{ id: "t1" }], hasMore: false, included: {
- parentMessages: [{ id: "opener1", channelId: "c1" }], firstMessages: [{ channelId: "t1", content: "first" }],
- tags: [{ messageId: "opener1", tag: "bug" }], participants: [{ channelId: "t1", userId: "u1" }],
+ expect(await response.json()).toMatchObject({ threads: [{ id: "t1" }], page: { hasMore: false }, included: {
+ messages: [{ id: "opener1", channelId: "c1" }, { channelId: "t1", content: "first" }],
+ tags: [{ messageId: "opener1", tag: "bug" }], members: [{ channelId: "t1", userId: "u1" }],
} })
expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["opener1"], { channelId: "c1" })
expect(mockListParticipantsForChannels).toHaveBeenCalledWith(expect.anything(), ["t1"], 5)
@@ -178,32 +203,32 @@ describe("GET /api/community/channels/[id]/threads", () => {
it("keeps non-forum child collections unchanged without querying archive tags", async () => {
mockResolveChannelAccessContext.mockResolvedValue({
- channel: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "text" },
- anchor: { id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "text" },
+ channel: parentRow({ id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "text" }),
+ anchor: parentRow({ id: "c1", serverId: "s1", parentChannelId: null, creatorId: null, type: "text" }),
role: "member",
isPrivate: false,
isChannelMember: false,
})
mockListChildChannels.mockResolvedValue([
- { id: "thread_1", parentMessageId: "opener_1" },
- { id: "thread_2", parentMessageId: null },
+ childRow({ id: "thread_1", parentMessageId: "opener_1" }),
+ childRow({ id: "thread_2", parentMessageId: null }),
])
const res = await GET(req(), ctx)
expect(res.status).toBe(200)
expect((await res.json()).threads).toEqual([
- { id: "thread_1", parentMessageId: "opener_1" },
- { id: "thread_2", parentMessageId: null },
+ childRow({ id: "thread_1", parentMessageId: "opener_1" }),
+ childRow({ id: "thread_2", parentMessageId: null }),
])
expect(mockFilterMessageIdsByTag).not.toHaveBeenCalled()
})
it("filters only the scoped child opener candidates for a normalized tag", async () => {
mockListChildChannels.mockResolvedValue([
- { id: "post_1", parentMessageId: "opener_1" },
- { id: "post_2", parentMessageId: "opener_2" },
- { id: "plain_thread", parentMessageId: null },
+ childRow({ id: "post_1", parentMessageId: "opener_1" }),
+ childRow({ id: "post_2", parentMessageId: "opener_2" }),
+ childRow({ id: "plain_thread", parentMessageId: null }),
])
mockFilterMessageIdsByTag
.mockResolvedValueOnce([])
@@ -213,14 +238,14 @@ describe("GET /api/community/channels/[id]/threads", () => {
expect(res.status).toBe(200)
expect(mockFilterMessageIdsByTag).toHaveBeenNthCalledWith(1, expect.anything(), ["opener_1", "opener_2"], "archived")
expect(mockFilterMessageIdsByTag).toHaveBeenNthCalledWith(2, expect.anything(), ["opener_1", "opener_2"], "bug")
- expect((await res.json()).threads).toEqual([{ id: "post_2", parentMessageId: "opener_2" }])
+ expect((await res.json()).threads).toEqual([childRow({ id: "post_2", parentMessageId: "opener_2" })])
})
- it("reuses the archive opener set for the legacy Archived tag filter", async () => {
+ it("reuses the archive opener set for the Archived tag filter", async () => {
mockListChildChannels.mockResolvedValue([
- { id: "post_1", parentMessageId: "opener_1" },
- { id: "post_2", parentMessageId: "opener_2" },
- { id: "plain_thread", parentMessageId: null },
+ childRow({ id: "post_1", parentMessageId: "opener_1" }),
+ childRow({ id: "post_2", parentMessageId: "opener_2" }),
+ childRow({ id: "plain_thread", parentMessageId: null }),
])
mockFilterMessageIdsByTag.mockResolvedValueOnce(["opener_1"])
@@ -235,7 +260,7 @@ describe("GET /api/community/channels/[id]/threads", () => {
["opener_1", "opener_2"],
"archived",
)
- expect((await res.json()).threads).toEqual([{ id: "post_1", parentMessageId: "opener_1" }])
+ expect((await res.json()).threads).toEqual([childRow({ id: "post_1", parentMessageId: "opener_1" })])
})
it("rejects an empty tag before querying message_tags", async () => {
@@ -255,14 +280,14 @@ describe("GET /api/community/channels/[id]/threads", () => {
it("returns a created-order page with scoped included resources and an opaque next cursor", async () => {
mockListForumThreadsByCreatedAt.mockResolvedValue([
- { id: "t3", parentMessageId: "m3", createdAt: "2026-08-08T03:00:00.000Z", activityAt: "2026-08-10T03:00:00.000Z" },
- { id: "t2", parentMessageId: "m2", createdAt: "2026-08-08T02:00:00.000Z", activityAt: "2026-08-11T02:00:00.000Z" },
- { id: "t1", parentMessageId: "m1", createdAt: "2026-08-08T01:00:00.000Z", activityAt: "2026-08-12T01:00:00.000Z" },
+ childRow({ id: "t3", parentMessageId: "m3", createdAt: "2026-08-08T03:00:00.000Z", activityAt: "2026-08-10T03:00:00.000Z" }),
+ childRow({ id: "t2", parentMessageId: "m2", createdAt: "2026-08-08T02:00:00.000Z", activityAt: "2026-08-11T02:00:00.000Z" }),
+ childRow({ id: "t1", parentMessageId: "m1", createdAt: "2026-08-08T01:00:00.000Z", activityAt: "2026-08-12T01:00:00.000Z" }),
])
- mockGetMessagesByIds.mockResolvedValue([{ id: "m3" }, { id: "m2" }])
- mockGetFirstMessageByChannelIds.mockResolvedValue([{ channelId: "t3", content: "preview" }])
+ mockGetMessagesByIds.mockResolvedValue([messageRow({ id: "m3" }), messageRow({ id: "m2" })])
+ mockGetFirstMessageByChannelIds.mockResolvedValue([messageRow({ channelId: "t3", content: "preview" })])
mockListTagsForMessages.mockResolvedValue([{ messageId: "m3", tag: "bug" }])
- mockListParticipantsForChannels.mockResolvedValue([{ channelId: "t3", userId: "u1" }])
+ mockListParticipantsForChannels.mockResolvedValue([participantRow({ channelId: "t3", userId: "u1" })])
const res = await GET(req(
"http://localhost/api/community/channels/c1/threads?order=createdAt&limit=2&include=parentMessage,firstMessage,tags,participants",
@@ -271,17 +296,15 @@ describe("GET /api/community/channels/[id]/threads", () => {
const body = await res.json()
expect(body.threads.map((thread: { id: string }) => thread.id)).toEqual(["t3", "t2"])
expect(body).toMatchObject({
- parentType: "forum",
- serverId: "s1",
- hasMore: true,
+ channel: { type: "forum", serverId: "s1" },
+ page: { hasMore: true },
included: {
- parentMessages: [{ id: "m3" }, { id: "m2" }],
- firstMessages: [{ channelId: "t3", content: "preview" }],
+ messages: [{ id: "m3" }, { id: "m2" }, { channelId: "t3", content: "preview" }],
tags: [{ messageId: "m3", tag: "bug" }],
- participants: [{ channelId: "t3", userId: "u1" }],
+ members: [{ channelId: "t3", userId: "u1" }],
},
})
- expect(body.nextCursor).toEqual(expect.any(String))
+ expect(body.page.nextCursor).toEqual(expect.any(String))
expect(mockListForumThreadsByCreatedAt).toHaveBeenCalledWith(expect.anything(), {
parentChannelId: "c1",
limit: 3,
@@ -292,7 +315,7 @@ describe("GET /api/community/channels/[id]/threads", () => {
mockListForumThreadsByCreatedAt.mockResolvedValue([])
const next = await GET(req(
- `http://localhost/api/community/channels/c1/threads?order=createdAt&limit=2&cursor=${encodeURIComponent(body.nextCursor)}`,
+ `http://localhost/api/community/channels/c1/threads?order=createdAt&limit=2&cursor=${encodeURIComponent(body.page.nextCursor)}`,
), ctx)
expect(next.status).toBe(200)
expect(mockListForumThreadsByCreatedAt).toHaveBeenLastCalledWith(expect.anything(), {
@@ -359,8 +382,8 @@ describe("GET /api/community/channels/[id]/threads", () => {
it("does not query created-order children when the forum access gate rejects the viewer", async () => {
mockResolveChannelAccessContext.mockResolvedValue({
- channel: { id: "c1", serverId: "s1", type: "forum" },
- anchor: { id: "c1", serverId: "s1", type: "forum" },
+ channel: parentRow({ id: "c1", serverId: "s1", type: "forum" }),
+ anchor: parentRow({ id: "c1", serverId: "s1", type: "forum" }),
role: "member",
isPrivate: true,
isCreator: false,
diff --git a/src/web/src/app/api/community/channels/[id]/threads/route.ts b/src/web/src/app/api/community/channels/[id]/threads/route.ts
index e2683c47c..2586f1737 100644
--- a/src/web/src/app/api/community/channels/[id]/threads/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/threads/route.ts
@@ -1,8 +1,8 @@
import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
-import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { FORUM_ARCHIVE_TAG, isForum, queries, MAX_FORUM_TAG_LENGTH, requestsCommunityContract, requestedCommunityContract } from "@alook/shared"
+import { FORUM_ARCHIVE_TAG, isForum, queries, MAX_FORUM_TAG_LENGTH, COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
import { writeCommunityThreadsRead } from "@/lib/community/thread-read"
import { parseBoundedInt } from "@/lib/community/messages"
@@ -15,11 +15,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
- const currentContract = requestsCommunityContract(req.headers)
- const contract = requestedCommunityContract(req.headers) === 3 ? 3 : 2
+ const contract = COMMUNITY_RESOURCE_CONTRACT_VERSION
const access = await requireMessageSurfaceAccess(db, channelId, ctx.userId)
- if (!access.ok) return writeError(currentContract ? access.error : "forbidden", currentContract ? access.status : 403)
- if (!currentContract && access.value.surface === "dm") return writeError("forbidden", 403)
+ if (!access.ok) return writeError(access.error, access.status)
const channel = access.value.surface === "channel" ? access.value.channel
: await queries.communityChannel.getChannelForMember(db, channelId, ctx.userId)
if (!channel) return writeError("not found", 404)
@@ -61,9 +59,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
if (cursor === null) return writeError("invalid cursor", 400)
const page = await readCommunityForumRows(db, channelId, { tag, cursor: cursor ?? undefined, pageSize, includes })
- if (currentContract) return writeCommunityThreadsRead(db, ctx.userId, channel, page.threads, { messages: [...page.parentMessages, ...page.firstMessages], tags: page.tags, participants: page.participants }, { hasMore: page.hasMore, nextCursor: page.nextCursor ?? null }, contract)
- return writeJSON({ serverId: channel.serverId, parentType: channel.type, threads: page.threads,
- included: { parentMessages: page.parentMessages, firstMessages: page.firstMessages.map(({ channelId, content }) => ({ channelId, content })), tags: page.tags, participants: page.participants }, hasMore: page.hasMore, ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}) })
+ return writeCommunityThreadsRead(db, ctx.userId, channel, page.threads, { messages: [...page.parentMessages, ...page.firstMessages], tags: page.tags, participants: page.participants }, { hasMore: page.hasMore, nextCursor: page.nextCursor ?? null }, contract)
} else {
threads = await queries.communityChannel.listChildChannels(db, channelId, {
@@ -112,13 +108,5 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
: Promise.resolve([]),
])
- if (currentContract) {
- return writeCommunityThreadsRead(db, ctx.userId, channel, threads, { messages: [...parentMessages, ...firstMessages], tags, participants }, { hasMore, nextCursor: nextCursor ?? null }, contract)
- }
- return writeJSON({
- serverId: channel.serverId,
- parentType: channel.type,
- threads,
- ...(order === "createdAt" || includes.size ? { included: { parentMessages, firstMessages: firstMessages.map(({ channelId, content }) => ({ channelId, content })), tags, participants }, hasMore, ...(nextCursor ? { nextCursor } : {}) } : {}),
- })
+ return writeCommunityThreadsRead(db, ctx.userId, channel, threads, { messages: [...parentMessages, ...firstMessages], tags, participants }, { hasMore, nextCursor: nextCursor ?? null }, contract)
})
diff --git a/src/web/src/app/api/community/channels/route.test.ts b/src/web/src/app/api/community/channels/route.test.ts
index b88ffbfd1..769bff3cb 100644
--- a/src/web/src/app/api/community/channels/route.test.ts
+++ b/src/web/src/app/api/community/channels/route.test.ts
@@ -1,3 +1,5 @@
+import { CommunityChannelResourceSchema } from "@alook/shared"
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -68,7 +70,7 @@ describe("POST /api/community/channels (create door — human arm)", () => {
vi.clearAllMocks()
mockCreateServerChannel.mockResolvedValue({ ok: true, value: { id: "c-new", name: "general", type: "text" } })
mockCreateDm.mockResolvedValue({ ok: true, value: { id: "dm-1" } })
- mockCreateThread.mockResolvedValue({ ok: true, value: { id: "t-1", parentMessageId: "msg-p" } })
+ mockCreateThread.mockResolvedValue({ ok: true, value: { ...channelResourceFixture({ id: "t-1", type: "thread", parentChannelId: "ch-parent", parentMessageId: "msg-p" }), archived: 0, storageOnly: "private" } })
})
it("dispatches type=text to the server-channel core, 201 {channel}", async () => {
@@ -129,6 +131,8 @@ describe("POST /api/community/channels (create door — human arm)", () => {
)
const body = await res.json()
expect(body.id).toBe("t-1")
+ expect(CommunityChannelResourceSchema.safeParse(body).success).toBe(true)
+ expect(body).not.toHaveProperty("storageOnly")
})
it("400s a thread create with no messageId (before touching the core)", async () => {
diff --git a/src/web/src/app/api/community/channels/route.ts b/src/web/src/app/api/community/channels/route.ts
index 82daa75b9..1d74fd9b8 100644
--- a/src/web/src/app/api/community/channels/route.ts
+++ b/src/web/src/app/api/community/channels/route.ts
@@ -1,3 +1,4 @@
+import { communityChannelResourceFromStorage } from "@alook/shared"
import { NextRequest } from "next/server"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
@@ -113,7 +114,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
name: body.name,
})
if (!result.ok) return writeError(result.error, result.status)
- return writeJSON(result.value, 201)
+ return writeJSON(communityChannelResourceFromStorage(result.value), 201)
}
default:
return writeError("type must be one of 'text', 'forum', 'dm', 'thread'", 400)
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 43bca6d34..7f4660423 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -52,7 +53,7 @@ const BOT = "bot_zoe"
function req(headers: Record<string, string> = { Authorization: "Bearer crk_abc" }): NextRequest {
return new NextRequest("http://localhost/api/community/friends/accepted", {
method: "GET",
- headers: { ...headers },
+ headers: { ...(headers.Authorization ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
diff --git a/src/web/src/app/api/community/friends/accepted/route.test.ts b/src/web/src/app/api/community/friends/accepted/route.test.ts
index ef626bfaf..bd7ee7f0b 100644
--- a/src/web/src/app/api/community/friends/accepted/route.test.ts
+++ b/src/web/src/app/api/community/friends/accepted/route.test.ts
@@ -1,6 +1,10 @@
+import { resourceBundleFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
+vi.mock("@/lib/community/attention-resources.server", () => ({ readCommunityResourceBundle: async (_db: unknown, viewerId: string, { profileIds }: { profileIds: string[] }) => resourceBundleFixture({ viewerId, profiles: profileIds.map(id => ({ id, name: id === "u2" ? "Gus" : "Lindsay", discriminator: id === "u2" ? "1337" : "0007", avatar: null, avatarVersion: 0, statusEmoji: id === "u2" ? "🎧" : null, statusText: id === "u2" ? "Vibing" : null })) }) }))
+
const listFriends = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -29,30 +33,32 @@ vi.mock("@/lib/middleware/auth", () => ({
import { GET } from "./route"
-const req = new NextRequest("http://localhost/api/community/friends/accepted")
+const req = new NextRequest("http://localhost/api/community/friends/accepted", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
-describe("GET /api/community/friends/accepted — human arm (inherits legacy GET /friends friends[])", () => {
+describe("GET /api/community/friends/accepted — current human relationship/profile contract", () => {
beforeEach(() => {
vi.clearAllMocks()
})
- it("includes statusEmoji/statusText sourced from the joined profile row", async () => {
+ it("publishes statusEmoji/statusText only in the full profile resource", async () => {
listFriends.mockResolvedValue([
{ id: "f1", friendUserId: "u2", friendName: "Gus", friendDiscriminator: "1337", friendImage: null, statusEmoji: "🎧", statusText: "Vibing" },
])
const res = await GET(req, {} as never)
expect(res.status).toBe(200)
- const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }
- expect(body.friends[0]).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" })
+ const body = await res.json()
+ expect(body.friends[0]).toEqual({ id: "f1", userId: "u2", sub: "" })
+ expect(body.resources.profiles[0]).toMatchObject({ id: "u2", statusEmoji: "🎧", statusText: "Vibing" })
})
- it("defaults statusEmoji/statusText for a friend with no profile row (no crash on the leftJoin)", async () => {
+ it("keeps nullable status facts in the full profile resource", async () => {
listFriends.mockResolvedValue([
{ id: "f2", friendUserId: "u3", friendName: "Lindsay", friendDiscriminator: "0007", friendImage: null, statusEmoji: null, statusText: null },
])
const res = await GET(req, {} as never)
expect(res.status).toBe(200)
- const body = await res.json() as { friends: Array<{ statusEmoji: string | null; statusText: string }> }
- expect(body.friends[0]).toMatchObject({ statusEmoji: null, statusText: "" })
+ const body = await res.json()
+ expect(body.friends[0]).toEqual({ id: "f2", userId: "u3", sub: "" })
+ expect(body.resources.profiles[0]).toMatchObject({ id: "u3", statusEmoji: null, statusText: null })
})
})
diff --git a/src/web/src/app/api/community/friends/accepted/route.ts b/src/web/src/app/api/community/friends/accepted/route.ts
index fd361855c..bfc1debe1 100644
--- a/src/web/src/app/api/community/friends/accepted/route.ts
+++ b/src/web/src/app/api/community/friends/accepted/route.ts
@@ -1,25 +1,10 @@
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextResponse, type NextRequest } from "next/server"
-import { queries, readOrStale } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityAcceptedFriendsReadSchema, type CommunityAcceptedFriendsRead, queries, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withCommunityActor } from "@/lib/middleware/community-actor"
-import { avatarInitial } from "@/lib/community/avatar"
-import { canonicalUserImage } from "@/lib/community/storage"
import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"
-/**
- * GET /api/community/friends/accepted — the accepted-friends bucket (route/disc
- * trunk, 接口树统一 轴3, folds the flat `listFriends` verb's accepted bucket).
- *
- * Dual-actor, reading the SAME `communityFriendship` status='accepted' data,
- * projected by actor.kind (Blondie #436: one source of truth so the human
- * migration off the legacy aggregate GET /friends is later byte-consistent):
- * - human → UI DTO (same shape GET /friends' `friends[]` emits today)
- * - bot → lean `FriendCard` + presence
- *
- * ①-C / users/me/* family invariant (Aigneis #426): scope is ALWAYS the caller's
- * own userId (ctx.actor.userId) — this endpoint takes NO target-user param, so a
- * bot can only ever read ITS OWN accepted friends, never probe another user's.
- */
export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
@@ -34,26 +19,15 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
return NextResponse.json({ accepted: buckets.accepted.map((r) => toFriendCard(r, onlineSet)) })
}
- // Human arm — same accepted projection GET /friends emits today (the legacy
- // aggregate stays live this step; this endpoint is the migration target).
- type FriendRow = Awaited<ReturnType<typeof queries.communityFriendship.listFriends>>[number]
- const { value, stale } = await readOrStale<{ rows: FriendRow[] }>(
- async () => ({ rows: await queries.communityFriendship.listFriends(db, userId) }),
- { rows: [] },
+ const { value } = await readOrStale<CommunityAcceptedFriendsRead>(
+ async () => {
+ const rows = await queries.communityFriendship.listFriends(db, userId)
+ const friends = rows.map(row => ({ id: row.id, userId: row.friendUserId, sub: "" }))
+ const resources = await readCommunityResourceBundle(db, userId, { channelIds: [], profileIds: friends.map(row => row.userId) })
+ return CommunityAcceptedFriendsReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, friends, resources })
+ },
+ CommunityAcceptedFriendsReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, friends: [], stale: true }),
{ route: "community/friends/accepted" },
)
- const friends = value.rows.map((f) => ({
- id: f.id,
- userId: f.friendUserId,
- name: f.friendName,
- discriminator: f.friendDiscriminator,
- avatar: canonicalUserImage(f.friendUserId, f.friendImage, f.friendAvatarVersion)
- ?? avatarInitial(f.friendName),
- avatarVersion: f.friendAvatarVersion,
- status: "offline" as const,
- sub: "",
- statusEmoji: f.statusEmoji ?? null,
- statusText: f.statusText ?? "",
- }))
- return NextResponse.json(stale ? { friends, stale: true } : { friends })
+ return NextResponse.json(value)
})
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 f82b9374e..0afe4e172 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
@@ -1,3 +1,5 @@
+import { resourceBundleFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -14,6 +16,8 @@ vi.mock("@/lib/auth", () => ({
})),
}))
+vi.mock("@/lib/community/attention-resources.server", () => ({ readCommunityResourceBundle: async (_db: unknown, viewerId: string, { profileIds }: { profileIds: string[] }) => resourceBundleFixture({ viewerId, profiles: profileIds.map(id => ({ id, name: "X", discriminator: "0042", avatar: null, avatarVersion: 0 })) }) }))
+
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
const mockGetUserInternal = vi.fn()
const mockGetBotBinding = vi.fn()
@@ -47,7 +51,7 @@ import { GET } from "./route"
function req(headers: Record<string, string> = {}): NextRequest {
return new NextRequest("http://localhost/api/community/friends/blocked", {
method: "GET",
- headers: { ...headers },
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), ...headers },
})
}
@@ -73,8 +77,9 @@ describe("GET /api/community/friends/blocked", () => {
const res = await GET(req())
expect(res.status).toBe(200)
const body = await res.json()
+ expect(body.resources.profiles).toEqual([expect.objectContaining({ id: "u_x", name: "X", avatar: null, avatarVersion: 0 })])
expect(body.blocked).toEqual([
- { id: "bk_1", userId: "u_x", name: "X", avatar: expect.any(String) },
+ { id: "bk_1", userId: "u_x" },
])
})
})
diff --git a/src/web/src/app/api/community/friends/blocked/route.ts b/src/web/src/app/api/community/friends/blocked/route.ts
index 8da81e585..60314217b 100644
--- a/src/web/src/app/api/community/friends/blocked/route.ts
+++ b/src/web/src/app/api/community/friends/blocked/route.ts
@@ -1,9 +1,8 @@
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextResponse, type NextRequest } from "next/server"
-import { queries, readOrStale } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityBlockedFriendsReadSchema, type CommunityBlockedFriendsRead, queries, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
-import { avatarInitial } from "@/lib/community/avatar"
-import { canonicalUserImage } from "@/lib/community/storage"
/**
* GET /api/community/friends/blocked — the blocked bucket (route/disc trunk,
@@ -21,19 +20,15 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
if (denied) return denied
const db = getDb(ctx.env.DB)
- type BlockedRow = Awaited<ReturnType<typeof queries.communityFriendship.listBlocked>>[number]
- const { value, stale } = await readOrStale<{ rows: BlockedRow[] }>(
- async () => ({ rows: await queries.communityFriendship.listBlocked(db, ctx.actor.userId) }),
- { rows: [] },
+ const { value } = await readOrStale<CommunityBlockedFriendsRead>(
+ async () => {
+ const rows = await queries.communityFriendship.listBlocked(db, ctx.actor.userId)
+ const blocked = rows.map(row => ({ id: row.id, userId: row.blockedUserId }))
+ const resources = await readCommunityResourceBundle(db, ctx.actor.userId, { channelIds: [], profileIds: blocked.map(row => row.userId) })
+ return CommunityBlockedFriendsReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, blocked, resources })
+ },
+ CommunityBlockedFriendsReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, blocked: [], stale: true }),
{ route: "community/friends/blocked" },
)
- const blocked = value.rows.map((b) => ({
- id: b.id,
- userId: b.blockedUserId,
- name: b.blockedName,
- avatar: canonicalUserImage(b.blockedUserId, b.blockedImage, b.blockedAvatarVersion)
- ?? avatarInitial(b.blockedName),
- avatarVersion: b.blockedAvatarVersion,
- }))
- return NextResponse.json(stale ? { blocked, stale: true } : { blocked })
+ return NextResponse.json(value)
})
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 9676e7c74..bd9aeb839 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -45,7 +46,7 @@ const BOT = "bot_zoe"
function req(headers: Record<string, string> = { Authorization: "Bearer crk_abc" }): NextRequest {
return new NextRequest("http://localhost/api/community/friends/pending", {
method: "GET",
- headers: { ...headers },
+ headers: { ...(headers.Authorization ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
diff --git a/src/web/src/app/api/community/friends/pending/route.test.ts b/src/web/src/app/api/community/friends/pending/route.test.ts
index ca8035150..e99310730 100644
--- a/src/web/src/app/api/community/friends/pending/route.test.ts
+++ b/src/web/src/app/api/community/friends/pending/route.test.ts
@@ -1,6 +1,10 @@
+import { resourceBundleFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
+vi.mock("@/lib/community/attention-resources.server", () => ({ readCommunityResourceBundle: async (_db: unknown, viewerId: string, { profileIds }: { profileIds: string[] }) => resourceBundleFixture({ viewerId, profiles: profileIds.map(id => ({ id, name: id === "u_person" ? "Ada" : "HelperBot", discriminator: "0042", avatar: null, avatarVersion: 0 })) }) }))
+
const listPending = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -33,7 +37,7 @@ vi.mock("@/lib/middleware/helpers", () => {
import { GET } from "./route"
-const req = new NextRequest("http://localhost/api/community/friends/pending")
+const req = new NextRequest("http://localhost/api/community/friends/pending", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
describe("GET /api/community/friends/pending", () => {
beforeEach(() => vi.clearAllMocks())
diff --git a/src/web/src/app/api/community/friends/pending/route.ts b/src/web/src/app/api/community/friends/pending/route.ts
index f66117769..f58e556e8 100644
--- a/src/web/src/app/api/community/friends/pending/route.ts
+++ b/src/web/src/app/api/community/friends/pending/route.ts
@@ -1,25 +1,10 @@
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextResponse, type NextRequest } from "next/server"
-import { queries, readOrStale } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityPendingFriendsReadSchema, type CommunityPendingFriendsRead, queries, readOrStale } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withCommunityActor } from "@/lib/middleware/community-actor"
-import { avatarInitial } from "@/lib/community/avatar"
-import { canonicalUserImage } from "@/lib/community/storage"
import { resolvePresence, toFriendCard } from "@/lib/community/friend-cards"
-/**
- * GET /api/community/friends/pending — the pending-requests bucket (route/disc
- * trunk, 接口树统一 轴3). Was human-only (withAuth); now dual-actor, folding the
- * flat `listFriends` verb's pendingIncoming/pendingOutgoing buckets for the bot.
- * Both arms read the SAME `communityFriendship` status='pending' data, projected
- * by actor.kind (Blondie #436 single-source-of-truth):
- * - human → the pending-page DTO (one `pending[]` with a `kind` in|out tag),
- * UNCHANGED from before this fold (byte-identical for the web client).
- * - bot → the two directional buckets `{ pendingIncoming, pendingOutgoing }`
- * as lean FriendCards + presence (the shape `alook friend list` composes).
- *
- * ①-C / users/me/* family invariant (Aigneis #426): NO target-user param — a
- * bot only ever reads its own pending set (scope = ctx.actor.userId).
- */
export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
@@ -37,24 +22,15 @@ export const GET = withCommunityActor(async (_req: NextRequest, ctx) => {
})
}
- // Human arm — byte-identical to the pre-fold human pending route.
- type PendingRow = Awaited<ReturnType<typeof queries.communityFriendship.listPending>>[number]
- const { value, stale } = await readOrStale<{ rows: PendingRow[] }>(
- async () => ({ rows: await queries.communityFriendship.listPending(db, userId) }),
- { rows: [] },
+ const { value } = await readOrStale<CommunityPendingFriendsRead>(
+ async () => {
+ const rows = await queries.communityFriendship.listPending(db, userId)
+ const pending = rows.map(row => ({ id: row.id, userId: row.userId, kind: row.kind, needsOwnerApproval: row.needsOwnerApproval }))
+ const resources = await readCommunityResourceBundle(db, userId, { channelIds: [], profileIds: pending.map(row => row.userId) })
+ return CommunityPendingFriendsReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, pending, resources })
+ },
+ CommunityPendingFriendsReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, pending: [], stale: true }),
{ route: "community/friends/pending" },
)
- // One row shape everywhere — no `source: 'bot'` tag (pass-as-human). An
- // outgoing row still gated on its owner renders a "Waiting on owner approval"
- // chip instead of a cancel affordance, keyed off `needsOwnerApproval`.
- const pending = value.rows.map((r) => ({
- id: r.id,
- userId: r.userId,
- name: r.name,
- avatar: canonicalUserImage(r.userId, r.image, r.avatarVersion) ?? avatarInitial(r.name),
- avatarVersion: r.avatarVersion,
- kind: r.kind,
- needsOwnerApproval: r.needsOwnerApproval,
- }))
- return NextResponse.json(stale ? { pending, stale: true } : { pending })
+ return NextResponse.json(value)
})
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 8739b725b..35541eba9 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -64,7 +65,7 @@ const TOKEN = "tok_abc"
function req(token: string, headers: Record<string, string> = {}): NextRequest {
return new NextRequest(`http://localhost/api/community/invites/${token}/join`, {
method: "POST",
- headers: { "content-type": "application/json", ...headers },
+ headers: { "content-type": "application/json", ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
const params = (token: string) => ({ params: Promise.resolve({ token }) })
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.test.ts b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
index afe39e8e9..cebb87dbd 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.test.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.test.ts
@@ -100,6 +100,7 @@ describe("POST /api/community/invites/[token]/join", () => {
joinedAt: "2026-07-03T00:00:00.000Z",
userName: "Alice",
userImage: null,
+ userAvatarVersion: 0, discriminator: "0042",
discriminator: "0042",
},
})
@@ -119,13 +120,16 @@ describe("POST /api/community/invites/[token]/join", () => {
joinedAt: "2026-07-03T00:00:00.000Z",
userName: "Alice",
userImage: null,
+ userAvatarVersion: 0, discriminator: "0042",
},
})
await callPOST("tok_abc")
const [, event] = mockFanOut.mock.calls[0]!
expect(event.member.name).toBe("Alice")
- expect(event.member.avatar).toBeUndefined()
+ expect(event.member.avatar).toBeNull()
+ expect(event.member.avatarVersion).toBe(0)
+ expect(event.member.discriminator).toBe("0042")
})
it("returns 400 for expired/invalid invite (useInvite → null)", async () => {
diff --git a/src/web/src/app/api/community/invites/[token]/join/route.ts b/src/web/src/app/api/community/invites/[token]/join/route.ts
index c455c9001..0b6a12cca 100644
--- a/src/web/src/app/api/community/invites/[token]/join/route.ts
+++ b/src/web/src/app/api/community/invites/[token]/join/route.ts
@@ -69,13 +69,13 @@ export const POST = withCommunityActor(async (_req, ctx) => {
member: {
id: result.member.id,
userId: result.member.userId,
- name: result.member.userName ?? "",
- discriminator: result.member.discriminator ?? undefined,
+ name: result.member.userName,
+ discriminator: result.member.discriminator,
avatar: canonicalUserImage(
result.member.userId,
result.member.userImage,
result.member.userAvatarVersion,
- ) ?? undefined,
+ ),
avatarVersion: result.member.userAvatarVersion,
role: result.member.role ?? ROLES.MEMBER,
joinedAt: result.member.joinedAt,
diff --git a/src/web/src/app/api/community/machines/route.test.ts b/src/web/src/app/api/community/machines/route.test.ts
index 9ad5c21f9..76bc95cd0 100644
--- a/src/web/src/app/api/community/machines/route.test.ts
+++ b/src/web/src/app/api/community/machines/route.test.ts
@@ -1,3 +1,4 @@
+import { machineResourceFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
@@ -42,19 +43,19 @@ describe("GET /api/community/machines — provider quota", () => {
})
it("returns the list without requesting entitlement or quota observations", async () => {
- const machines = [{ id: "machine", status: "online", availableRuntimes: [] }]
+ const machines = [machineResourceFixture({ id: "machine", status: "online", availableRuntimes: [] })]
mockListMachinesForUser.mockResolvedValue(machines)
mockListMachineBackendQuotasForUser.mockImplementation(() => new Promise(() => {}))
const response = await GET(new NextRequest("http://localhost/api/community/machines?view=list"))
expect(response.status).toBe(200)
- expect(await response.json()).toEqual({ machines })
+ expect(await response.json()).toEqual({ machines, complete: true })
expect(queries.productPlan.resolveMachinesMaxForUser).not.toHaveBeenCalled()
expect(mockListMachineBackendQuotasForUser).not.toHaveBeenCalled()
expect(mockListMachinesForUser).toHaveBeenCalledWith(expect.anything(), "u1")
})
it("keeps optional observations separate from the machine entity list", async () => {
- mockListMachinesForUser.mockResolvedValue([{ id: "machine", status: "online", availableRuntimes: [] }])
+ mockListMachinesForUser.mockResolvedValue([machineResourceFixture({ id: "machine", status: "online", availableRuntimes: [] })])
mockListMachineBackendQuotasForUser.mockResolvedValue(new Map())
const response = await GET(new NextRequest("http://localhost/api/community/machines?view=observations"))
const body = await response.json()
diff --git a/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts b/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts
index 0b3eda889..72916aaaf 100644
--- a/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/reactions/route.test.ts
@@ -116,7 +116,7 @@ describe("GET reaction details", () => {
}])
const response = await GET(request(), context)
await expect(response.json()).resolves.toMatchObject({
- actors: [{ userId: "user_1", profile: { avatar: "A" } }],
+ actors: [{ userId: "user_1", profile: { avatar: null } }],
})
})
})
diff --git a/src/web/src/app/api/community/messages/[id]/reactions/route.ts b/src/web/src/app/api/community/messages/[id]/reactions/route.ts
index fa6e6346f..1dd7d92cb 100644
--- a/src/web/src/app/api/community/messages/[id]/reactions/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/reactions/route.ts
@@ -1,10 +1,9 @@
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeError, writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries } from "@alook/shared"
+import { parseCommunityReactionDetailsRead, queries } from "@alook/shared"
import { authorizeReaction } from "@/lib/community/reaction-access"
import { canonicalUserImage } from "@/lib/community/storage"
-import { avatarInitial } from "@/lib/community/avatar"
export const GET = withCommunityActor(async (_req, ctx) => {
if (ctx.actor.kind !== "human") return writeError("human session required", 401)
@@ -20,7 +19,7 @@ export const GET = withCommunityActor(async (_req, ctx) => {
messageId,
access.scope,
)
- return writeJSON({
+ return writeJSON(parseCommunityReactionDetailsRead({
messageId,
scope: access.scope,
actors: actors.map((actor) => ({
@@ -34,10 +33,10 @@ export const GET = withCommunityActor(async (_req, ctx) => {
actor.profile.id,
actor.profile.image,
actor.profile.avatarVersion,
- ) ?? avatarInitial(actor.profile.name),
+ ),
avatarVersion: actor.profile.avatarVersion,
}
: null,
})),
- })
+ }, messageId, access.scope))
})
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 2d0d9af23..54c007b45 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
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityMessageReadSchema } from "@alook/shared"
const cloudflareMocks = vi.hoisted(() => ({
mediaDelete: vi.fn(),
@@ -58,6 +59,7 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
+ communityUserProfile: { getResourceProfiles: async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 })) },
communityChannel: {
getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
getChannelType: (...a: unknown[]) => mockGetChannelType(...a),
@@ -145,6 +147,9 @@ describe("GET /api/community/messages/[id]", () => {
it("returns the hydrated payload for a channel message when caller is a server member", async () => {
mockGetMessage.mockResolvedValue({
id: "m1",
+ seq: 7,
+ clientNonce: null,
+ authorAvatarVersion: 0,
authorId: "u-author",
authorName: "Alice",
authorImage: null,
@@ -168,7 +173,9 @@ describe("GET /api/community/messages/[id]", () => {
const res = await GET(req(), { params: { id: "m1" } } as any)
expect(res.status).toBe(200)
- const body = await res.json()
+ expect(res.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const envelope = CommunityMessageReadSchema.parse(await res.json())
+ const body = envelope.message
expect(body.id).toBe("m1")
expect(body.channelId).toBe("c1")
expect(body.content).toBe("hello")
@@ -177,7 +184,7 @@ describe("GET /api/community/messages/[id]", () => {
// id-addressed render URL (attachments fold), served by the canonical
// channels/{targetId}/attachments/{attachmentId} door.
expect(body.attachments).toEqual([
- { kind: "image", name: "photo.png", url: "/api/community/channels/c1/attachments/att_1", contentType: "image/png", sizeBytes: 12345 },
+ { id: "att_1", name: "photo.png", url: "/api/community/channels/c1/attachments/att_1", thumbnailUrl: null, contentType: "image/png", sizeBytes: 12345, width: null, height: null },
])
// Reactions came through with `me: true` since userId matches.
expect(body.reactions).toEqual([
@@ -191,6 +198,9 @@ describe("GET /api/community/messages/[id]", () => {
it("hydrates reply preview when replyToId is set + target is in the same channel", async () => {
mockGetMessage.mockResolvedValue({
id: "m1",
+ seq: 7,
+ clientNonce: null,
+ authorAvatarVersion: 0,
authorId: "u-author",
authorName: "Alice",
authorImage: null,
@@ -205,12 +215,14 @@ describe("GET /api/community/messages/[id]", () => {
})
mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
mockGetMessagesByIdsInScope.mockResolvedValue([
- { id: "m0", authorName: "Bob", content: "question?", channelId: "c1" },
+ { id: "m0", authorId: "bob", authorName: "Bob", content: "question?", channelId: "c1" },
])
const res = await GET(req(), { params: { id: "m1" } } as any)
- const body = await res.json()
- expect(body.replyTo).toEqual({ id: "m0", authorName: "Bob", text: "question?" })
+ expect(res.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const envelope = CommunityMessageReadSchema.parse(await res.json())
+ const body = envelope.message
+ expect(body.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob", text: "question?" })
const [, , scope] = mockGetMessagesByIdsInScope.mock.calls[0]
expect(scope).toEqual({ channelId: "c1" })
})
@@ -218,6 +230,9 @@ describe("GET /api/community/messages/[id]", () => {
it("omits reply preview when target is in a different channel (scope guard)", async () => {
mockGetMessage.mockResolvedValue({
id: "m1",
+ seq: 7,
+ clientNonce: null,
+ authorAvatarVersion: 0,
authorId: "u-author",
authorName: "Alice",
authorImage: null,
@@ -236,7 +251,9 @@ describe("GET /api/community/messages/[id]", () => {
mockGetMessagesByIdsInScope.mockResolvedValue([])
const res = await GET(req(), { params: { id: "m1" } } as any)
- const body = await res.json()
+ expect(res.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const envelope = CommunityMessageReadSchema.parse(await res.json())
+ const body = envelope.message
// Target not found in scope — mapper returns the `deleted` sentinel.
expect(body.replyTo).toEqual({ id: "m0", authorName: "Deleted user", text: "", deleted: true })
})
@@ -251,6 +268,9 @@ describe("GET /api/community/messages/[id]", () => {
it("returns 403 when the caller isn't a member of the channel's server", async () => {
mockGetMessage.mockResolvedValue({
id: "m1",
+ seq: 7,
+ clientNonce: null,
+ authorAvatarVersion: 0,
authorId: "u-author",
authorName: "Alice",
authorImage: null,
@@ -271,6 +291,9 @@ describe("GET /api/community/messages/[id]", () => {
it("returns the payload for a DM message when caller participates", async () => {
mockGetMessage.mockResolvedValue({
id: "m1",
+ seq: 7,
+ clientNonce: null,
+ authorAvatarVersion: 0,
authorId: "u1",
authorName: "Alice",
authorImage: null,
@@ -293,7 +316,9 @@ describe("GET /api/community/messages/[id]", () => {
const res = await GET(req(), { params: { id: "m1" } } as any)
expect(res.status).toBe(200)
- const body = await res.json()
+ expect(res.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const envelope = CommunityMessageReadSchema.parse(await res.json())
+ const body = envelope.message
expect(body.content).toBe("hi dm")
// Never touched the channel-permission path.
expect(mockGetChannelForMember).not.toHaveBeenCalled()
@@ -302,6 +327,9 @@ describe("GET /api/community/messages/[id]", () => {
it("returns 404 when the caller doesn't participate in the DM (no access-member row)", async () => {
mockGetMessage.mockResolvedValue({
id: "m1",
+ seq: 7,
+ clientNonce: null,
+ authorAvatarVersion: 0,
authorId: "u-other",
authorName: "Someone",
authorImage: null,
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 eddd6afa0..72405be06 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -16,9 +16,9 @@ import {
broadcastToUserSafe,
fanOutToServerMembers,
} from "@/lib/community/fanout"
-import { readCommunityMessageResource } from "@/lib/community/message-payload"
+import { readCommunityMessageResource, readCommunityMessageProfiles } from "@/lib/community/message-payload"
import { scheduleForumPostMediaCleanup } from "@/lib/community/forum-post-media-cleanup"
-import { CommunityMessageReadSchema, requestedCommunityContract, type CommunityContract } from "@alook/shared"
+import { CommunityMessageReadSchema, COMMUNITY_RESOURCE_CONTRACT_VERSION, type CommunityContract } from "@alook/shared"
import { writeCommunityContractJSON } from "@/lib/community/read-contract"
// A bot addresses by ref-in-query (`?ref=` + `?seq=`, the folded `resolve`
@@ -56,7 +56,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
if (ctx.actor.kind === "bot") {
return handleBotResolve(db, ctx.actor.userId, req)
}
- return handleHumanGet(db, ctx.actor.userId, ctx.params?.id, requestedCommunityContract(req.headers) ?? 1)
+ return handleHumanGet(db, ctx.actor.userId, ctx.params?.id, COMMUNITY_RESOURCE_CONTRACT_VERSION)
})
/**
@@ -179,9 +179,9 @@ async function handleHumanGet(
if (!auth.ok) return writeError(auth.error, auth.status)
}
- const payload = await readCommunityMessageResource(db, userId, message, contract === 3 ? 3 : 1)
- if (contract === 3) return writeCommunityContractJSON(CommunityMessageReadSchema.parse({ contractVersion: 3, channelId: message.channelId, message: payload }), 3)
- return writeJSON({ ...payload, channelId: message.channelId })
+ const payload = await readCommunityMessageResource(db, userId, message, contract)
+ const profiles = await readCommunityMessageProfiles(db, [payload])
+ return writeCommunityContractJSON(CommunityMessageReadSchema.parse({ contractVersion: contract, channelId: message.channelId, message: payload, profiles }), contract)
}
/**
diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
index f23b61e98..f5ad1ca66 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/route.test.ts
@@ -51,10 +51,10 @@ const ctx = { params: { id: "s1" } } as any
it("GET returns the canonical category rows for a server member", async () => {
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "member" })
- mockFindMany.mockResolvedValue([{ id: "cat1", serverId: "s1", name: "General", position: 0, private: 0 }])
+ mockFindMany.mockResolvedValue([{ id: "cat1", serverId: "s1", name: "General", position: 0, private: 0, creatorId: "u1" }])
const res = await GET(new NextRequest("http://localhost/api/community/servers/s1/categories"), ctx)
expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ categories: [{ id: "cat1", serverId: "s1", name: "General", position: 0, private: 0 }] })
+ expect(await res.json()).toEqual({ categories: [{ id: "cat1", serverId: "s1", name: "General", position: 0, private: false, creatorId: "u1" }] })
})
function postReq(body: unknown) {
@@ -74,7 +74,7 @@ describe("POST /api/community/servers/[id]/categories", () => {
})
it("creates a category", async () => {
- mockCreateCategory.mockResolvedValue({ id: "cat1", name: "General", position: 0, private: 0 })
+ mockCreateCategory.mockResolvedValue({ id: "cat1", serverId: "s1", name: "General", position: 0, private: 0, creatorId: "u1" })
const res = await POST(postReq({ name: "General" }), ctx)
expect(res.status).toBe(201)
diff --git a/src/web/src/app/api/community/servers/[id]/categories/route.ts b/src/web/src/app/api/community/servers/[id]/categories/route.ts
index 85af8a3ed..bcfc83438 100644
--- a/src/web/src/app/api/community/servers/[id]/categories/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/categories/route.ts
@@ -1,3 +1,4 @@
+import { CommunityCategoryResourceSchema } from "@alook/shared"
import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
@@ -19,7 +20,7 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
const auth = await requireServerMember(db, serverId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
const categories = await readCommunityServerCategoryRows(db, serverId)
- return writeJSON({ categories })
+ return writeJSON({ categories: categories.map(row => CommunityCategoryResourceSchema.strip().parse({ ...row, private: !!row.private })) })
})
export const POST = withAuth(async (req: NextRequest, ctx) => {
@@ -63,12 +64,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
throw err
}
- const category = {
- id: row.id,
- name: row.name,
- position: row.position ?? 0,
- private: !!row.private,
- }
+ const category = CommunityCategoryResourceSchema.strip().parse({ ...row, private: !!row.private })
await fanOutToServerMembers(serverId, {
type: WS_EVENTS.CATEGORY_CREATE,
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 52862a386..f8cc1fb0b 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -56,7 +57,7 @@ import { GET } from "./route"
function req(server: string | undefined, headers: Record<string, string> = {}): NextRequest {
const url = new URL("http://localhost/api/community/servers/resolve/channels")
if (server !== undefined) url.searchParams.set("server", server)
- return new NextRequest(url, { method: "GET", headers: { ...headers } })
+ return new NextRequest(url, { method: "GET", headers: { ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers } })
}
const ctx = { params: { id: "resolve" } } as unknown as { params: { id: string } }
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
index e718009a5..c30170f97 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
@@ -1,6 +1,10 @@
+import { BUSINESS_SCHEMA_VERSION, CommunityChannelResourceSchema, CommunityForumSidebarEnvelopeSchema } from "@alook/shared"
+import { channelResourceFixture, messageResourceFixture, serverResourceFixture, fullResourceBundleFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
+const mockReadResourceBundle = vi.fn()
+vi.mock("@/lib/community/attention-resources.server", () => ({ readCommunityResourceBundle: (...args: unknown[]) => mockReadResourceBundle(...args) }))
const mockGetMember = vi.fn()
const mockListServerChannelsForViewer = vi.fn()
const mockListParticipatingForumThreads = vi.fn()
@@ -48,33 +52,49 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
beforeEach(() => {
vi.clearAllMocks()
mockListEligibleUnreadChannels.mockResolvedValue([])
+ mockGetMessagesByIds.mockResolvedValue([])
+ mockReadResourceBundle.mockImplementation(async (_db, viewerId: string, input: { channelIds: string[]; messageIds: string[]; serverIds: string[] }) => {
+ const visible = await mockListServerChannelsForViewer()
+ const projection = await mockListParticipatingForumThreads()
+ const candidates = new Map([...visible, ...projection.canonical, ...(projection.retained ? [projection.retained] : [])].map(row => [row.id, row]))
+ const channels = input.channelIds.map(id => {
+ const row = candidates.get(id)
+ if (!row) throw new Error(`Missing explicit channel fixture ${id}`)
+ const { activityAt: _activityAt, ...channel } = row
+ return CommunityChannelResourceSchema.parse(channel)
+ })
+ const messages = await mockGetMessagesByIds()
+ return fullResourceBundleFixture(viewerId, [serverResourceFixture({ id: "server_1", ownerId: "owner", isOwner: false })], channels, messages)
+ })
})
it("returns only viewer-visible channel rows after one server membership gate", async () => {
mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
- mockListServerChannelsForViewer.mockResolvedValue([{ id: "channel_1", serverId: "server_1", name: "general" }])
+ mockListServerChannelsForViewer.mockResolvedValue([channelResourceFixture({ id: "channel_1", serverId: "server_1", name: "general" })])
const response = await GET(
new NextRequest("http://localhost/api/community/servers/server_1/channels"),
{ params: { id: "server_1" } } as never,
)
expect(response.status).toBe(200)
- expect(await response.json()).toEqual({ channels: [{ id: "channel_1", serverId: "server_1", name: "general" }] })
+ expect(await response.json()).toEqual({ channels: [channelResourceFixture({ id: "channel_1", serverId: "server_1", name: "general" })] })
expect(mockListServerChannelsForViewer).toHaveBeenCalledWith(expect.anything(), "server_1", "user_1")
})
it("reuses the scoped participant query for visible text and forum parents", async () => {
mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
mockListServerChannelsForViewer.mockResolvedValue([
- { id: "forum_visible", type: "forum" }, { id: "text_visible", type: "text" }, { id: "child", type: "thread" },
+ channelResourceFixture({ id: "forum_visible", serverId: "server_1", type: "forum" }),
+ channelResourceFixture({ id: "text_visible", serverId: "server_1", type: "text" }),
+ channelResourceFixture({ id: "child", serverId: "server_1", type: "thread", parentChannelId: "text_visible", parentMessageId: "other-opener" }),
])
- const thread = { id: "text_child", parentChannelId: "text_visible", parentMessageId: "opener", type: "thread", activityAt: "2026-08-08T11:00:00.000Z" }
+ const thread = { ...channelResourceFixture({ id: "text_child", serverId: "server_1", type: "thread", parentChannelId: "text_visible", parentMessageId: "opener" }), activityAt: "2026-08-08T11:00:00.000Z" }
mockListParticipatingForumThreads.mockResolvedValue({ canonical: [thread], retained: null, retainedDisposition: null })
- mockGetMessagesByIds.mockResolvedValue([{ id: "opener", channelId: "text_visible", content: "Text opener" }])
+ mockGetMessagesByIds.mockResolvedValue([messageResourceFixture({ id: "opener", channelId: "text_visible", content: "Text opener" })])
const response = await GET(new NextRequest("http://localhost/api/community/servers/server_1/channels?type=thread&parentType=forum,text&participating=true&activeWithin=72h&limitPerParent=5&include=parentMessage"), { params: { id: "server_1" } } as never)
expect(response.status).toBe(200)
expect(mockListParticipatingForumThreads).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ parentChannelIds: ["forum_visible", "text_visible"], userId: "user_1", limitPerParent: 5 }))
- expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["opener"], ["forum_visible", "text_visible"])
- expect(await response.json()).toMatchObject({ channels: [expect.objectContaining({ id: "text_child" })], included: { parentMessages: [{ id: "opener", channelId: "text_visible", content: "Text opener" }] } })
+ expect(mockReadResourceBundle).toHaveBeenCalledWith(expect.anything(), "user_1", { channelIds: ["forum_visible", "text_visible", "text_child"], messageIds: ["opener"], serverIds: ["server_1"] })
+ expect(CommunityForumSidebarEnvelopeSchema.parse(await response.json())).toMatchObject({ channels: [expect.objectContaining({ id: "text_child" })], resources: { messages: [expect.objectContaining({ id: "opener", channelId: "text_visible", content: "Text opener" })] } })
})
it("returns recent participating forum threads with opener messages and server-relative expiry", async () => {
@@ -82,10 +102,10 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
vi.setSystemTime(new Date("2026-08-08T12:00:00.000Z"))
mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
mockListServerChannelsForViewer.mockResolvedValue([
- { id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" },
- { id: "text_visible", serverId: "server_1", name: "General", type: "text" },
+ channelResourceFixture({ id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" }),
+ channelResourceFixture({ id: "text_visible", serverId: "server_1", name: "General", type: "text" }),
])
- const thread = {
+ const thread = { ...channelResourceFixture({ id: "thread_1", serverId: "server_1", type: "thread", parentChannelId: "forum_visible", parentMessageId: "message_1" }),
id: "thread_1",
serverId: "server_1",
parentChannelId: "forum_visible",
@@ -98,7 +118,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
retained: thread,
retainedDisposition: "eligible",
})
- mockGetMessagesByIds.mockResolvedValue([{ id: "message_1", content: "Current title" }])
+ mockGetMessagesByIds.mockResolvedValue([messageResourceFixture({ id: "message_1", channelId: "forum_visible", content: "Current title" })])
mockListEligibleUnreadChannels.mockResolvedValue([{ channelId: "thread_1" }])
try {
@@ -114,7 +134,9 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
limitPerParent: 5,
retainId: "thread_1",
})
- expect(await response.json()).toEqual({
+ expect(CommunityForumSidebarEnvelopeSchema.parse(await response.json())).toEqual({
+ schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: "server_1",
+ resources: await mockReadResourceBundle.mock.results[0]!.value,
channels: [expect.objectContaining({
id: "thread_1",
expiresAt: "2026-08-11T11:00:00.000Z",
@@ -131,24 +153,25 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
unread: true,
}),
retainedDisposition: "eligible",
- included: { parentMessages: [{ id: "message_1", content: "Current title" }] },
serverNow: "2026-08-08T12:00:00.000Z",
})
expect(mockListEligibleUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["thread_1"])
- expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["message_1"], ["forum_visible"])
+ expect(mockReadResourceBundle).toHaveBeenCalledWith(expect.anything(), "user_1", { channelIds: ["forum_visible", "thread_1"], messageIds: ["message_1"], serverIds: ["server_1"] })
+ expect((await mockReadResourceBundle.mock.results[0]!.value).messages).toMatchObject([{ id: "message_1", channelId: "forum_visible", content: "Current title" }])
} finally {
vi.useRealTimers()
}
})
- it("keeps canonical order intact and builds legacy retain order with binary comparison", async () => {
+ it("keeps canonical order intact and builds retained display order with binary comparison", async () => {
vi.useFakeTimers()
vi.setSystemTime(new Date("2026-08-08T12:00:00.000Z"))
mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
mockListServerChannelsForViewer.mockResolvedValue([
- { id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" },
+ channelResourceFixture({ id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" }),
])
const row = (id: string) => ({
+ ...channelResourceFixture({ id, serverId: "server_1", type: "thread", parentChannelId: "forum_visible", parentMessageId: `message_${id}` }),
id,
serverId: "server_1",
parentChannelId: "forum_visible",
@@ -162,9 +185,9 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
retainedDisposition: "eligible",
})
mockGetMessagesByIds.mockResolvedValue([
- { id: "message_z", content: "Z" },
- { id: "message_a", content: "A" },
- { id: "message_ä", content: "Retained" },
+ messageResourceFixture({ id: "message_z", channelId: "forum_visible", content: "Z" }),
+ messageResourceFixture({ id: "message_a", channelId: "forum_visible", content: "A" }),
+ messageResourceFixture({ id: "message_ä", channelId: "forum_visible", content: "Retained" }),
])
try {
@@ -186,7 +209,7 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
it("serializes an archived-opener retained negative without returning the child", async () => {
mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
mockListServerChannelsForViewer.mockResolvedValue([
- { id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" },
+ channelResourceFixture({ id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" }),
])
mockListParticipatingForumThreads.mockResolvedValue({
canonical: [],
@@ -206,9 +229,9 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
canonicalChannels: [],
retainedChannel: null,
retainedDisposition: "opener-archived",
- included: { parentMessages: [] },
+ resources: { messages: [] },
})
- expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), [], ["forum_visible"])
+ expect(mockReadResourceBundle).toHaveBeenCalledWith(expect.anything(), "user_1", { channelIds: ["forum_visible"], messageIds: [], serverIds: ["server_1"] })
})
it("rejects a partial or oversized sidebar query without reading child threads", async () => {
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.ts
index 49c926316..1aaa3217f 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts
@@ -1,3 +1,6 @@
+import { communityChannelResourceFromStorage } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityForumSidebarChannelSummarySchema, CommunityForumSidebarEnvelopeSchema } from "@alook/shared"
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { NextResponse, NextRequest } from "next/server"
import { supportsSidebarThreads } from "@/lib/community/forum-sidebar"
import { getDb } from "@/lib/db"
@@ -34,7 +37,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
const search = req.nextUrl.searchParams
const sidebarKeys = ["type", "parentType", "participating", "activeWithin", "limitPerParent", "retainId", "include"]
const wantsSidebarThreads = sidebarKeys.some((key) => search.has(key))
- if (!wantsSidebarThreads) return NextResponse.json({ channels: visibleChannels })
+ if (!wantsSidebarThreads) return NextResponse.json({ channels: visibleChannels.map(communityChannelResourceFromStorage) })
if (
search.get("type") !== "thread" ||
@@ -77,12 +80,12 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
const parentMessageIds = rows
.map((channel) => channel.parentMessageId)
.filter((id): id is string => !!id)
- const [parentMessages, unreadRows] = await Promise.all([
- queries.communityMessage.getMessagesByIdsInChannels(db, parentMessageIds, parentIds),
+ const [resources, unreadRows] = await Promise.all([
+ readCommunityResourceBundle(db, ctx.actor.userId, { channelIds: [...parentIds, ...rows.map(row => row.id)], messageIds: parentMessageIds, serverIds: [serverId] }),
queries.communityInbox.listEligibleUnreadChannels(db, ctx.actor.userId, rows.map((channel) => channel.id)),
])
const unreadIds = new Set(unreadRows.map((row) => row.channelId))
- const projectChannel = (channel: (typeof rows)[number]) => ({
+ const projectChannel = (channel: (typeof rows)[number]) => CommunityForumSidebarChannelSummarySchema.strip().parse({
...channel,
expiresAt: new Date(Date.parse(channel.activityAt) + windowMs).toISOString(),
unread: unreadIds.has(channel.id),
@@ -107,14 +110,14 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
compareAsciiSqliteBinary(b.id, a.id)
)
}
- return NextResponse.json({
+ return NextResponse.json(CommunityForumSidebarEnvelopeSchema.parse({
+ schemaVersion: BUSINESS_SCHEMA_VERSION, serverId, resources,
channels,
canonicalChannels,
retainedChannel,
retainedDisposition: projection.retainedDisposition,
- included: { parentMessages },
serverNow,
- })
+ }))
}
const botUserId = ctx.actor.userId
diff --git a/src/web/src/app/api/community/servers/[id]/invites/route.ts b/src/web/src/app/api/community/servers/[id]/invites/route.ts
index eecd914e7..551decbb9 100644
--- a/src/web/src/app/api/community/servers/[id]/invites/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/invites/route.ts
@@ -1,3 +1,6 @@
+import { BUSINESS_SCHEMA_VERSION, CommunityInvitesReadSchema } from "@alook/shared"
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
+import { writeCommunityContractJSON } from "@/lib/community/read-contract"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
@@ -22,8 +25,10 @@ export const GET = withAuth(async (_req, ctx) => {
const auth = await requireServerMember(db, serverId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- const invites = await queries.communityInvite.listServerInvites(db, serverId)
- return writeJSON({ invites })
+ const rows = await queries.communityInvite.listServerInvites(db, serverId)
+ const invites = rows.map(row => ({ id: row.id, token: row.token, maxUses: row.maxUses, uses: row.uses, expiresAt: row.expiresAt, createdAt: row.createdAt, creatorId: row.creatorId }))
+ const resources = await readCommunityResourceBundle(db, ctx.userId, { channelIds: [], serverIds: [serverId], profileIds: [...new Set(invites.flatMap(row => row.creatorId === null ? [] : [row.creatorId]))] })
+ return writeCommunityContractJSON(CommunityInvitesReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, serverId, invites, resources }))
})
export const POST = withAuth(async (req, ctx) => {
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 650769192..9ffd933a5 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -69,7 +70,7 @@ function req(
if (params.cursor !== undefined) url.searchParams.set("cursor", params.cursor)
return new NextRequest(url, {
method: "GET",
- headers: { ...headers },
+ headers: { ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/route.test.ts
index 72e356cb8..b452feb94 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.test.ts
@@ -59,6 +59,9 @@ function buildRow(i: number) {
userName: `User ${i}`,
userEmail: `u${i}@x.com`,
userImage: null,
+ userAvatarVersion: 0,
+ statusEmoji: null,
+ statusText: null,
discriminator: String(i).padStart(4, "0"),
}
}
@@ -173,7 +176,7 @@ describe("GET /api/community/servers/[id]/members — cursor envelope", () => {
expect(body.members.map((m) => m.discriminator)).toEqual(["0001", "0002"])
})
- it("includes statusEmoji/statusText sourced from the joined profile row, and defaults for a user with no profile row", async () => {
+ it("includes statusEmoji/statusText sourced from the joined profile row, and real NULL for a user with no profile row", async () => {
const rows = [
{ ...buildRow(1), statusEmoji: "🎧", statusText: "Vibing" },
{ ...buildRow(2), statusEmoji: null, statusText: null },
@@ -182,9 +185,9 @@ describe("GET /api/community/servers/[id]/members — cursor envelope", () => {
mockCountMembers.mockResolvedValue(2)
const res = await GET(getReq(), ctx)
- const body = await res.json() as { members: Array<{ statusEmoji: string | null; statusText: string }> }
+ const body = await res.json() as { members: Array<{ statusEmoji: string | null; statusText: string | null }> }
expect(body.members[0]).toMatchObject({ statusEmoji: "🎧", statusText: "Vibing" })
- expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: "" })
+ expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: null })
})
it("owner-scoped isBot gating: own bot exposes isBot/ownerUserId; other bots pass as humans", async () => {
@@ -221,14 +224,14 @@ describe("GET /api/community/servers/[id]/members — cursor envelope", () => {
expect(res.status).toBe(401)
})
- it("envelope key set is { members, hasMore, cursor?, limit, total }", async () => {
+ it("binds the current member page to its server and viewer", async () => {
// cursor is omitted from the JSON when hasMore=false (undefined values
// are dropped by NextResponse.json). Assert the core keys are present.
mockListMembersPaginated.mockResolvedValue({ members: [buildRow(1)], hasMore: false, cursor: undefined })
mockCountMembers.mockResolvedValue(1)
const res = await GET(getReq(), ctx)
const body = await res.json() as Record<string, unknown>
- expect(Object.keys(body).sort()).toEqual(["hasMore", "limit", "members", "total"])
+ expect(Object.keys(body).sort()).toEqual(["hasMore", "limit", "members", "serverId", "total", "viewerId"])
// When hasMore=true the cursor key IS present.
mockListMembersPaginated.mockResolvedValue({
@@ -238,6 +241,6 @@ describe("GET /api/community/servers/[id]/members — cursor envelope", () => {
})
const res2 = await GET(getReq(), ctx)
const body2 = await res2.json() as Record<string, unknown>
- expect(Object.keys(body2).sort()).toEqual(["cursor", "hasMore", "limit", "members", "total"])
+ expect(Object.keys(body2).sort()).toEqual(["cursor", "hasMore", "limit", "members", "serverId", "total", "viewerId"])
})
})
diff --git a/src/web/src/app/api/community/servers/[id]/members/route.ts b/src/web/src/app/api/community/servers/[id]/members/route.ts
index 2258cbfc5..3002f2dd0 100644
--- a/src/web/src/app/api/community/servers/[id]/members/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/route.ts
@@ -2,7 +2,7 @@ import { NextResponse, type NextRequest } from "next/server"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
- queries,
+ queries, parseCommunityServerMembersRead,
formatHandle,
parseNameAndTag,
DEFAULT_MEMBERS_PAGE_SIZE,
@@ -128,5 +128,5 @@ async function handleHumanList(
mapMemberForApi(r, userId, { botGating: true }),
)
- return writeJSON({ members, hasMore: envelope.hasMore, cursor: envelope.cursor, limit, total })
+ return writeJSON(parseCommunityServerMembersRead({ viewerId: userId, serverId, members, hasMore: envelope.hasMore, cursor: envelope.cursor, limit, total }, serverId, userId, false))
}
diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
index fccdb96bc..bc103bddc 100644
--- a/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.test.ts
@@ -59,6 +59,9 @@ function buildRow(i: number, name: string) {
userName: name,
userEmail: `${name.toLowerCase()}@x.com`,
userImage: null,
+ userAvatarVersion: 0,
+ statusEmoji: null,
+ statusText: null,
discriminator: String(i).padStart(4, "0"),
}
}
@@ -69,7 +72,7 @@ describe("GET /api/community/servers/[id]/members/search", () => {
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", serverId: "srv_1", role: "member" })
})
- it("returns matched members as a backward-compatible paginated envelope", async () => {
+ it("returns matched members as a current scoped paginated envelope", async () => {
mockSearchMembers.mockResolvedValue({
members: [buildRow(1, "Alice"), buildRow(2, "Alicia")],
hasMore: false,
@@ -99,7 +102,7 @@ describe("GET /api/community/servers/[id]/members/search", () => {
expect(body.members.map((m) => m.discriminator)).toEqual(["0001", "0002"])
})
- it("includes statusEmoji/statusText, defaulting for a user with no profile row", async () => {
+ it("includes statusEmoji/statusText, preserving NULL for a user with no profile row", async () => {
mockSearchMembers.mockResolvedValue({
members: [
{ ...buildRow(1, "Alex"), statusEmoji: "🎮", statusText: "Gaming" },
@@ -108,12 +111,12 @@ describe("GET /api/community/servers/[id]/members/search", () => {
hasMore: false,
})
const res = await GET(getReq("?q=Alex"), ctx)
- const body = await res.json() as { members: Array<{ statusEmoji: string | null; statusText: string }> }
+ const body = await res.json() as { members: Array<{ statusEmoji: string | null; statusText: string | null }> }
expect(body.members[0]).toMatchObject({ statusEmoji: "🎮", statusText: "Gaming" })
- expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: "" })
+ expect(body.members[1]).toMatchObject({ statusEmoji: null, statusText: null })
})
- it("never emits isBot/ownerUserId (no bot gating on search — byte-identical)", async () => {
+ it("never emits isBot/ownerUserId (no bot gating on search)", async () => {
// Even if a row carried bot columns, search passes them through as humans.
mockSearchMembers.mockResolvedValue({
members: [
diff --git a/src/web/src/app/api/community/servers/[id]/members/search/route.ts b/src/web/src/app/api/community/servers/[id]/members/search/route.ts
index c1fb10ca9..abda05415 100644
--- a/src/web/src/app/api/community/servers/[id]/members/search/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/members/search/route.ts
@@ -1,7 +1,7 @@
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries, MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"
+import { parseCommunityServerMembersRead, queries, MAX_MEMBERS_PAGE_SIZE } from "@alook/shared"
import { requireServerMember } from "@/lib/community/permissions"
import { parseBoundedInt } from "@/lib/community/messages"
import { mapMemberForApi } from "@/lib/community/member-payload"
@@ -49,5 +49,5 @@ export const GET = withAuth(async (req, ctx) => {
})
: undefined
- return writeJSON({ members, limit, hasMore: page.hasMore, cursor: nextCursor })
+ return writeJSON(parseCommunityServerMembersRead({ viewerId: ctx.userId, serverId, members, limit, hasMore: page.hasMore, cursor: nextCursor }, serverId, ctx.userId, true))
})
diff --git a/src/web/src/app/api/community/servers/[id]/onboard/route.ts b/src/web/src/app/api/community/servers/[id]/onboard/route.ts
index 15d567743..33761ba70 100644
--- a/src/web/src/app/api/community/servers/[id]/onboard/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/onboard/route.ts
@@ -121,7 +121,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
userId: bot.id,
name: bot.name,
discriminator: bot.discriminator,
- avatar: canonicalUserImage(bot.id, bot.image, bot.avatarVersion) ?? undefined,
+ avatar: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),
avatarVersion: bot.avatarVersion,
role: member.role ?? ROLES.MEMBER,
joinedAt: member.joinedAt,
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 a642623af..54bd73209 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -46,7 +47,7 @@ import { GET } from "./route"
function req(headers: Record<string, string> = {}): NextRequest {
return new NextRequest("http://localhost/api/community/servers/channels", {
method: "GET",
- headers: { ...headers },
+ headers: { ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
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 571437aaa..741393d67 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -60,7 +61,7 @@ import { GET } from "./route"
function req(headers: Record<string, string> = {}): NextRequest {
return new NextRequest("http://localhost/api/community/servers", {
method: "GET",
- headers: { ...headers },
+ headers: { ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
diff --git a/src/web/src/app/api/community/servers/route.test.ts b/src/web/src/app/api/community/servers/route.test.ts
index 2e536156f..af3d16cfe 100644
--- a/src/web/src/app/api/community/servers/route.test.ts
+++ b/src/web/src/app/api/community/servers/route.test.ts
@@ -65,7 +65,7 @@ describe("POST /api/community/servers", () => {
it("does not accept official status when creating a server", async () => {
createServer.mockResolvedValue({
server: { id: "srv_1", name: "New", ownerId: "u1", official: false },
- ownerMember: { id: "mem_1", userId: "u1", joinedAt, userName: "Alice" },
+ ownerMember: { id: "mem_1", userId: "u1", joinedAt, userName: "Alice", userImage: null, userAvatarVersion: 0, userDiscriminator: "0042" },
})
const res = await POST(postReq({ name: "New", official: true }))
expect(res.status).toBe(201)
@@ -74,10 +74,10 @@ describe("POST /api/community/servers", () => {
})
})
- it("fires MEMBER_JOIN with byte-identical payload sourced from createServer's ownerMember", async () => {
+ it("fires current MEMBER_JOIN identity sourced from createServer's ownerMember", async () => {
createServer.mockResolvedValue({
server: { id: "srv_1", name: "My Server", ownerId: "u1" },
- ownerMember: { id: "mem_1", userId: "u1", joinedAt, userName: "Alice" },
+ ownerMember: { id: "mem_1", userId: "u1", joinedAt, userName: "Alice", userImage: null, userAvatarVersion: 0, userDiscriminator: "0042" },
})
const res = await POST(postReq({ name: "My Server" }))
@@ -91,6 +91,7 @@ describe("POST /api/community/servers", () => {
id: "mem_1",
userId: "u1",
name: "Alice",
+ avatar: null, avatarVersion: 0, discriminator: "0042",
role: ROLES.OWNER,
joinedAt,
},
@@ -125,7 +126,7 @@ describe("POST /api/community/servers", () => {
it("normalizes a spaced name via slugify before creating the server", async () => {
createServer.mockResolvedValue({
server: { id: "srv_1", name: "My-Home", ownerId: "u1" },
- ownerMember: { id: "mem_1", userId: "u1", joinedAt, userName: "Alice" },
+ ownerMember: { id: "mem_1", userId: "u1", joinedAt, userName: "Alice", userImage: null, userAvatarVersion: 0, userDiscriminator: "0042" },
})
const res = await POST(postReq({ name: "My Home" }))
@@ -147,7 +148,7 @@ describe("POST /api/community/servers", () => {
const server = { id: "srv_x", name: "S", ownerId: "u1" }
createServer.mockResolvedValue({
server,
- ownerMember: { id: "mem_x", userId: "u1", joinedAt, userName: "Alice" },
+ ownerMember: { id: "mem_x", userId: "u1", joinedAt, userName: "Alice", userImage: null, userAvatarVersion: 0, userDiscriminator: "0042" },
})
const res = await POST(postReq({ name: "S" }))
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index 28eaaaeb2..baa3ebeda 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -124,7 +124,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
ownerMember.userId,
ownerMember.userImage,
ownerMember.userAvatarVersion,
- ) ?? undefined,
+ ),
avatarVersion: ownerMember.userAvatarVersion,
role: ROLES.OWNER,
joinedAt: ownerMember.joinedAt,
diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
index 82507f245..65af9a57c 100644
--- a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
+++ b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
@@ -46,6 +46,7 @@ describe("GET /api/community/users/[userId]/profile", () => {
name: "Gus",
discriminator: "1337",
image: null,
+ avatarVersion: 0,
aboutMe: "hi",
bannerColor: null,
statusEmoji: "🎧",
@@ -71,6 +72,7 @@ describe("GET /api/community/users/[userId]/profile", () => {
name: "Gus",
discriminator: "1337",
image: null,
+ avatarVersion: 0,
aboutMe: "hi",
bannerColor: null,
mutualServers: 1,
@@ -87,6 +89,7 @@ describe("GET /api/community/users/[userId]/profile", () => {
name: "Gus",
discriminator: "1337",
image: null,
+ avatarVersion: 0,
aboutMe: "",
bannerColor: null,
statusEmoji: null,
@@ -106,6 +109,7 @@ describe("GET /api/community/users/[userId]/profile", () => {
name: "Maia",
discriminator: "6751",
image: null,
+ avatarVersion: 0,
aboutMe: "backend",
bannerColor: null,
statusEmoji: null,
diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.ts b/src/web/src/app/api/community/users/[userId]/profile/route.ts
index 647bbc62f..81199cae5 100644
--- a/src/web/src/app/api/community/users/[userId]/profile/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/profile/route.ts
@@ -1,4 +1,4 @@
-import { queries } from "@alook/shared"
+import { parseCommunityUserCardRead, queries } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
@@ -26,7 +26,7 @@ export const GET = withAuth(async (_req, ctx) => {
const viewerSet = new Set(viewerServerIds)
const mutualServers = targetServerIds.filter((sid) => viewerSet.has(sid)).length
- return writeJSON({
+ return writeJSON(parseCommunityUserCardRead({
id: profile.id,
name: profile.name,
discriminator: profile.discriminator,
@@ -38,5 +38,5 @@ export const GET = withAuth(async (_req, ctx) => {
statusEmoji: profile.statusEmoji,
statusText: profile.statusText,
...profile.identity,
- })
+ }, id, ctx.userId))
})
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
index 87d5c8d0d..726253cb4 100644
--- 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
@@ -1,5 +1,6 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
const mocks = vi.hoisted(() => ({
snapshot: vi.fn(),
@@ -15,8 +16,12 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: {
...actual.queries,
+ communityMessage: { getMessagesByIdsInChannels: vi.fn(async () => []) },
+ communityChannel: { listReadableMessageChannelsForUser: vi.fn(async (_db: unknown, _viewer: string, ids: string[]) => ids.map(id => channelResourceFixture({ id, serverId: null, type: "dm", name: null }))), listChannelMembershipsForUserInChannels: vi.fn(async () => []) },
+ communityUserProfile: { getResourceProfiles: vi.fn(async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: id === "u2" ? "Alice" : id === "u3" ? "Bob" : "Viewer", discriminator: id === "u2" ? "0002" : id === "u3" ? "0003" : "0042", avatar: id === "u2" ? "/api/community/users/u2/avatar?v=7" : null, avatarVersion: id === "u2" ? 7 : 0 }))), getProfilesByUserIds: vi.fn(async () => []) },
+ user: { getUsersByIds: vi.fn(async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: id === "u2" ? "Alice" : id === "u3" ? "Bob" : id === "peer" ? "Peer" : "Viewer", discriminator: id === "u2" ? "0002" : id === "u3" ? "0003" : "0042", image: id === "u2" ? "/api/community/users/u2/avatar" : null, avatarVersion: id === "u2" ? 7 : 0 }))) },
communityAttention: {
- getAccountAttentionSnapshot: (...args: unknown[]) => mocks.snapshot(...args),
+ getAccountAttentionProjection: (...args: unknown[]) => mocks.snapshot(...args),
},
},
readOrStale: (operation: () => unknown) => Promise.resolve(operation()).then((value) => ({
@@ -25,6 +30,7 @@ vi.mock("@alook/shared", async () => {
})),
}
})
+vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: async (_db: unknown, channelId: string) => ({ ok: true, value: { channel: channelResourceFixture({ id: channelId, serverId: null, type: "dm", name: null }) } }) }))
vi.mock("@/lib/middleware/auth", () => ({
withAuth: (handler: any) => (request: any) => handler(request, {
env: { DB: { binding: "d1" } },
@@ -40,18 +46,17 @@ import { GET } from "./route"
describe("GET /api/community/users/me/attention", () => {
beforeEach(() => vi.clearAllMocks())
- it.each([undefined, "1", "2", "3"])("exposes exact DM counts only for the resource contract: %s", async (contract) => {
+ it("exposes exact DM counts for the sole current resource contract", async () => {
mocks.snapshot.mockResolvedValue({
scopes: [{ scopeId: "dm1", channelId: "dm1", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 5, unreadCount: 2, lastAttentionSeq: null, attentionCount: 0 }],
items: [], limit: 100, truncated: false,
included: { servers: [], channels: [], dms: [{ id: "dm1", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, lastMessageAt: "2026-10-24T00:00:00Z", lastUnreadSeq: 5 }], profiles: [{ userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 }], messages: [] },
})
- const headers = new Headers()
- if (contract) headers.set(COMMUNITY_CONTRACT_HEADER, contract)
+ const headers = new Headers({ [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) })
const response = await GET(new Request("http://localhost/api/community/users/me/attention", { headers }) as any)
const body = await response.json()
expect(response.status).toBe(200)
- expect(body.scopes[0].unreadCount).toBe(contract === "3" ? 2 : undefined)
+ expect(body.scopes[0].unreadCount).toBe(2)
})
it("uses the primary-authoritative session for the stateless snapshot", async () => {
@@ -65,14 +70,14 @@ describe("GET /api/community/users/me/attention", () => {
},
})
- const response = await GET(new Request("http://localhost/api/community/users/me/attention") as any)
+ const response = await GET(new Request("http://localhost/api/community/users/me/attention", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }) 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)
})
- it("returns the same canonical avatar contract for included DMs and profiles", async () => {
+ it("keeps named summary hints separate from canonical full avatar resources", async () => {
mocks.snapshot.mockResolvedValue({
scopes: [{
scopeId: "dm1",
@@ -117,17 +122,19 @@ describe("GET /api/community/users/me/attention", () => {
},
})
- const response = await GET(new Request("http://localhost/api/community/users/me/attention") as any)
+ const response = await GET(new Request("http://localhost/api/community/users/me/attention", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }) as any)
const body = await response.json()
- expect(body.included.dms[0].avatar).toBe("/api/community/users/u2/avatar?v=7")
+ expect(body.included.dms[0].avatar).toBe("/api/community/users/u2/avatar")
+ expect(body.resources.profiles.find((row: { id: string }) => row.id === "u2")).toMatchObject({ avatar: "/api/community/users/u2/avatar?v=7", avatarVersion: 7 })
+ expect(body.resources.profiles.find((row: { id: string }) => row.id === "u3")).toMatchObject({ avatar: null, avatarVersion: 0 })
expect(body.included.profiles).toEqual([
expect.objectContaining({
userId: "u2",
- avatar: "/api/community/users/u2/avatar?v=7",
+ avatar: "/api/community/users/u2/avatar",
avatarVersion: 7,
}),
- expect.objectContaining({ userId: "u3", avatar: "B", avatarVersion: 0 }),
+ expect.objectContaining({ userId: "u3", avatar: "", avatarVersion: 0 }),
])
})
})
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
index e58f56067..e9442553b 100644
--- a/src/web/src/app/api/community/users/me/attention/route.ts
+++ b/src/web/src/app/api/community/users/me/attention/route.ts
@@ -4,28 +4,13 @@ import {
MAX_INBOX_PAGE_SIZE,
queries,
readOrStale,
- requestedCommunityContract,
} from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
-import { avatarInitial } from "@/lib/community/avatar"
+import { hydrateAttentionResources } from "@/lib/community/attention-resources.server"
import { parseBoundedInt } from "@/lib/community/messages"
-import { canonicalUserImage } from "@/lib/community/storage"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-function canonicalizeIncludedAvatar<T extends {
- userId: string
- name: string
- avatar: string
- avatarVersion: number
-}>(row: T): T {
- return {
- ...row,
- avatar: canonicalUserImage(row.userId, row.avatar, row.avatarVersion)
- ?? avatarInitial(row.name),
- }
-}
-
export const GET = withAuth(async (request, ctx) => {
const db = getPrimaryDb(ctx.env.DB)
const url = new URL(request.url)
@@ -35,8 +20,9 @@ export const GET = withAuth(async (request, ctx) => {
MAX_INBOX_PAGE_SIZE,
)
const { value, stale } = await readOrStale(
- () => queries.communityAttention.getAccountAttentionSnapshot(db, ctx.userId, limit),
+ async () => hydrateAttentionResources(db, ctx.userId, await queries.communityAttention.getAccountAttentionProjection(db, ctx.userId, limit)),
{
+ resources: { viewerId: ctx.userId, servers: [], serverMemberships: [], channels: [], memberships: [], profiles: [], messages: [] },
scopes: [],
items: [],
limit,
@@ -51,17 +37,6 @@ export const GET = withAuth(async (request, ctx) => {
},
{ route: "community/attention" },
)
- const normalized = {
- ...value,
- scopes: requestedCommunityContract(request.headers) === 3
- ? value.scopes
- : value.scopes.map(({ unreadCount: _unreadCount, ...scope }) => scope),
- included: {
- ...value.included,
- dms: value.included.dms.map(canonicalizeIncludedAvatar),
- profiles: value.included.profiles.map(canonicalizeIncludedAvatar),
- },
- }
- if (stale) return writeJSON({ ...normalized, stale: true })
- return writeJSON(AccountAttentionSnapshotSchema.parse(normalized))
+ if (stale) return writeJSON({ ...value, stale: true })
+ return writeJSON(AccountAttentionSnapshotSchema.parse(value))
})
diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.test.ts b/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
index ffda1317e..c433f8179 100644
--- a/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
+++ b/src/web/src/app/api/community/users/me/channel-directory/route.test.ts
@@ -1,7 +1,10 @@
+import { channelResourceFixture, serverResourceFixture, fullResourceBundleFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
const listChannelRefDirectoryForUser = vi.fn()
+const readResourceBundle = vi.fn()
+vi.mock("@/lib/community/attention-resources.server", () => ({ readCommunityResourceBundle: (...args: unknown[]) => readResourceBundle(...args) }))
const db = { scoped: true }
vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => db) }))
@@ -45,13 +48,16 @@ describe("GET /api/community/users/me/channel-directory", () => {
},
]
listChannelRefDirectoryForUser.mockResolvedValue(directory)
+ const resources = fullResourceBundleFixture("viewer_1", [serverResourceFixture({ id: "server_1", name: "Studio", discriminator: "0042", ownerId: "owner", isOwner: false })], [channelResourceFixture({ id: "channel_1", serverId: "server_1", name: "general" })])
+ readResourceBundle.mockResolvedValue(resources)
const response = await GET(
new NextRequest("http://localhost/api/community/users/me/channel-directory"),
)
expect(response.status).toBe(200)
- expect(await response.json()).toEqual({ directory })
+ expect(await response.json()).toEqual({ directory, resources })
+ expect(readResourceBundle).toHaveBeenCalledExactlyOnceWith(db, "viewer_1", { serverIds: ["server_1"], channelIds: ["channel_1"] })
expect(listChannelRefDirectoryForUser).toHaveBeenCalledWith(db, "viewer_1")
expect(listChannelRefDirectoryForUser).toHaveBeenCalledTimes(1)
})
diff --git a/src/web/src/app/api/community/users/me/channel-directory/route.ts b/src/web/src/app/api/community/users/me/channel-directory/route.ts
index 99c082055..d7a216dbe 100644
--- a/src/web/src/app/api/community/users/me/channel-directory/route.ts
+++ b/src/web/src/app/api/community/users/me/channel-directory/route.ts
@@ -1,3 +1,4 @@
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { queries } from "@alook/shared"
import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
@@ -9,5 +10,6 @@ export const GET = withAuth(async (_req, ctx) => {
db,
ctx.userId,
)
- return writeJSON({ directory })
+ const resources = await readCommunityResourceBundle(db, ctx.userId, { serverIds: directory.map(row => row.id), channelIds: directory.flatMap(row => row.channels.map(channel => channel.id)) })
+ return writeJSON({ directory, resources })
})
diff --git a/src/web/src/app/api/community/users/me/dms/route.test.ts b/src/web/src/app/api/community/users/me/dms/route.test.ts
index 9a9678665..2d6f35e6c 100644
--- a/src/web/src/app/api/community/users/me/dms/route.test.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -70,6 +71,9 @@ describe("GET /api/community/users/me/dms — name projection", () => {
mockListDMs.mockResolvedValue([
{
id: "d1",
+ channel: channelResourceFixture({ id: "d1", type: "dm", serverId: null, createdAt: "2026-06-30T00:00:00.000Z", name: null }),
+ selfSource: "added", peerSource: "added",
+ otherUserAvatarVersion: 0, otherUserDiscriminator: "0001",
otherUserId: "u2",
otherUserName: "Alice",
otherUserEmail: "[email protected]",
@@ -81,11 +85,14 @@ describe("GET /api/community/users/me/dms — name projection", () => {
const res = await GET(getReq(), {} as any)
expect(res.status).toBe(200)
const body = (await res.json()) as {
- conversations: Array<{ id: string; name: string; avatar: string }>
+ conversations: Array<{ id: string; name: string; avatar: string; profile: unknown; memberships: unknown[]; channel: unknown }>
}
- expect(body.conversations[0]?.name).toBe("Alice")
- expect(body.conversations[0]?.name).not.toContain("@")
- expect(body.conversations[0]?.avatar).toBe("A")
+ expect(body.conversations[0]?.profile).toMatchObject({ name: "Alice" })
+ expect(JSON.stringify(body.conversations[0]?.profile)).not.toContain("[email protected]")
+ for (const key of ["name", "discriminator", "avatar", "avatarVersion"]) expect(body.conversations[0]).not.toHaveProperty(key)
+ expect(body.conversations[0]?.profile).toEqual({ id: "u2", name: "Alice", discriminator: "0001", avatar: null, avatarVersion: 0 })
+ expect(body.conversations[0]?.channel).toMatchObject({ id: "d1", type: "dm", serverId: null })
+ expect(body.conversations[0]?.memberships).toEqual(["u1", "u2"].map(userId => ({ channelId: "d1", userId, relation: "access", source: "added", isCreator: false, role: null, memberId: null })))
expect(body.conversations[0]).toMatchObject({
activityAt: "2026-06-30T00:00:00.000Z",
})
@@ -94,6 +101,8 @@ describe("GET /api/community/users/me/dms — name projection", () => {
it("projects canonical unread state and its sequence evidence", async () => {
mockListDMs.mockResolvedValue([{
id: "d1",
+ channel: channelResourceFixture({ id: "d1", type: "dm", serverId: null, createdAt: "2026-06-30T00:00:00.000Z", name: null }),
+ selfSource: "added", peerSource: "added",
otherUserId: "u2",
otherUserName: "Alice",
otherUserEmail: "[email protected]",
diff --git a/src/web/src/app/api/community/users/me/dms/route.ts b/src/web/src/app/api/community/users/me/dms/route.ts
index 34c31d376..11726b668 100644
--- a/src/web/src/app/api/community/users/me/dms/route.ts
+++ b/src/web/src/app/api/community/users/me/dms/route.ts
@@ -2,23 +2,9 @@ import { NextRequest } from "next/server"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { queries } from "@alook/shared"
-import { avatarInitial } from "@/lib/community/avatar"
+import { queries, parseCommunityDmsRead, CommunityResourceProfileSchema, CommunityMemberRelationSchema, communityChannelResourceFromStorage } from "@alook/shared"
import { canonicalUserImage } from "@/lib/community/storage"
-/**
- * GET /api/community/users/me/dms — the DM sidebar list, relocated from the
- * flat `GET /api/community/dm` (route/disc 接口树统一, Blondie #615/#432 terminal
- * table: RELOCATE into the users/me/* family, same class as inbox/marks/
- * server-folders — "my own" aggregate read, self-scope, no target-user param).
- * Byte-identical body to the former GET /dm handler; only the URL moved.
- *
- * DM channels carry server_id = NULL (no server to hang a `servers/{id}/…`
- * listing off), so this doesn't fit the channels/servers resource tree — it's
- * "the DM channels I'm a participant in", which is exactly the users/me/*
- * shape. POST (DM creation) already lives in the create-door (POST /channels
- * type: dm via createDmForUser) and needs no change here.
- */
export const GET = withAuth(async (_req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
const [rows, unreadRows] = await Promise.all([
@@ -30,13 +16,13 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
)
const conversations = rows.map((r) => ({
id: r.id,
+ channel: communityChannelResourceFromStorage(r.channel),
+ profile: CommunityResourceProfileSchema.parse({ id: r.otherUserId, name: r.otherUserName, discriminator: r.otherUserDiscriminator, avatar: canonicalUserImage(r.otherUserId, r.otherUserImage, r.otherUserAvatarVersion), avatarVersion: r.otherUserAvatarVersion }),
+ memberships: [
+ CommunityMemberRelationSchema.parse({ channelId: r.id, userId: ctx.userId, relation: "access", source: r.selfSource, isCreator: r.channel?.creatorId === ctx.userId, role: null, memberId: null }),
+ CommunityMemberRelationSchema.parse({ channelId: r.id, userId: r.otherUserId, relation: "access", source: r.peerSource, isCreator: r.channel?.creatorId === r.otherUserId, role: null, memberId: null }),
+ ],
userId: r.otherUserId,
- name: r.otherUserName,
- discriminator: r.otherUserDiscriminator,
- avatar: canonicalUserImage(r.otherUserId, r.otherUserImage, r.otherUserAvatarVersion)
- ?? avatarInitial(r.otherUserName),
- avatarVersion: r.otherUserAvatarVersion,
- status: "offline" as const,
preview: "",
activityAt: r.lastMessageAt ?? r.createdAt,
unread: unreadByChannelId.has(r.id),
@@ -44,5 +30,5 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {
? { lastUnreadSeq: unreadByChannelId.get(r.id) }
: {}),
}))
- return writeJSON({ conversations })
+ return writeJSON(parseCommunityDmsRead({ conversations }, ctx.userId))
})
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 967286a5e..052fc701e 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -64,7 +65,7 @@ import { POST } from "./route"
function req(body: unknown, headers: Record<string, string> = {}): NextRequest {
return new NextRequest("http://localhost/api/community/users/me/inbox/ack", {
method: "POST",
- headers: { "content-type": "application/json", ...headers },
+ headers: { "content-type": "application/json", ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
body: typeof body === "string" ? body : JSON.stringify(body),
})
}
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 bc92eb497..88273836b 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -58,7 +59,7 @@ import { POST } from "./route"
function req(body?: string, headers: Record<string, string> = {}): NextRequest {
return new NextRequest("http://localhost/api/community/users/me/inbox/pull", {
method: "POST",
- headers: { "content-type": "application/json", ...headers },
+ headers: { "content-type": "application/json", ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
...(body !== undefined ? { body } : {}),
})
}
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 0288d2a87..20fca0c1a 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -48,7 +49,7 @@ import { GET } from "./route"
function req(headers: Record<string, string> = {}): NextRequest {
return new NextRequest("http://localhost/api/community/users/me/inbox/snapshot", {
method: "GET",
- headers: { ...headers },
+ headers: { ...(new Headers(headers).has("Authorization") ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }), ...headers },
})
}
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 50b36a5dd..cc1784103 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
@@ -1,3 +1,5 @@
+import { channelResourceFixture, messageResourceFixture, serverResourceFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
@@ -7,6 +9,7 @@ const mockGetServersByIds = vi.fn()
const mockListAccessVisibleChannelIds = vi.fn()
const mockToAgentMessages = vi.fn()
const mockListByMessageIds = vi.fn()
+const mockGetMessageResources = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -26,19 +29,27 @@ vi.mock("@alook/shared", async () => {
listAccessVisibleChannelIdsForUser: (...args: unknown[]) => mockListAccessVisibleChannelIds(...args),
toAgentMessages: (...args: unknown[]) => mockToAgentMessages(...args),
},
+ communityMessage: { getMessagesByIdsInChannels: async (db: unknown, ids: string[], channels: string[]) => (await mockGetMessageResources(db, ids, channels)).filter((row: { id: string; channelId: string }) => ids.includes(row.id) && channels.includes(row.channelId)) },
+ communityReaction: { listReactionsByMessageIds: vi.fn(async () => []) },
+ communityUserProfile: { getResourceProfiles: vi.fn(async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "Alice", discriminator: "0001", avatar: null, avatarVersion: 0 }))), getProfilesByUserIds: vi.fn(async () => []) },
+ user: { getUsersByIds: vi.fn(async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: id === "u-alice" ? "Alice" : "Viewer", discriminator: "0001", image: null, avatarVersion: 0 }))) },
communityAttachment: {
listByMessageIds: (...args: unknown[]) => mockListByMessageIds(...args),
},
communityChannel: {
+ listReadableMessageChannelsForUser: vi.fn(async (_db: unknown, _viewer: string, ids: string[]) => ids.map(id => channelResourceFixture({ id, serverId: "s1", type: id === "c1" ? "thread" : "text", name: id === "c1" ? "general" : "Parent", parentChannelId: id === "c1" ? "parent1" : null, parentMessageId: id === "c1" ? "opener" : null }))),
+ listChannelMembershipsForUserInChannels: vi.fn(async () => []),
getChannelsByIds: (...args: unknown[]) => mockGetChannelsByIds(...args),
},
communityServer: {
+ listUserServers: vi.fn(async () => [{ ...serverResourceFixture({ id: "s1", ownerId: "u1" }), role: "owner", memberId: "server-member" }]),
getServersByIds: (...args: unknown[]) => mockGetServersByIds(...args),
},
},
}
})
+vi.mock("@/lib/community/permissions", () => ({ requireMessageSurfaceAccess: async (_db: unknown, id: string) => ({ ok: true, value: { channel: channelResourceFixture({ id, serverId: "s1", type: id === "c1" ? "thread" : "text", name: id === "c1" ? "general" : "Parent", parentChannelId: id === "c1" ? "parent1" : null, parentMessageId: id === "c1" ? "opener" : null }) } }) }))
vi.mock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
@@ -77,6 +88,7 @@ describe("GET /api/community/users/me/marks", () => {
mockGetServersByIds.mockResolvedValue([])
mockListAccessVisibleChannelIds.mockResolvedValue(["c1"])
mockListByMessageIds.mockResolvedValue([])
+ mockGetMessageResources.mockResolvedValue([])
mockToAgentMessages.mockResolvedValue([])
})
@@ -106,6 +118,7 @@ describe("GET /api/community/users/me/marks", () => {
author: { id: "u-alice", name: "Alice", email: "[email protected]", image: null },
},
])
+ mockGetMessageResources.mockResolvedValue([{ ...messageResourceFixture({ id: "m1", channelId: "c1", authorId: "u-alice", type: "system", seq: 42, content: "pinned thought", createdAt: "2026-06-25T09:00:00Z" }), authorName: "Alice", authorImage: null, authorAvatarVersion: 0 }])
mockGetChannelsByIds.mockResolvedValue([{
id: "c1",
name: "general",
@@ -127,8 +140,11 @@ 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", type: "system", authorId: "u-alice", authorName: "Alice", content: "pinned thought", seq: 42 },
+ m: { id: "m1" },
})
+ expect(body.resources.messages[0]).toMatchObject({ id: "m1", channelId: "c1", type: "system", authorId: "u-alice", authorName: "Alice", content: "pinned thought", seq: 42 })
+ expect(body.resources.messages[0]).not.toHaveProperty("authorEmail")
+ expect(mockGetMessageResources).toHaveBeenCalledWith({}, ["m1"], ["c1", "parent1"])
})
it("normalizes an ordinary stored message to the canonical chat wire type", async () => {
@@ -143,13 +159,15 @@ describe("GET /api/community/users/me/marks", () => {
},
author: { id: "u-alice", name: "Alice", image: null, avatarVersion: 0 },
}])
+ mockGetMessageResources.mockResolvedValue([{ ...messageResourceFixture({ id: "m-default", channelId: "c1", authorId: "u-alice", content: "hello", createdAt: "2026-06-25T09:00:00Z" }), type: "default", authorName: "Alice", authorImage: null, authorAvatarVersion: 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" })
+ expect(body.marked[0].m).toEqual({ id: "m-default" })
+ expect(body.resources.messages[0]).toMatchObject({ id: "m-default", type: "chat" })
})
it("returns empty marked array when none", async () => {
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 4f84e5795..5a618290a 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
@@ -1,3 +1,4 @@
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
@@ -9,9 +10,9 @@ import {
withD1Retry,
} from "@alook/shared"
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
@@ -115,30 +116,14 @@ export const GET = withCommunityActor(async (req, ctx) => {
return {
id: row.mark.id,
server: srv ? srv.name : "Server unavailable",
- serverId: ch?.serverId,
- channel: ch ? ch.name : "Conversation unavailable",
+ serverId: ch?.serverId ?? null,
+ channel: ch?.name ?? "Conversation",
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(
- row.author.id,
- row.author.image,
- row.author.avatarVersion,
- ) ?? avatarInitial(row.author.name),
- authorAvatarVersion: row.author.avatarVersion,
- content: row.message.content,
- // seq is the jump key (Msg.seq) — a marked message is usually outside
- // the loaded window, so a seq-less scroll silently no-ops. Lives inside
- // `m` to match the frontend `Marked` type (m: Msg).
- seq: row.message.seq,
- createdAt: row.message.createdAt,
- },
+ m: { id: row.message.id },
}
})
- return writeJSON({ marked, limit })
+ const resources = await readCommunityResourceBundle(db, userId, { channelIds: [...new Set(rows.map(row => row.mark.channelId))], messageIds: rows.map(row => row.message.id) })
+ return writeJSON({ marked, limit, resources })
})
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 bd73e20af..0e31963d1 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
@@ -91,6 +91,7 @@ describe("GET /api/community/users/me/profile", () => {
name: "Jane Roe",
discriminator: "4242",
image: "/api/community/users/u1/avatar",
+ avatarVersion: 0,
})
})
@@ -107,7 +108,7 @@ describe("GET /api/community/users/me/profile", () => {
discriminator: "4242",
name: "Jane Roe",
statusEmoji: null,
- statusText: "",
+ statusText: null,
})
})
@@ -127,21 +128,12 @@ describe("GET /api/community/users/me/profile", () => {
})
})
- it("falls back to \"0000\" when the user row is missing", async () => {
+ it("returns404 when the self user row is missing without inventing an identity", async () => {
getProfile.mockResolvedValue(null)
getUser.mockResolvedValue(null)
const res = await GET(new NextRequest("http://localhost/api/community/users/me/profile"), {} as never)
- expect(await res.json()).toEqual({
- id: "u1",
- aboutMe: "",
- avatar: "?",
- avatarVersion: 0,
- bannerColor: null,
- discriminator: "0000",
- name: "",
- statusEmoji: null,
- statusText: "",
- })
+ expect(res.status).toBe(404)
+ expect(await res.json()).toEqual({ error: "profile not found" })
})
})
@@ -172,7 +164,7 @@ describe("PATCH /api/community/users/me/profile", () => {
aboutMe: data.aboutMe ?? "",
bannerColor: data.bannerColor ?? null,
statusEmoji: data.statusEmoji ?? null,
- statusText: data.statusText ?? "",
+ statusText: data.statusText === undefined ? "" : data.statusText,
identity: id === "b1"
? { kind: "bot", ownerProfile: { id: "u1" } }
: { kind: "human" },
@@ -295,7 +287,7 @@ describe("PATCH /api/community/users/me/profile", () => {
id: "u1",
name: "Jane Roe",
discriminator: "4242",
- avatar: "J",
+ avatar: null,
avatarVersion: 0,
aboutMe: "hi",
bannerColor: "#aabbcc",
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 d53de7612..cfce024c4 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
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from "next/server"
import {
- queries,
+ queries, parseCommunitySelfProfileRead,
MAX_PROFILE_ABOUT_LENGTH,
MAX_STATUS_TEXT_LENGTH,
MAX_EMOJI_BYTES,
@@ -13,13 +13,13 @@ import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { fanOutProfileUpdate, fanOutStatusUpdate } from "@/lib/community/fanout"
import { canonicalUserImage } from "@/lib/community/storage"
-import { avatarInitial } from "@/lib/community/avatar"
import { readCommunitySelfProfile } from "@/lib/community/self-profile.server"
export const GET = withCommunityActor(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
const userId = ctx.actor.userId
- return writeJSON((await readCommunitySelfProfile(db, userId)).profile)
+ const self = await readCommunitySelfProfile(db, userId)
+ return self ? writeJSON(self.profile) : writeError("profile not found", 404)
})
export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
@@ -171,7 +171,7 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
// Normalise the response shape — same as GET — so callers don't see
// `userId` leak through on PATCH.
- const res = writeJSON({
+ const res = writeJSON(parseCommunitySelfProfileRead({
id: canonical.id,
name: canonical.name,
discriminator: canonical.discriminator,
@@ -179,13 +179,13 @@ export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
canonical.id,
canonical.image,
canonical.avatarVersion,
- ) ?? avatarInitial(canonical.name),
+ ),
avatarVersion: canonical.avatarVersion,
aboutMe: canonical.aboutMe,
bannerColor: canonical.bannerColor,
statusEmoji: canonical.statusEmoji,
statusText: canonical.statusText,
- })
+ }, userId))
// Forward the re-signed session cookies from a rename so the browser
// picks up the new name immediately — `withAuth` also forwards its own
diff --git a/src/web/src/app/api/community/users/search/route.test.ts b/src/web/src/app/api/community/users/search/route.test.ts
new file mode 100644
index 000000000..625c65118
--- /dev/null
+++ b/src/web/src/app/api/community/users/search/route.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityReadErrorSchema, CommunityUserSearchReadSchema, DEFAULT_USER_SEARCH_LIMIT, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"
+import type { AuthenticatedHandler } from "@/lib/middleware/auth"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+
+let database: ReturnType<typeof createCommunitySqliteDb>
+vi.mock("@/lib/db", () => ({ getDb: () => database.db }))
+vi.mock("@/lib/middleware/auth", async () => {
+ const { protectCommunityJsonResponse } = await import("@/lib/middleware/response-cache")
+ return { withAuth: (handler: AuthenticatedHandler) => async (request: NextRequest) => protectCommunityJsonResponse(request,
+ await handler(request, { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" })) }
+})
+import { GET } from "./route"
+
+function seed(id: string, name: string, discriminator = "0042", image: string | null = null, avatarVersion = 0, deletedAt: string | null = null) {
+ database.sqlite.prepare('INSERT INTO user (id,name,email,discriminator,image,"avatarVersion","createdAt","updatedAt","deletedAt") VALUES (?,?,?,?,?,?,?,?,?)')
+ .run(id, name, `${id}@example.test`, discriminator, image, avatarVersion, "2026-10-29T00:00:00Z", "2026-10-29T00:00:00Z", deletedAt)
+}
+async function request(query?: string) {
+ const url = new URL("http://localhost/api/community/users/search")
+ if (query !== undefined) url.searchParams.set("q", query)
+ return GET(new NextRequest(url, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }), {} as never)
+}
+async function result(query: string) {
+ const response = await request(query)
+ expect(response.status).toBe(200)
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ return CommunityUserSearchReadSchema.parse(await response.json()).users
+}
+
+beforeEach(() => { database = createCommunitySqliteDb() })
+afterEach(() => { database.sqlite.close() })
+
+describe("GET user search through the real handler and Shared SQL", () => {
+ it.each([undefined, "", " ", "a".repeat(MIN_SEARCH_LENGTH - 1), "a".repeat(MAX_SEARCH_LENGTH + 1)])("rejects an invalid query before SQL (%s)", async query => {
+ const response = await request(query)
+ expect(response.status).toBe(400)
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const error = CommunityReadErrorSchema.parse(await response.json())
+ expect(error.error.message).toContain(query === undefined || !query.trim() ? "q is required" : query.length < MIN_SEARCH_LENGTH ? "at least" : "≤")
+ expect(database.record.invocations).toBe(0)
+ })
+
+ it("accepts the minimum query length", async () => {
+ const name = "a".repeat(MIN_SEARCH_LENGTH)
+ seed("minimum", name)
+ expect(await result(name)).toMatchObject([{ id: "minimum", name, discriminator: "0042", image: null, avatarVersion: 0 }])
+ })
+
+ it("accepts the maximum query length", async () => {
+ const name = "a".repeat(MAX_SEARCH_LENGTH)
+ seed("maximum", name)
+ expect((await result(name)).map(user => user.id)).toEqual(["maximum"])
+ })
+
+ it("trims a substring query and excludes the viewer and actual deleted rows", async () => {
+ seed("viewer", "Ada")
+ seed("ada", "Ada")
+ seed("adaline", "Adaline", "0063")
+ seed("other", "Other")
+ seed("deleted", "Ada", "0081", null, 0, "2026-10-28T00:00:00Z")
+ expect(new Set((await result(" Ada ")).map(user => user.id))).toEqual(new Set(["ada", "adaline"]))
+ })
+
+ it("matches an exact name and tag rather than a name substring or another tag", async () => {
+ seed("viewer", "Ada", "0042")
+ seed("exact", "Ada", "0042")
+ seed("different-tag", "Ada", "0043")
+ seed("longer-name", "Adaline", "0042")
+ expect((await result(" Ada #0042 ")).map(user => user.id)).toEqual(["exact"])
+ })
+
+ it("limits after viewer exclusion using the existing Shared search limit", async () => {
+ seed("viewer", "Limit viewer")
+ for (let index = 0; index < DEFAULT_USER_SEARCH_LIMIT + 4; index++) seed(`user-${index}`, `Limit ${index}`)
+ const users = await result("Limit")
+ expect(users).toHaveLength(DEFAULT_USER_SEARCH_LIMIT)
+ expect(users.every(user => user.id.startsWith("user-"))).toBe(true)
+ expect(users.some(user => user.id === "viewer")).toBe(false)
+ })
+
+ it("preserves a legitimate null image and canonicalizes only owned image URLs by the actual version", async () => {
+ seed("null", "Avatar null", "0042", null, 0)
+ seed("owned", "Avatar owned", "0043", "/api/community/users/owned/avatar", 7)
+ seed("external", "Avatar external", "0044", "https://images.example.test/avatar.png", 3)
+ const users = new Map((await result("Avatar")).map(user => [user.id, user]))
+ expect(users.get("null")).toEqual({ id: "null", name: "Avatar null", discriminator: "0042", image: null, avatarVersion: 0 })
+ expect(users.get("owned")).toMatchObject({ image: "/api/community/users/owned/avatar?v=7", avatarVersion: 7 })
+ expect(users.get("external")).toMatchObject({ image: "https://images.example.test/avatar.png", avatarVersion: 3 })
+ })
+
+ it("returns the current Shared empty result when no user matches", async () => {
+ seed("other", "Other")
+ expect(await result("Absent")).toEqual([])
+ })
+})
diff --git a/src/web/src/app/api/community/users/search/route.ts b/src/web/src/app/api/community/users/search/route.ts
index bf4f772dc..59a2d577c 100644
--- a/src/web/src/app/api/community/users/search/route.ts
+++ b/src/web/src/app/api/community/users/search/route.ts
@@ -3,7 +3,7 @@ import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
- queries,
+ queries, CommunityUserSearchReadSchema,
MIN_SEARCH_LENGTH,
MAX_SEARCH_LENGTH,
DEFAULT_USER_SEARCH_LIMIT,
@@ -39,7 +39,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
limit: DEFAULT_USER_SEARCH_LIMIT,
})
- return writeJSON({
+ return writeJSON(CommunityUserSearchReadSchema.parse({
users: users.map((u) => ({
id: u.id,
name: u.name,
@@ -47,5 +47,5 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
avatarVersion: u.avatarVersion,
discriminator: u.discriminator,
})),
- })
+ }))
})
diff --git a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
index 59dc227cc..43f6ab3e2 100644
--- a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import "fake-indexeddb/auto"
import React from "react"
import { dehydrate, useIsRestoring } from "@tanstack/react-query"
@@ -60,7 +61,7 @@ it.each([null, false, true].flatMap(blockMode => (["accepted", "incoming"] as co
await act(async () => { await seedConversationEntry(registry!.queryClient, fresh) })
expect(ids).toContain("m2")
if (blocked) act(() => dispatchCommunityWsEvents([{ type: "community:friend.block", userId: "peer", ...(blockMode ? { blockedByViewer: true } : {}) }], {
- deliveryMode: "batch", contract: 2, queryClient: registry!.queryClient, communityStore: registry!.runtime.ui, wsStore: registry!.runtime.ws,
+ deliveryMode: "batch", contract: BUSINESS_SCHEMA_VERSION, queryClient: registry!.queryClient, communityStore: registry!.runtime.ui, wsStore: registry!.runtime.ws,
sub: { dmConversationId: "c1" }, viewerUserIdRef: { current: "viewer" }, matchesFocus: event => event.channelId === "c1",
}))
expect(registry!.runtime.ws.actions.isChannelAccessRevoked("c1", null)).toBe(blocked)
diff --git a/src/web/src/app/c/QueryProvider.native-entry.dom.test.tsx b/src/web/src/app/c/QueryProvider.native-entry.dom.test.tsx
index 457bb4cf1..72355c897 100644
--- a/src/web/src/app/c/QueryProvider.native-entry.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.native-entry.dom.test.tsx
@@ -1,6 +1,8 @@
+import { serverMembersReadFixture } from "@/test/community-resource-fixtures"
+import { machineResourceFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import React from "react"
-import { dehydrate, QueryClient, useIsRestoring } from "@tanstack/react-query"
+import { dehydrate, HydrationBoundary, QueryClient, useIsRestoring } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, render, screen, waitFor } from "@/test/react-dom-harness"
import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
@@ -35,8 +37,10 @@ describe("native client-entry consumers", () => {
{ diskVersion: 5, liveVersion: 8, winner: 8 },
])("preserves qualified avatar v$winner through disk restoration and live updates", async ({ diskVersion, liveVersion, winner }) => {
const initial = { id: "viewer", name: "Session viewer", email: "[email protected]", discriminator: "0042", avatar: "/avatar?v=6", avatarVersion: 6 }
- const disk = new QueryClient()
- disk.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [profileSchema.parse({ ...initial, identityComplete: true, avatar: `/avatar?v=${diskVersion}`, avatarVersion: diskVersion, aboutMe: "Cached about" })], { updatedAt: Date.now() - 10_000 })
+ const disk = new QueryClient(), bootstrap = new QueryClient()
+ bootstrap.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [profileSchema.parse({ id: initial.id, name: initial.name, discriminator: initial.discriminator, avatar: initial.avatar, avatarVersion: initial.avatarVersion })])
+ const authUser = { ...initial, name: "Auth hint", avatar: "/avatar?v=1", avatarVersion: 1 }
+ disk.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [profileSchema.parse({ id: initial.id, name: initial.name, discriminator: initial.discriminator, avatar: `/avatar?v=${diskVersion}`, avatarVersion: diskVersion, aboutMe: "Cached about" })], { updatedAt: Date.now() - 10_000 })
let release!: (value: unknown) => void
mocks.restore.mockReturnValue(new Promise(resolve => { release = resolve }))
let restoring = true
@@ -47,7 +51,7 @@ describe("native client-entry consumers", () => {
React.useLayoutEffect(() => { registry = owned; restoring = pending }, [owned, pending])
return <section><output data-testid="avatar-version">{self.avatarVersion}</output><span data-testid="profile-about">{self.aboutMe}</span><Avatar label={self.avatar} seed={self.id} /></section>
}
- const view = render(<QueryProvider userId="viewer" initialUser={initial}><CurrentUserProvider initialUser={initial}><Self /></CurrentUserProvider></QueryProvider>)
+ const view = render(<QueryProvider userId="viewer" initialUser={authUser}><HydrationBoundary state={dehydrate(bootstrap)}><CurrentUserProvider initialUser={authUser}><Self /></CurrentUserProvider></HydrationBoundary></QueryProvider>)
try {
await waitFor(() => expect(screen.getByTestId("avatar-version")).toHaveTextContent("6"))
const image = view.container.querySelector("img")
@@ -59,13 +63,13 @@ describe("native client-entry consumers", () => {
expect(view.container.querySelector("img")).toBe(image)
expect(image).toHaveAttribute("src", `/avatar?v=${winner}`)
expect(screen.getByTestId("profile-about")).toHaveTextContent("Cached about")
- } finally { release(undefined); view.unmount(); disk.clear() }
+ } finally { release(undefined); view.unmount(); disk.clear(); bootstrap.clear() }
})
it("hydrates the persisted machine list into an already mounted native query while live list waits", async () => {
const actual = await vi.importActual<typeof import("@/lib/query-persister")>("@/lib/query-persister")
const disk = new QueryClient()
- const machine = { id: "machine", hostname: "Restored host", displayName: "Computer", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "1", createdAt: "created", updatedAt: "updated", status: "online" }
- disk.setQueryData(communityKeys.machines(), { machines: [machine] }, { updatedAt: 1000 })
+ const machine = machineResourceFixture({ id: "machine", hostname: "Restored host", displayName: "Computer", osRelease: "24", daemonVersion: "1", createdAt: "created", updatedAt: "updated" })
+ disk.setQueryData(communityKeys.machines(), { machines: [machine], complete: true, observed: true, source: "network" }, { updatedAt: 1000 })
const persister = actual.createIdbPersister("viewer-machine-roundtrip")
await persister.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(disk) })
const stored = await persister.restoreClient()
@@ -86,10 +90,10 @@ describe("native client-entry consumers", () => {
await waitFor(() => expect(screen.getByTestId("machines")).toHaveTextContent("Restored host"))
expect(current.data?.machines[0].status).toBeUndefined()
expect(current.data?.machineCapacity).toBeUndefined()
- await act(async () => release({ machines: [{ ...machine, status: "offline" }] }))
+ await act(async () => release({ machines: [{ ...machine, status: "offline" }], complete: true }))
await waitFor(() => expect(current.data?.machines[0].status).toBe("offline"))
} finally {
- release({ machines: [] })
+ release({ machines: [], complete: true })
view.unmount()
await persister.removeClient()
disk.clear()
@@ -99,7 +103,7 @@ describe("native client-entry consumers", () => {
it.each([true, false])("connects real member search and popup after client entry when the directory starts ready=%s", async (serverReady) => {
const person = { id: "member-peer", userId: "peer", name: "John Doe", discriminator: "0042", avatar: "J", avatarVersion: 0, role: "member", status: "offline", sub: "" }
mocks.api.mockImplementation(async (url: string) => {
- if (url.startsWith("/api/community/servers/s1/members")) return { members: [person], hasMore: false, limit: 50, total: 1 }
+ if (url.startsWith("/api/community/servers/s1/members")) return serverMembersReadFixture("s1", [person], { search: url.includes("/members/search"), limit: 50 })
if (url === "/api/community/servers") return { servers: [] }
throw new Error(`Unexpected resource ${url}`)
})
@@ -138,7 +142,7 @@ describe("native client-entry consumers", () => {
it("releases real member and profile projections after native restore and allows mention search", async () => {
const person = { id: "member-peer", userId: "peer", name: "John Doe", discriminator: "0042", avatar: "J", avatarVersion: 0, role: "member", status: "offline", sub: "" }
mocks.api.mockImplementation(async (url: string) => {
- if (url.startsWith("/api/community/servers/s1/members")) return { members: [person], hasMore: false, limit: 50, total: 1 }
+ if (url.startsWith("/api/community/servers/s1/members")) return serverMembersReadFixture("s1", [person], { search: url.includes("/members/search"), limit: 50 })
throw new Error(`Unexpected resource ${url}`)
})
let members!: ReturnType<typeof useServerMembers>
diff --git a/src/web/src/app/c/QueryProvider.observability.dom.test.tsx b/src/web/src/app/c/QueryProvider.observability.dom.test.tsx
index faebf7e73..78c954f99 100644
--- a/src/web/src/app/c/QueryProvider.observability.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.observability.dom.test.tsx
@@ -32,7 +32,7 @@ function activate(id: string) {
}
async function seed(id: string) {
const client = new QueryClient()
- client.setQueryData(key(id), [{ id, identityComplete: true, name: "Private " + id, discriminator: "0001", avatar: "A", avatarVersion: 0 }], { updatedAt: Date.now() - 1000 })
+ client.setQueryData(key(id), [{ id, name: "Private " + id, discriminator: "0001", avatar: null, avatarVersion: 0 }], { updatedAt: Date.now() - 1000 })
await createIdbPersister(id).persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client) })
client.clear()
}
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
index 9b71a8508..d28bcaf20 100644
--- a/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.restore-order.dom.test.tsx
@@ -1,3 +1,8 @@
+import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import type { UserProfile } from "@/hooks/community/use-user-profile"
+import { serverResourceFixture, messageResourceFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
+import { canonicalChannelRow } from "@/lib/community-db/schema"
import { useToggleReactionApi } from "@/hooks/community/mutations/message-reactions"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import React from "react"
@@ -50,7 +55,7 @@ import { createCommunityDbRegistry, getCommunityDbRegistry } from "@/lib/communi
import { getCommunityRuntime, useCommunityRuntime } from "@/stores/community/runtime"
import { applyTypingIndicator } from "@/hooks/community/community-ws/typing"
import { useCommunityStore } from "@/stores/community"
-import { apiFetchProfiles } from "@/lib/community/profile-seed"
+import { apiFetchProfiles, communityUserProfilePatch } from "@/lib/community/profile-seed"
import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"
vi.mock("next/navigation", () => ({ usePathname: () => "/c/channels/server-1/post-1", useRouter: () => ({ replace: vi.fn() }) }))
vi.mock("@/hooks/community/use-servers", async (importOriginal) => ({
@@ -70,26 +75,41 @@ beforeEach(() => {
})
describe("QueryProvider persistence ordering", () => {
- it.each([0, 1_000])("preserves the original server snapshot timestamp through legacy position migration (%s)", async (updatedAt) => {
+ it.each([0, 1_000])("preserves the current complete server snapshot timestamp without migration (%s)", async (updatedAt) => {
const client = new QueryClient()
const key = communityKeys.communityDbCollection("restore-order-viewer", "servers")
- client.setQueryData(key, [{ id: "legacy-server", name: "Legacy", discriminator: "0001", description: "", ownerId: "restore-order-viewer", icon: null, official: false, isOwner: true, unread: false, mentions: 0 }], { updatedAt })
+ client.setQueryData(key, [serverResourceFixture({ id: "current-server", name: "Current", position: 7, discriminator: "0001", ownerId: "restore-order-viewer" })], { updatedAt })
const registry = createCommunityDbRegistry(client, "restore-order-viewer")
const input = readCommunityRestoredCollections({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client) }, "restore-order-viewer")
await restoreCommunityCollections(registry, input)
registry.captureRestoredCollections(input)
expect(client.getQueryState(key)?.dataUpdatedAt).toBe(updatedAt)
- expect(client.getQueryData(key)).toEqual([expect.objectContaining({ id: "legacy-server", position: 0 })])
+ expect(client.getQueryData(key)).toEqual([expect.objectContaining({ id: "current-server", position: 7 })])
expect(registry.hasRestoredCollection("servers")).toBe(true)
expect(registry.hasRestoredData()).toBe(true)
await registry.cleanup()
client.clear()
})
- it.each([false, true])("distinguishes the SSR self profile from an actual restored profile (%s)", async (hasDiskSnapshot) => {
+ it("refuses an incomplete old server row without inventing its position", async () => {
+ const seed = new QueryClient(), client = new QueryClient()
+ const { position: _position, ...old } = serverResourceFixture({ id: "old-server" })
+ const key = communityKeys.communityDbCollection("restore-order-viewer", "servers")
+ seed.setQueryData(key, [old], { updatedAt: 0 })
+ const disk = readCommunityRestoredCollections({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(seed) }, "restore-order-viewer")
+ expect(disk.servers).toBeUndefined()
+ const registry = createCommunityDbRegistry(client, "restore-order-viewer")
+ await restoreCommunityCollections(registry, disk)
+ registry.captureRestoredCollections(disk)
+ await registry.preload()
+ expect(registry.collections.servers.size).toBe(0)
+ expect(registry.hasRestoredCollection("servers")).toBe(false)
+ await registry.cleanup(); seed.clear(); client.clear()
+ })
+ it.each([false, true])("distinguishes auth-only self props from an actual restored full profile (%s)", async (hasDiskSnapshot) => {
const viewerId = "restore-order-viewer"
const profileKey = communityKeys.communityDbCollection(viewerId, "profiles")
const seed = new QueryClient()
- seed.setQueryData(profileKey, [{ id: viewerId, identityComplete: true, name: "Disk viewer", discriminator: "0001", avatar: "D", avatarVersion: 1 }], { updatedAt: Date.now() - 60_000 })
+ seed.setQueryData(profileKey, [{ id: viewerId, name: "Disk viewer", discriminator: "0001", avatar: "D", avatarVersion: 1 }], { updatedAt: Date.now() - 60_000 })
persister.restoreClient.mockResolvedValue(hasDiskSnapshot ? { buster: PERSIST_BUSTER, timestamp: Date.now(), clientState: dehydrate(seed) } : undefined)
const mark = vi.spyOn(performance, "mark")
mark.mockClear()
@@ -107,7 +127,7 @@ describe("QueryProvider persistence ordering", () => {
await waitFor(() => expect(restoring).toBe(false))
expect(registry.hasRestoredData()).toBe(hasDiskSnapshot)
expect(registry.hasRestoredCollection("profiles")).toBe(hasDiskSnapshot)
- await waitFor(() => expect(registry.collections.profiles.get(viewerId)?.name).toBe(hasDiskSnapshot ? "Disk viewer" : "SSR viewer"))
+ await waitFor(() => expect(registry.collections.profiles.get(viewerId)?.name).toBe(hasDiskSnapshot ? "Disk viewer" : undefined))
expect(mark.mock.calls.filter(([name]) => name === "alook:restore:first-cached-paint")).toHaveLength(hasDiskSnapshot ? 1 : 0)
mark.mockRestore()
renderer.unmount()
@@ -116,15 +136,7 @@ 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,
- resourceComplete: false as const,
- seq: 1,
- createdAt: "2026-09-25T00:00:00.000Z",
- content: "persisted canonical body",
- }
+ const message = messageResourceFixture({ id: "persisted-message", channelId: "persisted-dm", authorId: "peer", createdAt: "2026-09-25T00:00:00.000Z", content: "persisted canonical body" })
const canonicalKey = communityKeys.communityDbCollection(viewerId, "messages")
const seedClient = new QueryClient()
seedClient.setQueryData(
@@ -134,24 +146,7 @@ describe("QueryProvider persistence ordering", () => {
)
seedClient.setQueryData(
communityKeys.communityDbCollection(viewerId, "channels"),
- [{ topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
- id: "persisted-dm",
- resourceComplete: false,
- 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,
- }],
+ [canonicalChannelRow(channelResourceFixture({ id: "persisted-dm", type: "dm", serverId: null, name: null, creatorId: null }))],
{ updatedAt: Date.now() - 60_000 },
)
seedClient.setQueryData(
@@ -161,13 +156,13 @@ describe("QueryProvider persistence ordering", () => {
id: `persisted-dm:${viewerId}:access`,
channelId: "persisted-dm",
userId: viewerId,
- relation: "access",
+ relation: "access", source: "explicit",
},
{
id: "persisted-dm:peer:access",
channelId: "persisted-dm",
userId: "peer",
- relation: "access",
+ relation: "access", source: "explicit",
},
],
{ updatedAt: Date.now() - 60_000 },
@@ -175,7 +170,7 @@ describe("QueryProvider persistence ordering", () => {
seedClient.setQueryData(
communityKeys.communityDbCollection(viewerId, "profiles"),
[{
- identityComplete: true, id: "peer",
+ id: "peer",
name: "Persisted peer",
discriminator: "0001",
avatar: "P",
@@ -326,7 +321,14 @@ describe("QueryProvider real DbClient Strict Mode ownership", () => {
const cleanupReads: boolean[] = []
const requestOwners: Array<ReturnType<typeof getCommunityDbRegistry>> = []
const requestResults: Array<string> = []
- const fetch = vi.fn((_input: RequestInfo | URL) => Promise.resolve(new Response(JSON.stringify({ id: "strict-peer", name: "Strict response" }), { status: 200 })))
+ const fetch = vi.fn((input: RequestInfo | URL) => {
+ const path = String(input)
+ const body = path.includes("/channels/strict-route/messages?entry=1")
+ ? conversationEntryFromChannel(channelResourceFixture({ id: "strict-route", serverId: "strict-server", name: "Strict route" }), "strict-viewer")
+ : { id: "strict-peer", name: "Strict response", discriminator: "0042", image: null, avatarVersion: 0, aboutMe: "", bannerColor: null, kind: "human", mutualServers: 0, statusEmoji: null, statusText: null }
+ if (!path.includes("/channels/strict-route/messages?entry=1") && !path.includes("/users/strict-peer/profile")) throw new Error(`Unexpected strict-owner request ${path}`)
+ return Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }))
+ })
vi.stubGlobal("fetch", fetch)
let original: ReturnType<typeof getCommunityDbRegistry> = null
let client: QueryClient | null = null
@@ -350,7 +352,7 @@ describe("QueryProvider real DbClient Strict Mode ownership", () => {
runtime.ui.actions.setCurrentChannelId("strict-route")
requestOwners.push(registry)
const controller = new AbortController()
- void apiFetchProfiles<{ id: string; name: string }>("/api/community/users/strict-peer/profile", (profile) => [{ id: profile.id, identityAbout: { name: profile.name } }], { signal: controller.signal }, registry)
+ void apiFetchProfiles<UserProfile>("/api/community/users/strict-peer/profile", (profile) => [communityUserProfilePatch(profile.id, { name: profile.name, discriminator: profile.discriminator, avatar: profile.image, avatarVersion: profile.avatarVersion })], { signal: controller.signal }, registry)
.then((data) => { requestResults.push(data.name) }, (error: unknown) => { requestResults.push((error as { name: string }).name) })
return () => { controller.abort(); runtime.ui.actions.setCurrentChannelId(null) }
}, [qc, registry, runtime])
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index b87535811..fe5a325ef 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -16,9 +16,7 @@ import {
} from "@/lib/query-persister"
import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"
import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"
-import {
- communityKeys,
-} from "@/lib/query-keys"
+
import {
createCommunityDbRegistry,
registerCommunityDbRegistry,
@@ -29,10 +27,9 @@ import { useSession, currentSessionViewer } from "@/lib/auth-client"
import { useRouter } from "next/navigation"
import { usePersistedAccountLifecycle } from "@/lib/use-persisted-account-lifecycle"
import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
+import { registerBusinessSchemaOwner } from "@/lib/business-schema-lifecycle"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { discardCommunityRestoreReplacements, installCommunityDbSync, restoreCommunityCollections } from "@/lib/community-db/sync"
-import { profileSchema } from "@/lib/community-db/schema"
-import { avatarInitial } from "@/lib/community/avatar"
import type { CurrentUser } from "@/contexts/community/current-user"
import { observeHydration, discardHydration } from "@/lib/observability/restore"
import { captureTelemetryIdentityRetirement, setTelemetryUser } from "@/lib/observability/client"
@@ -109,7 +106,6 @@ export function QueryProvider(props: { children: ReactNode; userId: string | nul
function ScopedQueryProvider({
children,
userId,
- initialUser,
session,
sessionViewer,
}: {
@@ -119,19 +115,7 @@ function ScopedQueryProvider({
session: ReturnType<typeof useSession>
sessionViewer: () => string | null | undefined
}) {
- const [queryClient] = useState(() => {
- const client = createQueryClient()
- if (initialUser && initialUser.id === userId) {
- client.setQueryData(communityKeys.communityDbCollection(userId, "profiles"), [profileSchema.parse({
- id: userId, name: initialUser.name, discriminator: initialUser.discriminator || null,
- ...(initialUser.avatar === avatarInitial(initialUser.name) ? {} : { avatar: initialUser.avatar }),
- avatarVersion: initialUser.avatarVersion,
- identityComplete: !!initialUser.discriminator && initialUser.avatar !== avatarInitial(initialUser.name) && initialUser.avatarVersion !== undefined,
- aboutMe: initialUser.aboutMe, statusEmoji: initialUser.statusEmoji, statusText: initialUser.statusText,
- })], { updatedAt: 0 })
- }
- return client
- })
+ const [queryClient] = useState(createQueryClient)
const [restoreGate] = useState(createRestoreGate)
const [communityDb] = useState(() => createCommunityDbRegistry(queryClient, userId, { waitForRestore: restoreGate.ready }))
// Persister is bound to the userId at construction; on account switch the
@@ -142,6 +126,11 @@ function ScopedQueryProvider({
const active = useSelector(communityDb.runtime.lifecycle, (state) => state.active)
const router = useRouter()
useLayoutEffect(() => { communityDb.bindAuthentication(sessionViewer, persister.retireAccount, persister.retireChannels) }, [communityDb, sessionViewer, persister])
+ useLayoutEffect(() => registerBusinessSchemaOwner(async () => {
+ restoreGate.release()
+ retireCommunityAccount(communityDb)
+ await communityDb.retireDisk()
+ }), [communityDb, restoreGate])
const retireTelemetryIdentity = useRef<() => void>(() => undefined)
useLayoutEffect(() => { setTelemetryUser(userId); retireTelemetryIdentity.current = captureTelemetryIdentityRetirement() }, [userId])
const identityRetired = useRef(false)
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 079786cb8..4b65832d1 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
@@ -1,3 +1,4 @@
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
import { createElement, useLayoutEffect } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act } from "@/test/react-dom-harness"
@@ -267,7 +268,7 @@ function ServerLayout({ children }: { children?: React.ReactNode }) {
}
function render(node: React.ReactNode) {
- ingestServers(getCommunityDbRegistry(mocks.queryClient)!, { servers: mocks.servers.current.map(({ id }) => ({ id, name: id, unread: false, mentions: 0 })) })
+ ingestServers(getCommunityDbRegistry(mocks.queryClient)!, serverRailResponseFixture({ servers: mocks.servers.current.map(({ id }) => ({ id, name: id, unread: false, mentions: 0 })) }, getCommunityDbRegistry(mocks.queryClient)!.accountId))
return renderDom(node, { wrapper: ({ children }) => createElement(CommunityTestProvider, { client: mocks.queryClient, userId: "viewer-1", retainOwner: true }, children) })
}
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 fc9b46987..8f64fbb56 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
@@ -1,16 +1,16 @@
import "fake-indexeddb/auto"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import React from "react"
-import { act, render, waitFor } from "@/test/react-dom-harness"
-import { useQueryClient } from "@tanstack/react-query"
+import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"
+import { dehydrate, QueryClient, useQueryClient } from "@tanstack/react-query"
import { getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import { useCommunityWsStore } from "@/stores/community/ws"
-import { clearAllPersistedCaches } from "@/lib/query-persister"
+import { clearAllPersistedCaches, createIdbPersister, PERSIST_BUSTER } from "@/lib/query-persister"
import { communityKeys } from "@/lib/query-keys"
const fixtures = vi.hoisted(() => ({
user: { id: "user-a", name: "A", email: "[email protected]", avatar: "A" },
- fetch: vi.fn(), notifications: vi.fn(),
+ fetch: vi.fn(), notifications: vi.fn(), ws: vi.fn(), attention: vi.fn(), projectionError: false,
}))
vi.mock("@/lib/auth-client", () => ({
useSession: () => ({ data: { user: fixtures.user }, isPending: false }),
@@ -18,9 +18,20 @@ vi.mock("@/lib/auth-client", () => ({
}))
vi.mock("next/navigation", () => ({ usePathname: () => "/c/me", useRouter: () => ({ replace: vi.fn(), refresh: vi.fn() }) }))
vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
-vi.mock("@/hooks/community/use-community-ws", () => ({ useCommunityWs: vi.fn() }))
-vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSettings: fixtures.notifications }))
-vi.mock("@/hooks/community/use-account-attention", () => ({ useAccountAttention: vi.fn() }))
+vi.mock("@/hooks/community/use-community-ws", () => ({ useCommunityWs: fixtures.ws }))
+vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSettings: () => {
+ fixtures.notifications()
+ const registry = getCommunityDbRegistry(useQueryClient())!
+ registries.set(registry.accountId!, registry)
+} }))
+vi.mock("@/lib/community-db/projections", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/community-db/projections")>()
+ return { ...actual, useCanonicalProfilesProjection: (...args: Parameters<typeof actual.useCanonicalProfilesProjection>) => {
+ const result = actual.useCanonicalProfilesProjection(...args)
+ return fixtures.projectionError ? { ...result, isReady: false, isError: true } : result
+ } }
+})
+vi.mock("@/hooks/community/use-account-attention", () => ({ useAccountAttention: fixtures.attention }))
vi.mock("@/hooks/community/use-native-system-notifications", () => ({ useNativeSystemNotifications: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => fixtures.fetch(...args) }))
vi.mock("@/components/perf/perf-trace-bootstrap", () => ({ PerfTraceBootstrap: () => null }))
@@ -33,7 +44,7 @@ import { CommunityShell } from "./community-shell"
const registries = new Map<string, CommunityDbRegistry>()
const seen: Array<{ viewer: string | null; presence: string[] }> = []
const selfProfileCalls = () => fixtures.fetch.mock.calls.filter(([path]) => path === "/api/community/users/me/profile")
-const self = (id: string) => ({ id, name: "Jane Roe", discriminator: "4242", aboutMe: "hello", avatar: "new-avatar", avatarVersion: 3, statusEmoji: null, statusText: "" })
+const self = (id: string) => ({ id, name: "Jane Roe", discriminator: "4242", aboutMe: "hello", bannerColor: null, avatar: "new-avatar", avatarVersion: 3, statusEmoji: null, statusText: "" })
function Probe() {
const client = useQueryClient()
const registry = getCommunityDbRegistry(client)!
@@ -68,6 +79,9 @@ beforeEach(async () => {
throw new Error(`Unexpected bootstrap endpoint: ${path}`)
})
fixtures.notifications.mockClear()
+ fixtures.projectionError = false
+ fixtures.ws.mockClear()
+ fixtures.attention.mockClear()
registries.clear(); seen.length = 0
})
afterEach(() => { vi.unstubAllGlobals() })
@@ -140,3 +154,155 @@ describe("CommunityShell actual identity and bootstrap boundary", () => {
await waitFor(() => expect(original.queryClient.getQueryCache().getAll()).toHaveLength(0))
})
})
+
+it.each(["missing-core", "wrong-self"])("refuses a warm complete self %s before any canonical write", async defect => {
+ const { communityRegistrySnapshot } = await import("@/test/community-registry-snapshot")
+ render(tree())
+ await waitFor(() => expect(registries.get("user-a")?.collections.profiles.get("user-a")?.avatarVersion).toBe(3))
+ const registry = registries.get("user-a")!
+ const before = communityRegistrySnapshot(registry)
+ const malformed: Record<string, unknown> = { ...self("user-a"), name: "Must not publish" }
+ if (defect === "missing-core") delete malformed.avatarVersion
+ if (defect === "wrong-self") malformed.id = "foreign-self"
+ const original = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: unknown) => path === "/api/community/users/me/profile" ? Promise.resolve(malformed) : original(path, options))
+ const query = registry.queryClient.getQueryCache().find({ queryKey: communityKeys.selfProfile(), exact: true })!
+ await expect(registry.queryClient.query({ ...query.options, queryKey: communityKeys.selfProfile(), staleTime: 0 })).rejects.toThrow()
+ expect(communityRegistrySnapshot(registry)).toEqual(before)
+})
+
+
+it("mounts the first full-user consumer only after native full self publication", async () => {
+ const { useCurrentUser } = await import("@/contexts/community/current-user")
+ let release!: (value: ReturnType<typeof self>) => void
+ const held = new Promise<ReturnType<typeof self>>(resolve => { release = resolve })
+ const normal = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: unknown) => path === "/api/community/users/me/profile" ? held : normal(path, options))
+ const names: string[] = []
+ function FullUserChild() {
+ const user = useCurrentUser()
+ names.push(user.name)
+ return React.createElement("span", { "data-testid": "full-user-child" }, user.name)
+ }
+ const view = render(React.createElement(CommunityShell, { currentUser: fixtures.user }, React.createElement(FullUserChild)))
+ await waitFor(() => expect(selfProfileCalls()).toHaveLength(1))
+ expect(fixtures.notifications).toHaveBeenCalled()
+ expect(fixtures.attention).toHaveBeenCalled()
+ expect(fixtures.ws).toHaveBeenCalledWith({ viewerUserId: "user-a" })
+ await waitFor(() => expect(fixtures.fetch.mock.calls.some(([path]) => path === "/api/community/users/me/read-state")).toBe(true))
+ expect(view.queryByTestId("full-user-child")).toBeNull()
+ act(() => registries.get("user-a")!.runtime.ws.actions.setPresence("user-a", "online"))
+ expect(view.queryByTestId("full-user-child")).toBeNull()
+ await act(async () => { release(self(fixtures.user.id)) })
+ await waitFor(() => expect(view.getByTestId("full-user-child").textContent).toBe("Jane Roe"))
+ expect(names.length).toBeGreaterThan(0)
+ expect(names.every(name => name === "Jane Roe")).toBe(true)
+})
+
+it("admits required legitimate null self fields without inventing identity values", async () => {
+ const { useCurrentUser } = await import("@/contexts/community/current-user")
+ const profile = { ...self("user-a"), avatar: null, bannerColor: null, statusEmoji: null, statusText: null }
+ const normal = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: unknown) => path === "/api/community/users/me/profile" ? Promise.resolve(profile) : normal(path, options))
+ function Name() { return React.createElement("span", null, useCurrentUser().name) }
+ const view = render(React.createElement(CommunityShell, { currentUser: fixtures.user }, React.createElement(Name)))
+ await waitFor(() => expect(view.getByText("Jane Roe")).toBeDefined())
+ expect(registries.get("user-a")!.collections.profiles.get("user-a")).toMatchObject(profile)
+})
+
+it("keeps the full warm UI during held and failed background refresh", async () => {
+ const view = render(tree())
+ await waitFor(() => expect(view.getByText("content")).toBeDefined())
+ const registry = registries.get("user-a")!
+ await waitFor(() => expect(registry.queryClient.getQueryState(communityKeys.selfProfile())?.status).toBe("success"))
+ let reject!: (error: Error) => void
+ const held = new Promise((_, fail) => { reject = fail })
+ const normal = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: unknown) => path === "/api/community/users/me/profile" ? held : normal(path, options))
+ act(() => { void registry.queryClient.invalidateQueries({ queryKey: communityKeys.selfProfile() }) })
+ await waitFor(() => expect(selfProfileCalls()).toHaveLength(2))
+ expect(view.getByText("content")).toBeDefined()
+ await act(async () => { reject(new Error("background unavailable")) })
+ await waitFor(() => expect(registry.queryClient.getQueryState(communityKeys.selfProfile())?.status).toBe("error"), { timeout: 5_000 })
+ expect(view.getByText("content")).toBeDefined()
+ expect(view.queryByRole("alert")).toBeNull()
+})
+
+it("rereads a fresh cached ID if its full canonical self resource is absent", async () => {
+ const { writeCommunityCollectionRows } = await import("@/lib/community-db/write")
+ const view = render(tree())
+ await waitFor(() => expect(view.getByText("content")).toBeDefined())
+ const registry = registries.get("user-a")!
+ let release!: (value: ReturnType<typeof self>) => void
+ const held = new Promise<ReturnType<typeof self>>(resolve => { release = resolve })
+ const normal = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: unknown) => path === "/api/community/users/me/profile" ? held : normal(path, options))
+ await act(async () => { await writeCommunityCollectionRows(registry, "profiles", [], row => row.id) })
+ expect(registry.queryClient.getQueryData(communityKeys.selfProfile())).toEqual({ id: "user-a" })
+ await waitFor(() => expect(selfProfileCalls()).toHaveLength(2))
+ expect(view.queryByText("content")).toBeNull()
+ await act(async () => { release(self("user-a")) })
+ await waitFor(() => expect(view.getByText("content")).toBeDefined())
+ expect(selfProfileCalls()).toHaveLength(2)
+})
+
+it.each(["read-error", "malformed"])("offers retry without mounting missing-self UI on %s", async defect => {
+ const normal = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: unknown) => path === "/api/community/users/me/profile"
+ ? defect === "read-error" ? Promise.reject(new Error("self unavailable")) : Promise.resolve({ ...self("user-a"), avatarVersion: undefined })
+ : normal(path, options))
+ const view = render(tree())
+ await waitFor(() => expect(selfProfileCalls()).toHaveLength(2), { timeout: 5_000 })
+ const retry = await waitFor(() => view.getByRole("button", { name: "Try again" }), { timeout: 5_000 })
+ expect(view.queryByText("content")).toBeNull()
+ expect(view.getByRole("alert").textContent).toContain("Could not load your profile")
+ expect(registries.get("user-a")!.collections.profiles.get("user-a")).toBeUndefined()
+ fixtures.fetch.mockImplementation(normal)
+ fireEvent.click(retry)
+ await waitFor(() => expect(view.getByText("content")).toBeDefined())
+ expect(selfProfileCalls()).toHaveLength(3)
+})
+
+it("offers a reload exit for a reported native self projection failure", async () => {
+ fixtures.projectionError = true
+ const view = render(tree())
+ await waitFor(() => expect(registries.get("user-a")?.collections.profiles.get("user-a")?.avatarVersion).toBe(3))
+ expect(view.queryByText("content")).toBeNull()
+ const reload = vi.fn()
+ const browserWindow = window
+ vi.stubGlobal("window", new Proxy(browserWindow, { get: (target, key) => key === "location" ? { reload } : Reflect.get(target, key) }))
+ fireEvent.click(view.getByRole("button", { name: "Reload" }))
+ expect(reload).toHaveBeenCalledOnce()
+ vi.stubGlobal("window", browserWindow)
+ expect(view.getByRole("alert").textContent).toContain("Could not load your profile")
+})
+
+
+it.each([true, false])("uses restored full self immediately but waits for absent self fields (%s)", async complete => {
+ const { useCurrentUser } = await import("@/contexts/community/current-user")
+ const client = new QueryClient()
+ const profile = self("user-a")
+ client.setQueryData(communityKeys.communityDbCollection("user-a", "profiles"), complete ? [profile] : [{ id: profile.id, name: profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion }])
+ const persister = createIdbPersister("user-a")
+ await persister.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client) })
+ await waitFor(async () => expect((await persister.restoreClient())?.clientState.queries).toHaveLength(1))
+ let release!: (value: ReturnType<typeof self>) => void
+ const held = new Promise<ReturnType<typeof self>>(resolve => { release = resolve })
+ const normal = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: unknown) => path === "/api/community/users/me/profile" ? held : normal(path, options))
+ const names: string[] = []
+ function Name() {
+ const user = useCurrentUser()
+ names.push(user.name)
+ return React.createElement("span", { "data-testid": "restored-user" }, user.name)
+ }
+ const view = render(React.createElement(CommunityShell, { currentUser: fixtures.user }, React.createElement(Name)))
+ await waitFor(() => expect(selfProfileCalls()).toHaveLength(1))
+ if (complete) await waitFor(() => expect(view.getByTestId("restored-user").textContent).toBe("Jane Roe"))
+ else expect(view.queryByTestId("restored-user")).toBeNull()
+ await act(async () => { release(profile) })
+ await waitFor(() => expect(view.getByTestId("restored-user").textContent).toBe("Jane Roe"))
+ expect(names.every(name => name === "Jane Roe")).toBe(true)
+ expect(selfProfileCalls()).toHaveLength(1)
+ client.clear()
+})
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsx
index 3ecff49d4..a0dcf820d 100644
--- a/src/web/src/app/c/community-shell.tsx
+++ b/src/web/src/app/c/community-shell.tsx
@@ -1,18 +1,22 @@
"use client"
+
+import { CommunitySelfProfileReadSchema, parseCommunitySelfProfileRead } from "@alook/shared"
+import { apiFetch } from "@/lib/api/client"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
+import { useCanonicalProfilesProjection } from "@/lib/community-db/projections"
+import { Button } from "@/components/ui/button"
import { useCommunityRuntime } from "@/stores/community/runtime"
-import { useLayoutEffect, type ReactNode } from "react"
+import { useEffect, useLayoutEffect, type ReactNode } from "react"
import { usePathname } from "next/navigation"
-import { apiFetchProfiles } from "@/lib/community/profile-seed"
+import { loadAndSeedProfiles } from "@/lib/community/profile-seed"
import { QueryProvider } from "./QueryProvider"
import {
CurrentUserProvider,
- useCurrentUser,
type CurrentUser,
} from "@/contexts/community/current-user"
import { useCommunityWs } from "@/hooks/community/use-community-ws"
@@ -27,6 +31,8 @@ import { OwnerServerDeleteRouteGuard } from "@/components/community/shell/owner-
import { CommunityRestoreBoundary } from "@/components/community/shell/community-restore-bootstrap"
import { CommunitySessionPendingFrame } from "@/components/community/shell/community-session-pending-frame"
+const canonicalSelfProfileSchema = CommunitySelfProfileReadSchema.strip()
+
export function CommunityShell({
currentUser,
children,
@@ -39,7 +45,7 @@ export function CommunityShell({
<CommunityRestoreBoundary>
<ProfileAccountBoundary viewerId={currentUser.id}>
<CurrentUserProvider initialUser={currentUser}>
- <CommunityBootstrap>{children}</CommunityBootstrap>
+ <CommunityBootstrap viewerId={currentUser.id}>{children}</CommunityBootstrap>
</CurrentUserProvider>
</ProfileAccountBoundary>
</CommunityRestoreBoundary>
@@ -67,41 +73,33 @@ function ProfileAccountBoundary({
: <CommunitySessionPendingFrame pathname={pathname} />
}
-/**
- * Mounted once beneath the QueryClient + CurrentUser providers. Owns:
- * - The community WebSocket handler (`useCommunityWs`) — the module-scoped
- * Zustand stores assume a single instance for the whole session, so it lives
- * here at the tree root.
- * - The `aboutMe` hydration that used to live in the God-context's mount
- * effect — needed so the "Edit profile" dialog opens with the current value.
- */
-function CommunityBootstrap({ children }: { children: ReactNode }) {
+function CommunityBootstrap({ children, viewerId }: { children: ReactNode; viewerId: string }) {
const profileQueryClient = useQueryClient()
- const currentUser = useCurrentUser()
+ const pathname = usePathname()
useNotificationSettings()
useAccountAttention()
useAccountReadState()
- // Wire the WS handler once for the whole community subtree. `viewerUserId`
- // powers the `me` flag on incoming reactions — passing null would leave that
- // flag stuck at false for the viewer's own reactions.
- useCommunityWs({ viewerUserId: currentUser.id })
+ useCommunityWs({ viewerUserId: viewerId })
- // Hydrate the live public profile. The auth session can retain a stale image
- // after an avatar upload, while this self endpoint reads the canonical user
- // row alongside the community profile fields.
const registry = getCommunityDbRegistry(profileQueryClient)
- useQuery({
+ const projection = useCanonicalProfilesProjection([viewerId])
+ const projectedSelf = canonicalSelfProfileSchema.safeParse(projection.resourceProfiles.get(viewerId))
+ const selfReady = projection.isReady && !projection.isError && projectedSelf.success && projectedSelf.data.id === viewerId
+ const canonicalSelf = canonicalSelfProfileSchema.safeParse(registry?.collections.profiles.get(viewerId))
+ const hasCanonicalSelf = canonicalSelf.success && canonicalSelf.data.id === viewerId
+ const { isSuccess, isFetching, isError, refetch } = useQuery({
queryKey: communityKeys.selfProfile(),
queryFn: async ({ signal }) => {
- const profile = await apiFetchProfiles<{ id: string; aboutMe: string; avatar: string; avatarVersion: number; discriminator: string; name: string; statusEmoji: string | null; statusText: string }>(
- "/api/community/users/me/profile",
+ const profile = await loadAndSeedProfiles(
+ async origin => parseCommunitySelfProfileRead(await apiFetch<unknown>("/api/community/users/me/profile", { ...origin, signal }), viewerId),
(profile) => [{
id: profile.id,
identityAbout: {
name: profile.name,
discriminator: profile.discriminator,
aboutMe: profile.aboutMe,
+ bannerColor: profile.bannerColor,
},
avatar: {
avatar: profile.avatar,
@@ -111,14 +109,36 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {
statusEmoji: profile.statusEmoji,
statusText: profile.statusText,
},
- }], { signal }, registry,
+ }], registry, signal,
)
+ const published = canonicalSelfProfileSchema.parse(registry?.collections.profiles.get(viewerId))
+ if (published.id !== viewerId) throw new Error("Self profile publication mismatch")
return { id: profile.id }
},
- enabled: registry?.accountId === currentUser.id,
- staleTime: 5 * 60_000,
+ enabled: registry?.accountId === viewerId,
+ staleTime: hasCanonicalSelf ? 5 * 60_000 : 0,
})
+ useEffect(() => {
+ if (projection.isReady && !projection.isError && !hasCanonicalSelf && isSuccess && !isFetching) {
+ void refetch()
+ }
+ }, [projection.isReady, projection.isError, hasCanonicalSelf, isSuccess, isFetching, refetch])
+
+ if (!selfReady) {
+ const failed = projection.isError || isError
+ return (
+ <CommunitySessionPendingFrame pathname={pathname}>
+ {failed ? <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4 p-8" role="alert">
+ <p>Could not load your profile.</p>
+ {projection.isError
+ ? <Button className="h-11 sm:h-9" onClick={() => window.location.reload()}>Reload</Button>
+ : <Button className="h-11 sm:h-9" disabled={isFetching} onClick={() => { void refetch() }}>Try again</Button>}
+ </div> : undefined}
+ </CommunitySessionPendingFrame>
+ )
+ }
+
return (
<>
<PerfTraceBootstrap />
diff --git a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
index c9ac8ea71..1c2fa90d4 100644
--- a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
@@ -1,8 +1,10 @@
import React from "react"
-import { setupUser } from "@/test/react-dom-harness"
+import { setupUser, waitFor } from "@/test/react-dom-harness"
import { renderCommunity as render } from "@/test/community-owner-harness"
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { DmView } from "@/components/community/channels/dm-view"
+import { DmRoute } from "@/components/community/channels/dm-route"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
const {
mockDismissConversation,
@@ -16,7 +18,7 @@ const {
} = vi.hoisted(() => ({
mockDismissConversation: vi.fn(),
mockCommitRoute: vi.fn(),
- mockHistory: { allowed: true, denied: false, error: null as Error | null, retry: vi.fn(),
+ mockHistory: { real: false, allowed: true, denied: false, error: null as Error | null, retry: vi.fn(),
status: "readable", revoked: false, retryingMetadata: false, retryMetadata: vi.fn() },
mockBlocked: [] as Array<{ userId: string }>,
mockNavigationGate: { allowed: true, failed: false, retry: vi.fn() },
@@ -59,11 +61,12 @@ vi.mock("@/components/community/channels/dm-route-error-frame", () => ({
vi.mock("@/components/community/channels/conversation-resolution-error-frame", () => ({
ConversationResolutionErrorFrame: ({ onRetry }: { onRetry: () => void }) => React.createElement("button", { onClick: onRetry, "data-testid": "history-error" }, "Retry"),
}))
-vi.mock("@/hooks/community/use-channel-metadata", () => ({
- useChannelMetadata: () => ({ canRead: mockHistory.allowed, denied: mockHistory.denied,
+vi.mock("@/hooks/community/use-channel-metadata", async importOriginal => {
+ const actual=await importOriginal<typeof import("@/hooks/community/use-channel-metadata")>()
+ return {...actual,useChannelMetadata:(...args:Parameters<typeof actual.useChannelMetadata>)=>mockHistory.real ? actual.useChannelMetadata(...args) : ({ canRead: mockHistory.allowed, denied: mockHistory.denied,
status: mockHistory.status, revoked: mockHistory.revoked, retry: mockHistory.retryMetadata, retrying: mockHistory.retryingMetadata,
- data: { readProof: mockHistory.allowed ? {} : undefined } }),
-}))
+ data: { readProof: mockHistory.allowed ? {} : undefined } })}
+})
vi.mock("@/hooks/community/channel-metadata", () => ({ isChannelMetadataTokenCurrent: () => true }))
vi.mock("@/lib/community/last-community-route", () => ({ commitCommunityChannelRoute: mockCommitRoute }))
vi.mock("@/components/community/avatar", () => ({ Avatar: () => null }))
@@ -161,7 +164,7 @@ vi.mock("@alook/shared", async (importOriginal) => ({
vi.mock("@/hooks/community/use-notification-settings", () => ({
useNotificationSettings: () => ({ channel: {} }),
}))
-vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))
+vi.mock("@/lib/api/client", async importOriginal => ({...await importOriginal<typeof import("@/lib/api/client")>(), toastApiError:vi.fn()}))
vi.mock("@/lib/community-db/projections", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/projections")>(),
useCanonicalProfilesByUserId: () => new Map(),
}))
@@ -170,8 +173,10 @@ vi.mock("@/hooks/community/use-native-system-notifications", () => ({
mockDismissConversation(...args),
}))
+afterEach(()=>vi.unstubAllGlobals())
describe("DM notification dismissal readiness", () => {
beforeEach(() => {
+ mockHistory.real=false
mockDismissConversation.mockClear()
mockCommitRoute.mockClear()
mockDmMessages.navigationBlocked = false
@@ -321,3 +326,26 @@ describe("DM notification dismissal readiness", () => {
expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith("viewer_1", { kind: "dm", channelId: "dm_1" }, false)
})
})
+
+it.each([false,true])("presents current peerless denial before directory loading=%s without read or composer readiness",loading=>{
+ mockHistory.real=false;mockHistory.allowed=false;mockHistory.denied=true;mockHistory.revoked=true;mockHistory.status="denied";mockHistory.error=null
+ mockDmMessages.navigationBlocked=true;mockDms.dms=[];mockDms.isLoading=loading;mockBlocked.length=0
+ const view=render(React.createElement(DmView,{dmId:"dm_1"}))
+ expect(view.container.querySelector('[role="alert"]')?.textContent).toBe("You can no longer read this conversation.")
+ for(const id of ["dm-loading","dm-error","history-body","composer","composer-pending"]) expect(view.container.querySelector(`[data-testid="${id}"]`)).toBeNull()
+})
+it("reaches the actual peerless denial through real HTTP metadata and DmRoute without read PUT or notification readiness",async()=>{
+ mockHistory.real=true;mockDms.dms=[];mockDms.isLoading=false;mockBlocked.length=0;mockDmMessages.navigationBlocked=true
+ mockDismissConversation.mockClear();mockCommitRoute.mockClear()
+ const fetch=vi.fn(async()=>new Response(JSON.stringify({contractVersion:BUSINESS_SCHEMA_VERSION,error:{code:"blocked",message:"blocked",retryable:false}}),{status:403,headers:{"content-type":"application/json",[COMMUNITY_CONTRACT_HEADER]:String(BUSINESS_SCHEMA_VERSION)}}))
+ vi.stubGlobal("fetch",fetch)
+ const view=render(React.createElement(DmRoute,{dmId:"dm_1"}))
+ try {
+ await waitFor(()=>expect(view.container.querySelector('[role="alert"]')?.textContent).toBe("You can no longer read this conversation."))
+ for(const id of ["dm-loading","dm-error","history-body","composer","composer-pending"]) expect(view.container.querySelector(`[data-testid="${id}"]`)).toBeNull()
+ expect(mockCommitRoute).not.toHaveBeenCalled()
+ expect(mockDismissConversation.mock.calls.some(([, ,ready])=>ready===true)).toBe(false)
+ expect(fetch.mock.calls.length).toBeGreaterThan(0)
+ expect(fetch.mock.calls.every(([,options])=>!options?.method || options.method==="GET")).toBe(true)
+ } finally {view.unmount();mockHistory.real=false}
+})
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 30888843b..5a49d3d67 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
@@ -1,3 +1,4 @@
+import { attentionSnapshotScenarioFixture } from "@/test/community-resource-fixtures"
import { createElement } from "react"
import type { QueryClient } from "@tanstack/react-query"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
@@ -254,10 +255,10 @@ describe("MeLayout route memory", () => {
servers: [],
dms: [],
})
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, attentionSnapshotScenarioFixture({
scopes: [], items: [{ id: `friend_request:${request.id}`, kind: "friend_request", sourceId: request.id, scopeId: null, messageId: null, actorUserId: request.userId, createdAt: "2026-09-12T00:00:00.000Z" }],
included: { servers: [], channels: [], dms: [], messages: [], profiles: [{ userId: request.userId, name: request.name, discriminator: "0001", avatar: request.avatar, avatarVersion: 1 }] }, limit: 100, truncated: false,
- })
+ }, "viewer-1"))
publishCommunityFriendDecision(queryClient, request.id, "reject", { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined })
const rendered = renderLayout(queryClient)
diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsx
index 82989bb68..15f31c525 100644
--- a/src/web/src/app/layout.tsx
+++ b/src/web/src/app/layout.tsx
@@ -11,6 +11,7 @@ import { ThemeColorSync } from "@/components/theme-color-sync";
import { ServiceWorkerRegistration } from "@/components/service-worker-registration";
import { siteMetadata, siteStructuredData, siteViewport } from "@/lib/seo/site-metadata";
import { communityShellLayoutBootstrapScript } from "@/components/community/shell/shell-frame-geometry";
+import { businessDocumentVersionBootstrapScript } from "@/lib/service-worker/business-upgrade";
import { caveat, dmMono, dmSans, instrumentSerif, literata, vt323 } from "./fonts";
import "./globals.css";
@@ -29,6 +30,7 @@ export default function RootLayout({
suppressHydrationWarning
>
<head>
+ <script dangerouslySetInnerHTML={{ __html: businessDocumentVersionBootstrapScript }} />
<script dangerouslySetInnerHTML={{ __html: communityShellLayoutBootstrapScript }} />
<link rel="manifest" href="/manifest.json" />
<meta name="mobile-web-app-capable" content="yes" />
diff --git a/src/web/src/app/sw.test.ts b/src/web/src/app/sw.test.ts
index ae46861b1..b80a29ee2 100644
--- a/src/web/src/app/sw.test.ts
+++ b/src/web/src/app/sw.test.ts
@@ -12,7 +12,7 @@ describe("public worker activation", () => {
const listeners = vi.spyOn(Serwist.prototype, "addEventListeners")
const location = new URL("https://example.test/sw.js")
vi.stubGlobal("location", location)
- vi.stubGlobal("self", { location, __SW_MANIFEST: [{ url: shellUrl, revision: "fixture-shell" }, { url: "/icon-192.png", revision: "fixture" }, { url: "/favicon.ico", revision: "fixture-favicon" }, { url: "/_next/static/chunks/example.js", revision: "fixture-code" }], registration: { scope: `${location.origin}/` }, addEventListener: vi.fn() })
+ vi.stubGlobal("self", { skipWaiting: vi.fn(async () => undefined), location, __SW_MANIFEST: [{ url: shellUrl, revision: "fixture-shell" }, { url: "/icon-192.png", revision: "fixture" }, { url: "/favicon.ico", revision: "fixture-favicon" }, { url: "/_next/static/chunks/example.js", revision: "fixture-code" }], registration: { scope: `${location.origin}/` }, addEventListener: vi.fn() })
await import("./sw")
const serwist = listeners.mock.contexts[0]
if (!(serwist instanceof Serwist)) throw new Error("Missing actual Serwist instance")
@@ -83,7 +83,7 @@ describe("public worker activation", () => {
vi.stubGlobal("FetchEvent", WorkerFetchEvent)
vi.stubGlobal("location", location)
vi.stubGlobal("caches", storage)
- vi.stubGlobal("self", { location, caches: storage, registration: { scope: `${location.origin}/` }, addEventListener: vi.fn(),
+ vi.stubGlobal("self", { skipWaiting: vi.fn(async () => undefined), location, caches: storage, registration: { scope: `${location.origin}/` }, addEventListener: vi.fn(),
__SW_MANIFEST: [{ url: path, revision: null }, { url: "/icon-192.png", revision: "fixture" }] })
const network = vi.fn<typeof fetch>(async input => {
const shell = new URL(urlOf(input)).pathname === path
@@ -122,25 +122,70 @@ describe("public worker activation", () => {
expect(input).toMatchObject({ credentials: "omit", redirect: "error" })
}
})
- it("runs actual Serwist activation and deletes old custom cache names without changing the current cache", async () => {
+ it.each([true, false])("runs actual Serwist activation and claims only with the current cached shell: %s", async available => {
+ const html = '<main data-community-shell="public">Application</main>'
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(html))
+ const path = `/community-shell/${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("")}`
+ const stored = new Map<string, Response>()
const names = new Set(["alook-public-precache-v0", "alook-public-precache-v1", "alook-public-v99-runtime", "unrelated-cache"])
const storage = { keys: vi.fn(async () => [...names]), delete: vi.fn(async (name: string) => names.delete(name)),
- open: vi.fn(async (name: string) => { names.add(name); return { keys: async () => [] as Request[] } }) }
+ open: vi.fn(async (name: string) => { names.add(name); return { keys: async () => [] as Request[], match: async (key: string) => stored.get(key)?.clone() } }) }
+ const added = vi.spyOn(Serwist.prototype, "addEventListeners")
const listeners = new Map<string, Array<(event: { waitUntil: (promise: Promise<unknown>) => void }) => unknown>>()
const location = new URL("https://example.test/sw.js")
- const worker = { __SW_MANIFEST: [{ url: shellUrl, revision: "fixture-shell" }], location, caches: storage, registration: { scope: "https://example.test/" }, clients: { claim: vi.fn(async () => undefined) },
+ const worker = { skipWaiting: vi.fn(async () => undefined), __SW_MANIFEST: [{ url: path, revision: null }], location, caches: storage, registration: { scope: "https://example.test/" }, clients: { claim: vi.fn(async () => undefined), matchAll: vi.fn(async () => []) },
addEventListener: (type: string, listener: (event: { waitUntil: (promise: Promise<unknown>) => void }) => unknown) => listeners.set(type, [...listeners.get(type) ?? [], listener]) }
vi.stubGlobal("self", worker)
vi.stubGlobal("location", location)
vi.stubGlobal("caches", storage)
await import("./sw")
+ const serwist = added.mock.contexts[0]
+ if (!(serwist instanceof Serwist)) throw new Error("Missing actual Serwist instance")
+ if (available) stored.set(serwist.getPrecacheKeyForUrl(path)!, new Response(html, { headers: { "Content-Type": "text/html" } }))
const pending: Promise<unknown>[] = []
for (const listener of listeners.get("activate") ?? []) listener({ waitUntil: promise => { pending.push(promise) } })
- await Promise.all(pending)
- expect(worker.clients.claim).toHaveBeenCalledOnce()
+ if (available) await Promise.all(pending)
+ else await expect(Promise.all(pending)).rejects.toThrow("Current community shell unavailable")
+ expect(worker.clients.claim).toHaveBeenCalledTimes(available ? 1 : 0)
expect(names).toEqual(new Set(["alook-public-precache-v1", "unrelated-cache"]))
expect(storage.delete.mock.calls.map(([name]) => name)).toEqual(["alook-public-precache-v0", "alook-public-v99-runtime"])
expect(storage.open).toHaveBeenCalledWith("alook-public-precache-v1")
expect(listeners.has("fetch")).toBe(true)
})
})
+
+it.each(["probe", "probe-no-port", "unrelated", "missing-source", "source-without-id", "wrong-version", "missing-shell", "missing-client", "public-client", "current-marker", "navigate", "retry-marker", "navigation-refused"])("handles the actual worker message lifecycle: %s", async scenario => {
+ const { BUSINESS_SCHEMA_VERSION } = await import("@alook/shared/business-schema-version")
+ const { CURRENT_DOCUMENT_REQUEST, WORKER_VERSION_PROBE } = await import("../lib/service-worker/business-upgrade")
+ const location = new URL("https://example.test/sw.js")
+ const match = vi.spyOn(Serwist.prototype, "matchPrecache").mockResolvedValue(scenario === "missing-shell" ? undefined : new Response("cached current shell"))
+ const handlers: Array<(event: MessageEvent & { waitUntil: (value: Promise<unknown>) => void }) => void> = []
+ const marker = scenario === "current-marker" || scenario === "retry-marker" ? `?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}` : ""
+ const client = { id: "document", url: `https://example.test/${scenario === "public-client" ? "blog" : "c/me"}${marker}`, navigate: vi.fn(async () => scenario === "navigation-refused" ? null : ({ id: "new-document" })), postMessage: vi.fn() }
+ const clients = { matchAll: vi.fn(async () => scenario === "missing-client" ? [] : [client]), claim: vi.fn() }
+ vi.stubGlobal("location", location)
+ vi.stubGlobal("self", { location, skipWaiting: vi.fn(async () => undefined), registration: { scope: "https://example.test/" }, clients, __SW_MANIFEST: [{ url: shellUrl, revision: null }], addEventListener: (type: string, handler: typeof handlers[number]) => { if (type === "message") handlers.push(handler) } })
+ await import("./sw")
+ const reply = vi.fn()
+ const pending: Promise<unknown>[] = []
+ const data = { type: scenario.startsWith("probe") ? WORKER_VERSION_PROBE : scenario === "unrelated" ? "unrelated" : CURRENT_DOCUMENT_REQUEST, schemaVersion: scenario === "wrong-version" ? BUSINESS_SCHEMA_VERSION - 1 : BUSINESS_SCHEMA_VERSION, explicitRetry: scenario === "retry-marker" }
+ const source = scenario === "missing-source" ? null : scenario === "source-without-id" ? {} : { id: "document" }
+ handlers.at(-1)!({ data, source, ports: scenario === "probe-no-port" ? [] : [{ postMessage: reply }], waitUntil: promise => { pending.push(promise) } } as never)
+ await Promise.all(pending)
+ if (scenario.startsWith("probe")) {
+ expect(pending).toHaveLength(0)
+ if (scenario === "probe") expect(reply).toHaveBeenCalledWith({ schemaVersion: BUSINESS_SCHEMA_VERSION })
+ else expect(reply).not.toHaveBeenCalled()
+ expect(match).not.toHaveBeenCalled()
+ } else if (scenario === "unrelated") {
+ expect(pending).toHaveLength(0)
+ expect(reply).not.toHaveBeenCalled()
+ expect(match).not.toHaveBeenCalled()
+ } else {
+ const navigates = scenario === "navigate" || scenario === "retry-marker"
+ expect(reply).toHaveBeenCalledWith({ navigating: navigates })
+ expect(pending).toHaveLength(1)
+ expect(client.navigate).toHaveBeenCalledTimes(navigates || scenario === "navigation-refused" ? 1 : 0)
+ if (navigates) expect(client.navigate).toHaveBeenCalledWith(`https://example.test/c/me?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}`)
+ }
+})
diff --git a/src/web/src/app/sw.ts b/src/web/src/app/sw.ts
index bc9af1ea5..8f6ec47e1 100644
--- a/src/web/src/app/sw.ts
+++ b/src/web/src/app/sw.ts
@@ -7,6 +7,8 @@ import { createPublicRuntimeCaching } from "../lib/service-worker/public-cache-r
import { clearOutdatedPublicWorkerCaches } from "../lib/service-worker/public-cache-storage"
import { communityShellHash, isCommunityShellAssetRequest, isCommunityShellNavigation, isCommunityShellResponse } from "../lib/service-worker/community-shell"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared/business-schema-version"
+import { CURRENT_DOCUMENT_REQUEST, WORKER_VERSION_PROBE, upgradeBusinessWindow } from "../lib/service-worker/business-upgrade"
declare global {
interface WorkerGlobalScope extends SerwistGlobalConfig {
@@ -24,7 +26,8 @@ const shellUrl = shells[0]
const serwist = new Serwist({
precacheEntries: entries,
cacheId: publicWorkerCacheNames().cacheId,
- clientsClaim: true,
+ clientsClaim: false,
+ skipWaiting: true,
runtimeCaching: createPublicRuntimeCaching(self.location.origin, {
code: { maxEntries: 80, maxAgeSeconds: 30 * 24 * 60 * 60 },
fonts: { maxEntries: 160, maxAgeSeconds: 30 * 24 * 60 * 60 },
@@ -54,4 +57,29 @@ navigation.match = options => isCommunityShellNavigation(options.request, self.l
serwist.registerRoute(navigation)
serwist.addEventListeners()
-self.addEventListener("activate", event => event.waitUntil(clearOutdatedPublicWorkerCaches()))
+self.addEventListener("activate", event => event.waitUntil((async () => {
+ await clearOutdatedPublicWorkerCaches()
+ if (!await serwist.matchPrecache(shellUrl)) throw new Error("Current community shell unavailable")
+ await self.clients.claim()
+ const clients = await self.clients.matchAll({ type: "window" })
+ await Promise.allSettled(clients.map(client => upgradeBusinessWindow(client, self.location.origin)))
+})()))
+
+self.addEventListener("message", event => {
+ if (event.data?.type === WORKER_VERSION_PROBE) {
+ event.ports[0]?.postMessage({ schemaVersion: BUSINESS_SCHEMA_VERSION })
+ return
+ }
+ if (event.data?.type !== CURRENT_DOCUMENT_REQUEST) return
+ event.waitUntil((async () => {
+ const source = event.source
+ if (!source || !("id" in source) || event.data.schemaVersion !== BUSINESS_SCHEMA_VERSION || !await serwist.matchPrecache(shellUrl)) {
+ event.ports[0]?.postMessage({ navigating: false })
+ return
+ }
+ const client = (await self.clients.matchAll({ type: "window" })).find(client => client.id === source.id)
+ if (!client) { event.ports[0]?.postMessage({ navigating: false }); return }
+ const navigating = await upgradeBusinessWindow(client, self.location.origin, true, event.data.explicitRetry === true)
+ event.ports[0]?.postMessage({ navigating })
+ })())
+})
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 81adbbbeb..6609845ac 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
@@ -102,6 +102,7 @@ const {
retryingMetadata: false,
retryMetadata: vi.fn(),
routeHydrated: true,
+ windowReady: true,
routeLifecycle: "ready" as "pending" | "ready" | "terminal-error",
skeletonSubtype: "unknown" as "unknown" | "text" | "forum" | "thread",
layoutHint: {
@@ -472,6 +473,7 @@ describe("ChannelRoute message surface ownership", () => {
metadataError: false,
retryingMetadata: false,
routeHydrated: true,
+ windowReady: true,
routeLifecycle: "ready",
skeletonSubtype: "unknown",
layoutHint: { subtype: "unknown", parentChannelId: null, parentSubtype: "unknown" },
@@ -489,8 +491,8 @@ describe("ChannelRoute message surface ownership", () => {
vi.mocked(useChannelRouteModel).mockImplementation((_server, _param, id) => (id === "channel_1" ? parent : child) as never)
const base = conversationEntryFixture().channel
registry.collections.channels.utils.writeUpsert([
- channelSchema.parse({ ...base, id: "channel_1", serverId: "server_1", muted: false, unread: false, tags: [], pending: false, resourceComplete: true }),
- channelSchema.parse({ ...base, id: "child_1", serverId: "server_1", type: "thread", parentChannelId: "channel_1", parentMessageId: "opener_1", muted: false, unread: false, tags: [], pending: false, resourceComplete: true }),
+ channelSchema.parse({ ...base, id: "channel_1", serverId: "server_1", muted: false, tags: [], pending: false }),
+ channelSchema.parse({ ...base, id: "child_1", serverId: "server_1", type: "thread", parentChannelId: "channel_1", parentMessageId: "opener_1", muted: false, tags: [], pending: false }),
])
mockBreakpoint.value = "mobile"
mockSearchParams.value = ""
@@ -529,7 +531,11 @@ describe("ChannelRoute message surface ownership", () => {
if (boundary === "forward") mockNavigation.entryIntent = { href: "/c/channels/server_1/channel_1" }
if (boundary === "unhydrated") mockRouteModel.routeHydrated = false
if (boundary === "pending") mockRouteModel.routeLifecycle = "pending"
- if (boundary === "text") mockRouteModel.isForum = false
+ if (boundary === "text") {
+ mockRouteModel.isForum = false
+ mockRouteModel.channel = { id: "channel_1", name: "Text", type: "text" }
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ }
render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1", routeCommitted: false }))
const model = mockedUseChannelMemberViewModel.mock.calls.at(-1)![0]
expect(model.accessAllowed).toBe(false)
@@ -1441,6 +1447,17 @@ describe("ChannelRoute message surface ownership", () => {
expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
})
+ it("mounts a qualified child composer while window-dependent read actions remain pending", () => {
+ configureThreadRoute()
+ mockRouteModel.windowReady = false
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ isLoading: true, navigationBlocked: true, messages: [] }))
+ const view = render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ expect(view.container.querySelector('textarea[data-draft-key="server_1/channel_1"]')).not.toBeNull()
+ expect(mockDismissConversation).toHaveBeenCalledExactlyOnceWith("viewer_1", { kind: "server", serverId: "server_1", channelId: "channel_1" }, false)
+ expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
+ expect(mockOpenerGate).toHaveBeenCalledWith(expect.objectContaining({ lifecycle: "pending" }))
+ })
+
it("commits and dismisses only a ready top-level channel for the active account", async () => {
mockedUseChannelMessageFeed.mockReturnValue(feed())
await act(async () => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 0602f3b83..48b666b1b 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -219,7 +219,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
const forumPostOpener = useForumOpenerHint(
serverId,
currentChannelMeta?.parentMessageId,
- presented && isForumPostChild && !resolvingParent && routeModel.routeHydrated,
+ presented && isForumPostChild && !resolvingParent && routeModel.routeHydrated && routeModel.windowReady,
)
const channelName = useMemo(() => resolveChannelDisplayName({
forumPostTitle: isForumPostChild ? forumPostOpener.data?.content : null,
@@ -300,11 +300,11 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
uiHandlers.openProfile?.(name, e, discriminator, userId)
}, [uiHandlers])
- const channelReadReady =
+ const channelSurfaceReady =
routeModel.routeLifecycle === "ready" &&
routeModel.routeHydrated
- const channelHydrated = !resolvingParent && channelReadReady
- const clientReady = active && routeCommitted && channelHydrated && currentChannelId === channelId
+ const channelHydrated = !resolvingParent && channelSurfaceReady
+ const clientReady = active && routeCommitted && channelHydrated && routeModel.windowReady && currentChannelId === channelId
useNativeSystemNotificationConversationDismissal(currentUser.id, {
kind: "server",
serverId,
@@ -347,7 +347,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
parentChannelId={currentChannelMeta?.parentChannelId ?? null}
parentMessageId={currentChannelMeta?.parentMessageId ?? null}
parentIsForum={isForumPostChild}
- routeLifecycle={routeCommitted ? routeModel.routeLifecycle : "pending"}
+ routeLifecycle={routeCommitted && routeModel.windowReady ? routeModel.routeLifecycle : "pending"}
canRenameThread={canManageServer(myRole)}
onNavigateParent={navigateParent}
notificationLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}
diff --git a/src/web/src/components/community/channels/dm-route.dom.test.ts b/src/web/src/components/community/channels/dm-route.dom.test.ts
index 12a5ae700..dd4b260d3 100644
--- a/src/web/src/components/community/channels/dm-route.dom.test.ts
+++ b/src/web/src/components/community/channels/dm-route.dom.test.ts
@@ -1,9 +1,12 @@
+import { dmListRowFixture } from "@/test/community-resource-fixtures"
import React, { useLayoutEffect, type PropsWithChildren } from "react"
import { useCommunityRuntime } from "@/stores/community/runtime"
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, screen, setupUser, waitFor } from "@/test/react-dom-harness"
import { renderCommunity, renderCommunityHook } from "@/test/community-owner-harness"
import { DmRoute } from "./dm-route"
+import { useChannelMetadata } from "@/hooks/community/use-channel-metadata"
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION, CommunityReadErrorSchema } from "@alook/shared"
import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections"
import { ingestDms } from "@/lib/community-db/sync"
@@ -19,7 +22,8 @@ function render(node: React.ReactNode) {
}
const mocks = vi.hoisted(() => ({
- verification: { status: "pending", identityKnown: false, retrying: false, retry: vi.fn() },
+ realMetadata: false,
+ verification: { status: "pending", identityKnown: false, retrying: false, retry: vi.fn(), denialCode: undefined as import("@/lib/errors").CommunityApiError["code"] | undefined },
breakpoint: "desktop",
last: "dm-a",
cold: false,
@@ -28,10 +32,13 @@ const mocks = vi.hoisted(() => ({
vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace }) }))
vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "viewer" }) }))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))
-vi.mock("@/hooks/community/use-channel-metadata", () => ({ useChannelMetadata: () => mocks.verification }))
+vi.mock("@/hooks/community/use-channel-metadata", async importOriginal => {
+ const actual=await importOriginal<typeof import("@/hooks/community/use-channel-metadata")>()
+ return {...actual,useChannelMetadata:(...args:Parameters<typeof actual.useChannelMetadata>)=>mocks.realMetadata ? actual.useChannelMetadata(...args) : mocks.verification}
+})
vi.mock("@/stores/community", async (importOriginal) => ({ ...await importOriginal<typeof import("@/stores/community")>(), useCommunityStore: { getState: () => ({ uiHandlers: { cancelPendingNavigation: mocks.cancel } }) } }))
vi.mock("@/lib/community-db/sync", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/sync")>(), purgeCommunityChannel: mocks.purge }))
-vi.mock("@/lib/community/last-me-location", () => ({ ME_ROOT: "/c/me", getLastMeLeaf: () => mocks.last, clearLastMeLocation: mocks.clear }))
+vi.mock("@/lib/community/last-me-location", () => ({ ME_ROOT: "/c/me", getLastMeLeaf: () => mocks.last, clearLastMeLocation: () => { mocks.clear(); mocks.last = "" } }))
vi.mock("@/lib/community/last-community-route", () => ({
COMMUNITY_COLD_ENTRY_FALLBACK: "/c/me/machines",
consumeCommunityColdEntryFailure: (...args: unknown[]) => {
@@ -45,7 +52,10 @@ vi.mock("./dm-view", () => ({ DmView: ({ dmId }: { dmId: string }) => React.crea
vi.mock("./dm-loading-frame", () => ({ DmLoadingFrame: ({ reserveBackSlot }: { reserveBackSlot: boolean }) => React.createElement("div", { "data-testid": "dm-pending", "data-back": String(reserveBackSlot) }) }))
vi.mock("./dm-route-error-frame", () => ({ DmRouteErrorFrame: ({ onRetry, retrying, reserveBackSlot }: { onRetry: () => void; retrying: boolean; reserveBackSlot?: boolean }) => React.createElement("button", { onClick: onRetry, disabled: retrying, "data-back": String(reserveBackSlot) }, "Retry") }))
+afterEach(()=>vi.unstubAllGlobals())
beforeEach(() => {
+ mocks.realMetadata=false
+ mocks.verification.denialCode=undefined
mocks.verification.status = "pending"
mocks.verification.identityKnown = false
mocks.verification.retrying = false
@@ -58,7 +68,7 @@ beforeEach(() => {
describe("DM target main owns identity, retry and fallback", () => {
it.each(["pending", "retryable-error", "denied"])("keeps canonical DM presentation while entry is %s without granting read permission", async status => {
const owner = renderCommunityHook(() => useOptionalCommunityDbRegistry()).result.current!
- await act(async () => { ingestDms(owner, { conversations: [{ id: "dm-a", userId: "peer", name: "Peer", discriminator: "0042", avatar: "/avatar", avatarVersion: 1, status: "offline", preview: "" }] }) })
+ await act(async () => { ingestDms(owner, { conversations: [dmListRowFixture({ id: "dm-a", userId: "peer", name: "Peer", discriminator: "0042", avatar: "/avatar", avatarVersion: 1, status: "offline", preview: "" })] }) })
mocks.verification.status = status
expect(mocks.verification.identityKnown).toBe(false)
const route = render(React.createElement(DmRoute, { dmId: "dm-a" }))
@@ -152,3 +162,34 @@ describe("DM unknown viewport keeps the same responsive leading footprint", () =
view.unmount()
})
})
+
+it.each([["blocked",403],["not_allowed",403],["not_found",404]] as const)("uses real HTTP metadata to distinguish %s with no current native identity",async(code,status)=>{
+ mocks.realMetadata=true
+ const registry=renderCommunityHook(()=>useOptionalCommunityDbRegistry()).result.current!
+ let release!:(response:Response)=>void
+ const fetch=vi.fn(()=>new Promise<Response>(resolve=>{release=resolve}))
+ vi.stubGlobal("fetch",fetch)
+ const metadata=renderCommunityHook(()=>useChannelMetadata(null,"dm-a"))
+ const view=render(React.createElement(DmRoute,{dmId:"dm-a"}))
+ try {
+ await waitFor(()=>expect(fetch).toHaveBeenCalledOnce())
+ expect(registry.collections.channels.has("dm-a")).toBe(false)
+ expect(metadata.result.current.status).toBe("pending")
+ const payload=CommunityReadErrorSchema.parse({contractVersion:BUSINESS_SCHEMA_VERSION,error:{code,message:code,retryable:false}})
+ await act(async()=>{release(new Response(JSON.stringify(payload),{status,headers:{"content-type":"application/json",[COMMUNITY_CONTRACT_HEADER]:String(BUSINESS_SCHEMA_VERSION)}}))})
+ await waitFor(()=>expect(metadata.result.current.status).toBe("denied"))
+ expect(metadata.result.current).toMatchObject({denialCode:code,identityKnown:false,canRead:false,revoked:true})
+ expect(metadata.result.current.error).toBeNull()
+ expect(registry.collections.messages.size).toBe(0)
+ if(code==="blocked") {
+ expect(view.container.querySelector("main")).toHaveAttribute("data-channel-id","dm-a")
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(mocks.clear).not.toHaveBeenCalled()
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ } else {
+ expect(view.container.querySelector("main")).toBeNull()
+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
+ expect(mocks.clear).toHaveBeenCalledOnce()
+ }
+ } finally {view.unmount();metadata.unmount();await registry.queryClient.cancelQueries()}
+})
diff --git a/src/web/src/components/community/channels/dm-route.tsx b/src/web/src/components/community/channels/dm-route.tsx
index 1c1c094f6..4f4860ce7 100644
--- a/src/web/src/components/community/channels/dm-route.tsx
+++ b/src/web/src/components/community/channels/dm-route.tsx
@@ -23,9 +23,10 @@ export function DmRoute({ dmId, routeCommitted = true }: { dmId: string; routeCo
const currentUser = useCurrentUser()
const verification = useChannelMetadata(null, dmId)
const knownDm = useDmProjection()?.some(dm => dm.id === dmId) === true
+ const blocked = verification.denialCode === "blocked"
const exitedTarget = useRef<string | null>(null)
useEffect(() => {
- if (!routeCommitted || verification.status !== "denied" || verification.identityKnown || knownDm) return
+ if (!routeCommitted || blocked || verification.status !== "denied" || verification.identityKnown || knownDm) return
const target = JSON.stringify([currentUser.id, dmId])
if (exitedTarget.current === target) return
exitedTarget.current = target
@@ -36,13 +37,13 @@ export function DmRoute({ dmId, routeCommitted = true }: { dmId: string; routeCo
if (getLastMeLeaf() === dmId) clearLastMeLocation()
runtime.ui.get().uiHandlers.cancelPendingNavigation?.()
router.replace(destination)
- }, [currentUser.id, dmId, routeCommitted, router, runtime, verification.status, verification.identityKnown, knownDm])
+ }, [currentUser.id, dmId, routeCommitted, router, runtime, verification.status, verification.identityKnown, knownDm, blocked])
- if (verification.status === "retryable-error" && !verification.identityKnown && !knownDm) {
+ if (!blocked && verification.status === "retryable-error" && !verification.identityKnown && !knownDm) {
return <DmRouteErrorFrame onRetry={verification.retry} retrying={verification.retrying}
reserveBackSlot />
}
- if (!verification.identityKnown && !knownDm && verification.status !== "readable") {
+ if (!blocked && !verification.identityKnown && !knownDm && verification.status !== "readable") {
return <DmLoadingFrame reserveBackSlot />
}
return <DmView dmId={dmId} routeCommitted={routeCommitted} />
diff --git a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
index e52264800..62c3ca987 100644
--- a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
+++ b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
@@ -1,3 +1,5 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import React, { type PropsWithChildren } from "react"
import { renderToString } from "react-dom/server"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -7,13 +9,13 @@ import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { DmView } from "./dm-view"
import { dmConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
-const mocks = vi.hoisted(() => ({ api: vi.fn(), advance: vi.fn(), list: vi.fn(), positionEntry: null as object | null, failed: true, breakpoint: "mobile", identity: true, blocked: false }))
+const mocks = vi.hoisted(() => ({ api: vi.fn(), advance: vi.fn(), list: vi.fn(), positionEntry: null as object | null, failed: true, breakpoint: "mobile", identity: true, blocked: false, windowBlocked: false }))
vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api, toastApiError: vi.fn() }))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))
vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "u_me", name: "Me", avatar: "M" }) }))
vi.mock("@/hooks/community/use-dms", () => ({ useDms: () => ({ dms: mocks.identity ? ["dm_1", "dm_2"].map(id => ({ id, userId: "peer", name: "Peer", avatar: "P" })) : [], isLoading: false, isFetching: false }) }))
vi.mock("@/hooks/community/use-friends", () => ({ useFriends: () => ({ friends: [], blocked: mocks.blocked ? [{ id: "peer", userId: "peer" }] : [] }) }))
-vi.mock("@/hooks/community/use-messages", () => ({ useDmMessages: () => ({ messages: mocks.failed ? [{ id: "failed", clientNonce: "retry_nonce", authorId: "u_me", type: "chat", content: "retry" }] : [], positionEntry: mocks.positionEntry, positionDataState: "ready", isLoading: false, isPending: false, isError: false, latestSeq: 0 }) }))
+vi.mock("@/hooks/community/use-messages", () => ({ useDmMessages: () => ({ messages: mocks.failed ? [{ id: "failed", clientNonce: "retry_nonce", authorId: "u_me", type: "chat", content: "retry" }] : [], positionEntry: mocks.positionEntry, positionDataState: "ready", isLoading: false, isPending: false, isError: false, latestSeq: 0, navigationBlocked: mocks.windowBlocked }) }))
vi.mock("@/hooks/community/use-channel-metadata", () => ({ useChannelMetadata: () => ({ canRead: true, status: "readable" }) }))
vi.mock("@/hooks/community/use-dm-watermark", () => ({ useDmWatermark: vi.fn() }))
vi.mock("@/hooks/community/use-channel-ref-directory", () => ({ useChannelRefDirectory: () => ({ directory: [], isResolved: true }) }))
@@ -28,13 +30,17 @@ vi.mock("./dm-header", () => ({ DmHeaderSkeleton: () => React.createElement("hea
vi.mock("@/components/community/avatar", () => ({ Avatar: () => null }))
vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))
vi.mock("@/components/community/messages/conversation-footer-shell", () => ({ ConversationFooterSlotProvider: ({ children }: PropsWithChildren) => children, ConversationFooterShell: ({ children }: PropsWithChildren) => children }))
-vi.mock("@/components/community/messages/composer", () => ({ ComposerSkeleton: () => null, Composer: ({ onAcceptSend }: { onAcceptSend: (text: string) => boolean }) => React.createElement("button", { onClick: () => onAcceptSend("hello") }, "Send") }))
+vi.mock("@/components/community/messages/composer", () => ({ ComposerSkeleton: () => React.createElement("div", { "data-testid": "composer-pending" }), Composer: ({ onAcceptSend }: { onAcceptSend: (text: string) => boolean }) => React.createElement("button", { onClick: () => onAcceptSend("hello") }, "Send") }))
vi.mock("@/components/community/messages/message-list", () => ({ MessageList: (props: { onRetry?: (id: string) => void }) => {
mocks.list(props)
return React.createElement("button", { onClick: () => props.onRetry?.("failed") }, "Retry")
} }))
-beforeEach(() => { mocks.api.mockReset(); mocks.advance.mockReset(); mocks.list.mockReset(); mocks.positionEntry = null; mocks.failed = true; mocks.breakpoint = "mobile"; mocks.identity = true; mocks.blocked = false })
+beforeEach(() => { mocks.api.mockReset(); mocks.advance.mockReset(); mocks.list.mockReset(); mocks.positionEntry = null; mocks.failed = true; mocks.breakpoint = "mobile"; mocks.identity = true; mocks.blocked = false; mocks.windowBlocked = false })
+
+function posted(body: { content: string; nonce: string }) {
+ return { profiles: messageProfilesFixture([messageResourceFixture({ id: "confirmed", channelId: "dm_1", authorId: "u_me", authorName: "Me", authorAvatarVersion: 0, seq: 9, content: body.content, clientNonce: body.nonce, createdAt: "2026-10-09T00:00:00Z", embeds: [] })]), deduped: false, message: messageResourceFixture({ id: "confirmed", channelId: "dm_1", authorId: "u_me", authorName: "Me", authorAvatarVersion: 0, seq: 9, content: body.content, clientNonce: body.nonce, createdAt: "2026-10-09T00:00:00Z", embeds: [] }) }
+}
async function createDmOwner() {
const owner = await createCommunityQueryOwner("u_me")
@@ -56,6 +62,23 @@ async function createDmOwner() {
}
describe("real DmView accepted send UI lifecycle", () => {
+ it("keeps the known peer header and composer skeleton until its owned window is ready", async () => {
+ const owner = await createDmOwner()
+ mocks.windowBlocked = true
+ const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)
+ const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })
+ expect(view.container.querySelector("header")).not.toBeNull()
+ expect(screen.getByTestId("composer-pending")).toBeInTheDocument()
+ expect(screen.queryByRole("button", { name: "Send" })).toBeNull()
+ expect(mocks.list.mock.lastCall?.[0].onRetry).toBeUndefined()
+ expect(mocks.api).not.toHaveBeenCalled()
+ mocks.windowBlocked = false
+ view.rerender(React.createElement(DmView, { dmId: "dm_1" }))
+ expect(screen.getByRole("button", { name: "Send" })).toBeInTheDocument()
+ expect(screen.queryByTestId("composer-pending")).toBeNull()
+ view.unmount()
+ })
+
it("keeps qualified messages when peer identity is absent and restricts sends until the peer relationship is known", async () => {
const owner = await createDmOwner()
mocks.identity = false
@@ -70,7 +93,7 @@ describe("real DmView accepted send UI lifecycle", () => {
expect(mocks.list.mock.lastCall?.[0].messages).toHaveLength(1)
expect(mocks.list.mock.lastCall?.[0].onRetry).toBeUndefined()
expect(screen.queryByRole("button", { name: "Send" })).toBeNull()
- await act(async () => owner.registry.collections.channelMemberships.utils.writeUpsert({ id: "dm_1:peer:access", channelId: "dm_1", userId: "peer", relation: "access", source: "added", isCreator: false, role: null }))
+ await act(async () => owner.registry.collections.channelMemberships.utils.writeUpsert({ id: "dm_1:peer:access", channelId: "dm_1", userId: "peer", relation: "access", source: "added" }))
await waitFor(() => expect(screen.getByRole("button", { name: "Send" })).toBeInTheDocument())
expect(mocks.list.mock.lastCall?.[0].channel).toBe("Direct message")
expect(screen.getByRole("button", { name: "Retry" })).toBe(retained)
@@ -125,7 +148,7 @@ describe("real DmView accepted send UI lifecycle", () => {
expect(mocks.api.mock.calls[0][0]).toBe("/api/community/channels/dm_1/messages")
view.rerender(React.createElement(DmView, { dmId: "dm_2" }))
expect(options.signal.aborted).toBe(false)
- await act(async () => finish({ message: { id: "confirmed", seq: 9, type: "chat", content: body.content, authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T00:00:00Z", embeds: [] } }))
+ await act(async () => finish(posted(body)))
await waitFor(() => expect(owner.registry.collections.messages.get("confirmed")?.channelId).toBe("dm_1"))
expect(mocks.advance).not.toHaveBeenCalled()
expect(mocks.api).toHaveBeenCalledOnce()
@@ -135,7 +158,7 @@ describe("real DmView accepted send UI lifecycle", () => {
const owner = await createDmOwner()
owner.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" }, { nonce: "retry_nonce", tempId: "temp_retry", message: { type: "chat", authorId: "u_me", content: "retry" }, localUploads: [] })
owner.runtime.messageStream.actions.dispatch({ kind: "dm", id: "dm_1" }, { type: "postFail", nonce: "retry_nonce" })
- mocks.api.mockResolvedValueOnce({ message: { id: "confirmed", seq: 9, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T00:00:00Z", embeds: [] } })
+ mocks.api.mockImplementationOnce((_path: string, options: { body: string }) => Promise.resolve(posted(JSON.parse(options.body))))
const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)
const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })
await act(async () => screen.getByRole("button", { name: action === "send" ? "Send" : "Retry" }).click())
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 407d284f6..15f883a44 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -111,8 +111,8 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
}, [dms, dmId, peerId, peerProfile])
const displayName = dm?.name ?? "Direct message"
const dmBlocked = !!peerId && blocked.some((b) => (b.userId ?? b.id) === peerId)
+ const readDenied = metadata.denied || metadata.denialCode === "blocked"
const historyAllowed = !dmBlocked && metadata.canRead
- const sendAllowed = historyAllowed && !!peerId
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.
@@ -163,6 +163,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
enabled: !dmBlocked && !metadata.revoked && !metadata.denied,
viewerUserId: currentUser.id,
})
+ const sendAllowed = historyAllowed && !!peerId && !navigationBlocked
const messages = useMemo(() => historyAllowed ? fetchedMessages : [], [fetchedMessages, historyAllowed])
@@ -419,13 +420,15 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
return <DmLoadingFrame reserveBackSlot />
}
- if (!historyAllowed && loadingOwnership.fullFramePending) {
- return <DmLoadingFrame reserveBackSlot />
- }
+ if (!readDenied) {
+ if (!historyAllowed && loadingOwnership.fullFramePending) {
+ return <DmLoadingFrame reserveBackSlot />
+ }
- if (!historyAllowed && (loadingOwnership.missingPeer || !dm)) {
- return <DmRouteErrorFrame onRetry={() => { void dmsQuery.refetch({ cancelRefetch: false }) }}
- retrying={dmsQuery.isFetching} reserveBackSlot />
+ if (!historyAllowed && (loadingOwnership.missingPeer || !dm)) {
+ return <DmRouteErrorFrame onRetry={() => { void dmsQuery.refetch({ cancelRefetch: false }) }}
+ retrying={dmsQuery.isFetching} reserveBackSlot />
+ }
}
return (
@@ -446,7 +449,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
className="flex min-h-0 flex-1 flex-col"
>
<ConversationFooterSlotProvider>
- {dmBlocked ? null : metadata.denied ? <div role="alert" className="flex min-h-0 flex-1 items-center justify-center p-4 text-sm text-muted-foreground">You can no longer read this conversation.</div> : metadata.status === "retryable-error" ? <ConversationResolutionErrorFrame as="div" onRetry={metadata.retry} retrying={metadata.retrying} /> : !historyAllowed && initialLoadError ? <ConversationResolutionErrorFrame as="div" onRetry={retryInitialLoad} retrying={retryingInitialLoad} /> : <MessageList
+ {dmBlocked ? null : readDenied ? <div role="alert" className="flex min-h-0 flex-1 items-center justify-center p-4 text-sm text-muted-foreground">You can no longer read this conversation.</div> : metadata.status === "retryable-error" ? <ConversationResolutionErrorFrame as="div" onRetry={metadata.retry} retrying={metadata.retrying} /> : !historyAllowed && initialLoadError ? <ConversationResolutionErrorFrame as="div" onRetry={retryInitialLoad} retrying={retryingInitialLoad} /> : <MessageList
key={dmId}
variant="dm"
channel={displayName}
@@ -517,7 +520,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
>
You have blocked this user. Unblock to send messages.
</div>
- ) : metadata.denied ? null : !sendAllowed ? <ComposerSkeleton /> : (
+ ) : readDenied ? null : !sendAllowed ? <ComposerSkeleton /> : (
<Composer
sendContract="accepted"
channel={displayName}
diff --git a/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx b/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx
index eb508d9a9..6d3b07515 100644
--- a/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx
+++ b/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx
@@ -3,17 +3,16 @@ import { act, fireEvent, render } from "@/test/react-dom-harness"
import { ForumPostList } from "./forum-post-list"
import type { ForumThread } from "@/lib/community/models/message"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
-import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
+import { captureChannelMetadataToken, type ConversationListScope } from "@/lib/community/conversation-qualification"
import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
-const posts = Array.from({ length: 40 }, (_, index) => ({ id: `p${index}`, openerMessageId: `m${index}` } as ForumThread))
+const posts = Array.from({ length: 180 }, (_, index) => ({ id: `p${index}`, openerMessageId: `m${index}` } as ForumThread))
const renderPost = (post: ForumThread) => <div data-msg-id={post.openerMessageId} />
-describe("Forum native list identity and restoration", () => {
- it("keeps an unscoped native list readable without creating a snapshot record", () => {
+describe("Forum native list identity and ordinary reconstruction", () => {
+ it("keeps an unscoped native list readable", () => {
const view = render(<ForumPostList posts={posts} renderPost={renderPost} loadingContent={<span>Loading</span>} />)
resize()
const root = view.getByTestId("community-forum-post-list")
@@ -21,9 +20,9 @@ describe("Forum native list identity and restoration", () => {
expect(root.scrollTop).toBe(0)
})
- it.each(["same", "other-tag", "messages", "width", "hidden"] as const)("restores only the matching forum layout: %s", async mode => {
+ it.each(["same", "other-tag", "width", "hidden"] as const)("starts a new Forum instance at its normal first item: %s", async mode => {
const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "forum"), kind: "forum", tag: null }
+ const positionScope: ConversationListScope = { proof: captureChannelMetadataToken(client, "forum"), tag: null }
const props = { posts, renderPost, loadingContent: <span>Loading</span>, positionScope }
const first = render(<ForumPostList {...props} />)
resize()
@@ -31,12 +30,9 @@ describe("Forum native list identity and restoration", () => {
act(() => root.scrollTo({ top: 800 }))
runFrames()
resize()
- const before = root.scrollTop
- const saved = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))
- expect(saved?.offset).toBe(before)
+ expect(root.scrollTop).toBe(800)
first.unmount()
- const scope = mode === "other-tag" ? { ...positionScope, tag: "bug" }
- : mode === "messages" ? { ...positionScope, kind: "messages" as const } : positionScope
+ const scope = mode === "other-tag" ? { ...positionScope, tag: "bug" } : positionScope
if (mode === "width") scrollFixture.width = 600
if (mode === "hidden") { scrollFixture.width = 0; scrollFixture.height = 0 }
const second = render(<ForumPostList {...props} positionScope={scope} />)
@@ -47,14 +43,15 @@ describe("Forum native list identity and restoration", () => {
scrollFixture.height = 500
resize()
}
- const restored = second.getByTestId("community-forum-post-list")
- expect(restored.scrollTop).toBe(mode === "same" || mode === "hidden" ? before : 0)
- expect(restored.querySelector("[data-read-position-ready]")?.getAttribute("data-read-position-ready")).toBe("true")
+ const entered = second.getByTestId("community-forum-post-list")
+ expect(entered.scrollTop).toBe(0)
+ expect(entered.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "true")
+ expect(entered.querySelectorAll('[data-index]').length).toBeLessThan(60)
})
- it("admits a cached list after loading and retains its current instance across ordinary updates", async () => {
+ it("admits a cached list after loading and retains its current instance across ordinary proof refreshes", async () => {
const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "forum"), kind: "forum", tag: null }
+ const positionScope: ConversationListScope = { proof: captureChannelMetadataToken(client, "forum"), tag: null }
const props = { renderPost, loadingContent: <span>Loading</span>, positionScope }
const view = render(<ForumPostList {...props} posts={[]} loading />)
expect(view.getByText("Loading")).toBeDefined()
@@ -65,9 +62,29 @@ describe("Forum native list identity and restoration", () => {
act(() => root.scrollTo({ top: 700 }))
runFrames()
resize()
- view.rerender(<ForumPostList {...props} posts={posts} isFetching />)
+ view.rerender(<ForumPostList {...props} positionScope={{ ...positionScope, proof: captureChannelMetadataToken(client, "forum") }} posts={posts} isFetching />)
resize()
expect(view.getByTestId("community-forum-post-list")).toBe(root)
expect(root.scrollTop).toBe(700)
+ view.rerender(<ForumPostList {...props} positionScope={{ ...positionScope, tag: "bug" }} posts={posts} />)
+ resize()
+ expect(root.isConnected).toBe(false)
+ expect(view.getByTestId("community-forum-post-list").scrollTop).toBe(0)
})
})
+
+it("exposes only an unadmitted forum's initial loading and keeps an admitted empty list on refetch", () => {
+ const props = { posts: [], renderPost, loadingContent: <span>Loading actual forum</span> }
+ const view = render(<ForumPostList {...props} loading />)
+ expect(view.getByLabelText("Loading forum")).toHaveAttribute("aria-busy", "true")
+ expect(view.getByLabelText("Loading forum")).toHaveAttribute("data-community-conversation-subtype", "forum")
+ expect(view.getByText("Loading actual forum")).toBeVisible()
+ view.rerender(<ForumPostList {...props} />)
+ const admitted = view.getByTestId("community-forum-post-list")
+ expect(admitted).not.toHaveAttribute("aria-busy")
+ expect(view.queryByLabelText("Loading forum")).toBeNull()
+ view.rerender(<ForumPostList {...props} loading isFetching />)
+ expect(view.getByTestId("community-forum-post-list")).toBe(admitted)
+ expect(view.queryByText("Loading actual forum")).toBeNull()
+ expect(view.queryByLabelText("Loading forum")).toBeNull()
+})
diff --git a/src/web/src/components/community/channels/forum-post-list.tsx b/src/web/src/components/community/channels/forum-post-list.tsx
index 7c9427594..c25d1bb78 100644
--- a/src/web/src/components/community/channels/forum-post-list.tsx
+++ b/src/web/src/components/community/channels/forum-post-list.tsx
@@ -6,7 +6,7 @@ import { ListChevronsUpDown } from "lucide-react"
import { hashKey } from "@tanstack/react-query"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"
-import { readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, virtualListPositionKey, type VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import { conversationListScopeKey, type ConversationListScope } from "@/lib/community/conversation-qualification"
import { useObservedRegion, type ResourceObservation } from "@/lib/observability/regions"
import { visibleVirtualItems } from "@/lib/observability/virtual-window"
import type { ForumThread } from "@/lib/community/models/message"
@@ -20,7 +20,7 @@ type Props = {
posts: ForumThread[]
loading?: boolean
observation?: ResourceObservation
- positionScope?: VirtualListPositionScope
+ positionScope?: ConversationListScope
hasMore?: boolean
loadingMore?: boolean
isFetching?: boolean
@@ -32,33 +32,30 @@ type Props = {
}
export function ForumPostList(props: Props) {
- return <ForumPostListEntry key={props.positionScope ? hashKey(virtualListPositionKey(props.positionScope)) : undefined} {...props} />
+ return <ForumPostListEntry key={props.positionScope ? hashKey(conversationListScopeKey(props.positionScope)) : undefined} {...props} />
}
function ForumPostListEntry(props: Props) {
const [admitted, setAdmitted] = useState(false)
if (!props.loading && !admitted || props.posts.length > 0 && !admitted) setAdmitted(true)
- if (!admitted && props.loading && !props.posts.length) return <div data-testid={tid.forumPostList} className="flex-1 overflow-y-auto thin-scrollbar px-0 py-2 sm:px-4">{props.loadingContent}</div>
+ if (!admitted && props.loading && !props.posts.length) return <div data-testid={tid.forumPostList} aria-label="Loading forum" aria-busy="true" data-community-conversation-subtype="forum" className="flex-1 overflow-y-auto thin-scrollbar px-0 py-2 sm:px-4">{props.loadingContent}</div>
return <ForumPostListOwner {...props} />
}
-function ForumPostListOwner({ posts, loading, observation, positionScope, hasMore, loadingMore, isFetching, isError, onLoadMore, onScrollRoot, renderPost }: Props) {
+function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore, isFetching, isError, onLoadMore, onScrollRoot, renderPost }: Props) {
const scrollRef = useRef<HTMLDivElement>(null)
- const fingerprint = useMemo(() => virtualListLayoutFingerprint(posts), [posts])
- const [initialSnapshot] = useState(() => readVirtualListPosition(positionScope, fingerprint))
const initialized = useRef(false)
- const savedPosition = useRef<{ scope: VirtualListPositionScope | undefined; fingerprint: string; offset: number; width: number; height: number; total: number } | null>(null)
const [positionReady, setPositionReady] = useState(false)
- const context = useRef({ positionScope, fingerprint, posts })
- useLayoutEffect(() => { context.current = { positionScope, fingerprint, posts } }, [positionScope, fingerprint, posts])
+ const postsRef = useRef(posts)
+ useLayoutEffect(() => { postsRef.current = posts }, [posts])
const bindScrollRoot = useCallback((node: HTMLDivElement | null) => { scrollRef.current = node; onScrollRoot?.(node) }, [onScrollRoot])
const inspectPosition = useCallback((native: Virtualizer<HTMLDivElement, Element>) => {
const root = scrollRef.current
- const current = context.current
+ const current = postsRef.current
if (!initialized.current || !root || !root.isConnected || root.clientWidth <= 0 || root.clientHeight <= 0
|| native.isScrolling || Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1
- || native.options.count !== current.posts.length
- || current.posts.some((post, index) => native.options.getItemKey(index) !== post.id)) return
+ || native.options.count !== current.length
+ || current.some((post, index) => native.options.getItemKey(index) !== post.id)) return
const fold = native.getVirtualItemForOffset(root.scrollTop + 1)
const wrapper = fold && root.querySelector<HTMLElement>(`[data-index="${fold.index}"]`)
const rect = wrapper?.getBoundingClientRect()
@@ -66,40 +63,15 @@ function ForumPostListOwner({ posts, loading, observation, positionScope, hasMor
if (!fold || !rect || rect.height <= 0 || Math.abs(rect.height - fold.size) > 1
|| Math.abs(rect.top - root.getBoundingClientRect().top + root.scrollTop - padding - fold.start) > 1) return
setPositionReady(true)
- const previous = savedPosition.current
- const total = native.getTotalSize()
- if (previous && previous.scope === current.positionScope && previous.fingerprint === current.fingerprint
- && previous.offset === root.scrollTop && previous.width === root.clientWidth && previous.height === root.clientHeight
- && previous.total === total) return
- saveVirtualListPosition(current.positionScope, {
- version: 1, fingerprint: current.fingerprint, offset: root.scrollTop,
- width: root.clientWidth, height: root.clientHeight,
- paddingStart: native.options.paddingStart ?? 0, paddingEnd: native.options.paddingEnd ?? 0,
- anchorKey: fold.key, anchorOffset: fold.start - root.scrollTop,
- measurements: current.positionScope ? native.takeSnapshot() : [], at: Date.now(),
- })
- savedPosition.current = { scope: current.positionScope, fingerprint: current.fingerprint,
- offset: root.scrollTop, width: root.clientWidth, height: root.clientHeight, total }
}, [])
const getItemKey = useCallback((index: number) => posts[index]?.id ?? index, [posts])
const initializePosition = useCallback((native: Virtualizer<HTMLDivElement, Element>) => {
- const current = context.current
- if (initialized.current || !current.posts.length || native.options.count !== current.posts.length
- || current.posts.some((post, index) => native.options.getItemKey(index) !== post.id)) return
- const root = scrollRef.current
- if (initialSnapshot && (!root || root.clientWidth <= 0 || root.clientHeight <= 0)) return
+ const current = postsRef.current
+ if (initialized.current || !current.length || native.options.count !== current.length
+ || current.some((post, index) => native.options.getItemKey(index) !== post.id)) return
initialized.current = true
- if (initialSnapshot && initialSnapshot.fingerprint === current.fingerprint
- && root?.clientWidth === initialSnapshot.width && root.clientHeight === initialSnapshot.height) {
- if (Math.abs(root.scrollTop - initialSnapshot.offset) > 1) native.scrollToOffset(initialSnapshot.offset, { behavior: "auto" })
- } else {
- if (initialSnapshot) {
- native.setOptions({ ...native.options, initialMeasurementsCache: [] })
- native.measure()
- }
- native.scrollToIndex(0, { align: "start" })
- }
- }, [initialSnapshot])
+ native.scrollToIndex(0, { align: "start" })
+ }, [])
// eslint-disable-next-line react-hooks/incompatible-library -- supported TanStack Virtual imperative adapter
const virtualizer = useVirtualizer({
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
@@ -117,9 +89,7 @@ function ForumPostListOwner({ posts, loading, observation, positionScope, hasMor
getItemKey,
overscan: OVERSCAN,
rangeExtractor: forumRangeExtractor,
- initialRect: initialSnapshot ? { width: initialSnapshot.width, height: initialSnapshot.height } : { width: 0, height: 800 },
- initialOffset: initialSnapshot?.offset ?? 0,
- initialMeasurementsCache: initialSnapshot?.measurements ?? [],
+ initialRect: { width: 0, height: 800 },
onChange: native => { initializePosition(native); inspectPosition(native) },
})
useLayoutEffect(() => {
diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsx
index 82ea54594..a9c134327 100644
--- a/src/web/src/components/community/channels/forum-surface.tsx
+++ b/src/web/src/components/community/channels/forum-surface.tsx
@@ -1,7 +1,7 @@
"use client"
import { useMemo, useRef } from "react"
-import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import type { NewForumThread } from "../messages/create-forum-thread"
@@ -34,8 +34,8 @@ export function ForumSurface({ serverId, forumChannelId, routeTag, onSelectTag,
const feed = useForumFeed(serverId, forumChannelId, { routeTag, onSelectTag })
const readState = useConversationEntry(feed.selectionReady ? { channelId: forumChannelId, serverId, tag: feed.tag === "All" ? null : feed.tag } : null)
const proof = readState.resource?.proof
- const positionScope = useMemo<VirtualListPositionScope | undefined>(() => readState.canRead && proof
- ? { proof, kind: "forum", tag: feed.tag === "All" ? null : feed.tag } : undefined, [readState.canRead, proof, feed.tag])
+ const positionScope = useMemo<ConversationListScope | undefined>(() => readState.canRead && proof
+ ? { proof, tag: feed.tag === "All" ? null : feed.tag } : undefined, [readState.canRead, proof, feed.tag])
const [scrollRootEl, setScrollRootEl] = useAtom(useCreateAtom<HTMLDivElement | null>(null))
const retryScope = JSON.stringify([forumChannelId, feed.tag])
const [retryAttempt, setRetryAttempt] = useAtom(useCreateAtom<{ scope: string } | null>(null))
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index c6e755bc0..2c72d167e 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -21,7 +21,7 @@ import { tagColorClassName, tagColorStyle } from "@/lib/community/tag-color"
import { cn } from "@/lib/utils"
import { FORUM_ARCHIVE_TAG } from "@alook/shared"
import { ForumPostList } from "./forum-post-list"
-import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
@@ -130,7 +130,7 @@ export function ForumView({
onScrollRoot, positionScope,
}: {
forumChannelId: string
- positionScope?: VirtualListPositionScope
+ positionScope?: ConversationListScope
members: Member[]
mentionCandidates?: ComposerProps["mentionCandidates"]
observation?: import("@/lib/observability/regions").ResourceObservation
diff --git a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
index c8570ba38..f76fbedee 100644
--- a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
@@ -1,4 +1,5 @@
import React from "react"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import { act, fireEvent } from "@/test/react-dom-harness"
import { renderCommunity as render } from "@/test/community-owner-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -46,7 +47,10 @@ vi.mock("@/components/community/channels/channel-shell", () => ({
}) => React.createElement(React.Fragment, null, header, body, panels, dialogs),
}))
vi.mock("@/components/community/messages/composer", () => ({
- Composer: vi.fn(() => null),
+ Composer: vi.fn(function ComposerProbe() {
+ const active = React.useContext(ConversationActivityContext)
+ return React.createElement("div", { "data-testid": "community-composer-input", "data-composer-active": String(active) })
+ }),
}))
vi.mock("@/components/community/messages/conversation-footer-shell", () => ({
ConversationFooterSlotProvider: ({ children }: { children: React.ReactNode }) => children,
@@ -110,6 +114,7 @@ vi.mock("@/hooks/community/use-community-ws", () => ({
function feed(overrides: Record<string, unknown> = {}) {
return {
+ navigationBlocked: false,
messages: [],
isLoading: false,
isError: false,
@@ -477,3 +482,63 @@ describe("TextChannelSurface header hierarchy", () => {
expect(mockedChannelHeader.mock.calls.at(-1)?.[0]).not.toHaveProperty("typingUsers")
})
})
+
+it.each([false, true])("projects current pending on the existing text surface and keeps embedded=%s ownership", async embedded => {
+ const props = {
+ channelId: "channel_1", serverId: "server_1", serverParam: "server_1", channelName: "general",
+ viewer: { id: "viewer_1", name: "Viewer", avatar: "V" }, canManagePins: false, anchorMessageId: null,
+ notificationLevel: "default" as const, onSetNotificationLevel: vi.fn(), composerMembers: [], channelRefCandidates: [],
+ memberPanelProps: { members: [] }, manageMembersDialog: null, uiHandlers: {}, onOpenThread: vi.fn(),
+ onOpenProfile: vi.fn(), resolveUserName: (id: string) => id, embedded,
+ }
+ let renderer: ReturnType<typeof render> | undefined
+ let original: Element | null = null
+ for (const state of ["pending", "ready", "empty", "error"] as const) {
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ positionDataState: state, targetPositionDataState: state, isLoading: state === "pending" }))
+ await act(async () => {
+ if (renderer) renderer.rerender(React.createElement(TextChannelSurface, props))
+ else renderer = render(React.createElement(TextChannelSurface, props))
+ })
+ const body = renderer!.container.querySelector('[data-slot="community-conversation-surface"]')!
+ if (original) expect(body).toBe(original)
+ original = body
+ expect(body.tagName).toBe(embedded ? "DIV" : "MAIN")
+ expect(body).toHaveAttribute("data-channel-id", "channel_1")
+ expect(body).toHaveAttribute("data-community-conversation-subtype", "text")
+ if (!embedded && state === "pending") {
+ expect(body).toHaveAttribute("aria-busy", "true")
+ expect(body).toHaveAttribute("aria-label", "Loading conversation")
+ if (!embedded) expect(body).toHaveAttribute("data-testid", "community-conversation-resolution-pending")
+ } else {
+ expect(body).not.toHaveAttribute("aria-busy")
+ expect(body).not.toHaveAttribute("aria-label")
+ }
+ if (embedded || state !== "pending") expect(body).not.toHaveAttribute("data-testid")
+ expect(mockedChannelHeader.mock.calls.at(-1)?.[0]).toMatchObject({ channel: "general", kind: "text" })
+ expect(mockedConversationFooterShell).toHaveBeenCalled()
+ }
+ renderer!.unmount()
+})
+
+it.each([false, true])("retains the text composer shell while qualifying its inherited input activity (embedded=%s)", async embedded => {
+ const props = { channelId: "channel_1", serverId: "server_1", serverParam: "server_1", channelName: "general",
+ viewer: { id: "viewer_1", name: "Viewer", avatar: "V" }, canManagePins: false, anchorMessageId: null,
+ notificationLevel: "default" as const, onSetNotificationLevel: vi.fn(), composerMembers: [], channelRefCandidates: [],
+ memberPanelProps: { members: [] }, manageMembersDialog: null, uiHandlers: {}, onOpenThread: vi.fn(),
+ onOpenProfile: vi.fn(), resolveUserName: (id: string) => id, embedded }
+ let view: ReturnType<typeof render> | undefined
+ let original: Element | null = null
+ for (const [routeActive, navigationBlocked] of [[true, true], [true, false], [false, false], [true, true], [true, false]]) {
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ navigationBlocked }))
+ const node = React.createElement(ConversationActivityContext.Provider, { value: routeActive }, React.createElement(TextChannelSurface, props))
+ await act(async () => { if (view) view.rerender(node); else view = render(node) })
+ const shell = view!.getByTestId("community-composer-shell")
+ const input = view!.getByTestId("community-composer-input")
+ if (original) expect(input).toBe(original)
+ original = input
+ expect(input).toBeVisible()
+ expect(input).toHaveAttribute("data-composer-active", String(routeActive && !navigationBlocked))
+ expect(shell.hasAttribute("inert")).toBe(!routeActive || navigationBlocked)
+ }
+ view!.unmount()
+})
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index b4bf780fd..37c4187d7 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -23,6 +23,7 @@ import type { FileAttachment, ImagePreview } from "@/lib/community/models/messag
import type { OpenProfile } from "@/components/community/social/profile-types"
import type { RightPanel } from "@/components/community/shell/panel-types"
import { tid } from "@/lib/community/testids"
+import { ConversationActivityContext, useConversationActivity } from "@/contexts/community/conversation-activity"
export function TextChannelSurface({
channelId,
@@ -72,6 +73,7 @@ export function TextChannelSurface({
embedded?: boolean
}) {
const breakpoint = useBreakpoint()
+ const routeActive = useConversationActivity()
const [rightPanel, setRightPanel] = useAtom(useCreateAtom<RightPanel>(null))
const mentionInsertion = useAuthorMentionInsertion({
members: composerMembers,
@@ -95,6 +97,7 @@ export function TextChannelSurface({
setRightPanel((current) => current === panel ? null : panel)
}
const Body = embedded ? "div" : "main"
+ const inputActive = routeActive && feed.navigationBlocked === false
return (
<MessageChannelController
@@ -127,6 +130,10 @@ export function TextChannelSurface({
<Body
data-slot="community-conversation-surface"
data-channel-id={channelId}
+ data-testid={!embedded && feed.positionDataState === "pending" ? tid.conversationResolutionPending : undefined}
+ aria-busy={!embedded && feed.positionDataState === "pending" ? true : undefined}
+ aria-label={!embedded && feed.positionDataState === "pending" ? "Loading conversation" : undefined}
+ data-community-conversation-subtype="text"
className="flex min-h-0 min-w-0 flex-1 flex-col"
>
<ConversationFooterSlotProvider>
@@ -176,22 +183,25 @@ export function TextChannelSurface({
<ConversationFooterShell
data-onboarding-target="channel-composer"
data-testid={tid.channelComposerShell}
+ inert={!inputActive}
>
- <Composer
- ref={mentionInsertion.composerRef}
- channel={channelName}
- context="channel"
- members={composerMembers}
- mentionCandidates={composerMentionCandidates}
- channelRefCandidates={channelRefCandidates}
- sendContract="accepted"
- onAcceptSend={controller.acceptMessage}
- onTyping={controller.handleTyping}
- replyingTo={controller.replyTo ?? undefined}
- onCancelReply={() => controller.setReplyTo(null)}
- autoFocus={breakpoint === "desktop" && !embedded}
- draftKey={`${serverId}/${channelId}`}
- />
+ <ConversationActivityContext value={inputActive}>
+ <Composer
+ ref={mentionInsertion.composerRef}
+ channel={channelName}
+ context="channel"
+ members={composerMembers}
+ mentionCandidates={composerMentionCandidates}
+ channelRefCandidates={channelRefCandidates}
+ sendContract="accepted"
+ onAcceptSend={controller.acceptMessage}
+ onTyping={controller.handleTyping}
+ replyingTo={controller.replyTo ?? undefined}
+ onCancelReply={() => controller.setReplyTo(null)}
+ autoFocus={breakpoint === "desktop" && !embedded}
+ draftKey={`${serverId}/${channelId}`}
+ />
+ </ConversationActivityContext>
</ConversationFooterShell>
</ConversationFooterSlotProvider>
</Body>
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 bdcb672be..c71504bb6 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
@@ -1,4 +1,5 @@
import React from "react"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import { act, fireEvent, render } from "@/test/react-dom-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { ThreadChannelSurface } from "./thread-channel-surface"
@@ -61,7 +62,10 @@ vi.mock("@/components/community/shell/community-panel", () => ({
CommunityPanel: vi.fn(() => null),
}))
vi.mock("@/components/community/messages/composer", () => ({
- Composer: vi.fn(() => null),
+ Composer: vi.fn(function ComposerProbe() {
+ const active = React.useContext(ConversationActivityContext)
+ return React.createElement("div", { "data-testid": "community-composer-input", "data-composer-active": String(active) })
+ }),
ComposerSkeleton: vi.fn(() => null),
}))
vi.mock("@/components/community/messages/conversation-footer-shell", () => ({
@@ -140,6 +144,7 @@ const mockedUseClaimThreadOpenerReadHandoff = vi.mocked(useClaimThreadOpenerRead
function feed(overrides: Record<string, unknown> = {}) {
return {
+ navigationBlocked: false,
messages: [{ id: "message_1", type: "chat" }],
isLoading: false,
isError: false,
@@ -490,3 +495,51 @@ describe("ThreadChannelSurface ownership", () => {
})
})
+
+it.each([false, true])("projects current pending on the existing thread surface and keeps embedded=%s ownership", async embedded => {
+ let renderer: ReturnType<typeof render> | undefined
+ let original: Element | null = null
+ for (const state of ["pending", "ready", "empty", "error"] as const) {
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ positionDataState: state, targetPositionDataState: state, isLoading: state === "pending" }))
+ await act(async () => {
+ if (renderer) renderer.rerender(renderSurface({ embedded }))
+ else renderer = render(renderSurface({ embedded }))
+ })
+ const body = renderer!.container.querySelector('[data-slot="community-conversation-surface"]')!
+ if (original) expect(body).toBe(original)
+ original = body
+ expect(body.tagName).toBe(embedded ? "DIV" : "MAIN")
+ expect(body).toHaveAttribute("data-channel-id", "thread_1")
+ expect(body).toHaveAttribute("data-community-conversation-subtype", "thread")
+ if (!embedded && state === "pending") {
+ expect(body).toHaveAttribute("aria-busy", "true")
+ expect(body).toHaveAttribute("aria-label", "Loading thread")
+ if (!embedded) expect(body).toHaveAttribute("data-testid", "community-conversation-resolution-pending")
+ } else {
+ expect(body).not.toHaveAttribute("aria-busy")
+ expect(body).not.toHaveAttribute("aria-label")
+ }
+ if (embedded || state !== "pending") expect(body).not.toHaveAttribute("data-testid")
+ expect(mockedChannelHeader.mock.calls.at(-1)?.[0]).toMatchObject({ kind: "thread" })
+ expect(mockedConversationFooterShell).toHaveBeenCalled()
+ }
+ renderer!.unmount()
+})
+
+it.each([false, true])("retains the held child composer shell while qualifying input activity (embedded=%s)", async embedded => {
+ let view: ReturnType<typeof render> | undefined
+ let original: Element | null = null
+ for (const [routeActive, navigationBlocked] of [[true, true], [true, false], [false, false], [true, true], [true, false]]) {
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ navigationBlocked }))
+ const node = React.createElement(ConversationActivityContext.Provider, { value: routeActive }, renderSurface({ embedded }))
+ await act(async () => { if (view) view.rerender(node); else view = render(node) })
+ const shell = view!.getByTestId("community-composer-shell")
+ const input = view!.getByTestId("community-composer-input")
+ if (original) expect(input).toBe(original)
+ original = input
+ expect(input).toBeVisible()
+ expect(input).toHaveAttribute("data-composer-active", String(routeActive && !navigationBlocked))
+ expect(shell.hasAttribute("inert")).toBe(!routeActive || navigationBlocked)
+ }
+ view!.unmount()
+})
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 1d420c164..2aed9cddf 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -27,6 +27,7 @@ import type { OpenProfile } from "@/components/community/social/profile-types"
import type { RightPanel } from "@/components/community/shell/panel-types"
import type { ChannelMemberPanelProps } from "@/components/community/members/channel-member-view-model"
import { tid } from "@/lib/community/testids"
+import { ConversationActivityContext, useConversationActivity } from "@/contexts/community/conversation-activity"
import {
useClaimThreadOpenerReadHandoff,
type ThreadOpenerReadHandoff,
@@ -127,6 +128,8 @@ export function ThreadChannelSurface({
threadsEnabled: rightPanel === "threads",
})
const displayName = localName ?? channelName
+ const routeActive = useConversationActivity()
+ const inputActive = routeActive && feed.navigationBlocked === false
const Body = embedded ? "div" : "main"
const compactActions = !!splitActions && !layoutPending
@@ -218,6 +221,10 @@ export function ThreadChannelSurface({
<Body
data-slot="community-conversation-surface"
data-channel-id={channelId}
+ data-testid={!embedded && controller.feed.positionDataState === "pending" ? tid.conversationResolutionPending : undefined}
+ aria-busy={!embedded && controller.feed.positionDataState === "pending" ? true : undefined}
+ aria-label={!embedded && controller.feed.positionDataState === "pending" ? "Loading thread" : undefined}
+ data-community-conversation-subtype="thread"
className="flex min-h-0 min-w-0 flex-1 flex-col"
>
<ConversationFooterSlotProvider>
@@ -268,22 +275,25 @@ export function ThreadChannelSurface({
<ConversationFooterShell
data-onboarding-target="channel-composer"
data-testid={tid.channelComposerShell}
+ inert={!inputActive}
>
- <Composer
- ref={mentionInsertion.composerRef}
- channel={displayName}
- context="thread"
- members={composerMembers}
- mentionCandidates={composerMentionCandidates}
- channelRefCandidates={channelRefCandidates}
- sendContract="accepted"
- onAcceptSend={controller.acceptMessage}
- onTyping={controller.handleTyping}
- replyingTo={controller.replyTo ?? undefined}
- onCancelReply={() => controller.setReplyTo(null)}
- autoFocus={breakpoint === "desktop"}
- draftKey={`${serverId}/${channelId}`}
- />
+ <ConversationActivityContext value={inputActive}>
+ <Composer
+ ref={mentionInsertion.composerRef}
+ channel={displayName}
+ context="thread"
+ members={composerMembers}
+ mentionCandidates={composerMentionCandidates}
+ channelRefCandidates={channelRefCandidates}
+ sendContract="accepted"
+ onAcceptSend={controller.acceptMessage}
+ onTyping={controller.handleTyping}
+ replyingTo={controller.replyTo ?? undefined}
+ onCancelReply={() => controller.setReplyTo(null)}
+ autoFocus={breakpoint === "desktop"}
+ draftKey={`${serverId}/${channelId}`}
+ />
+ </ConversationActivityContext>
</ConversationFooterShell>
</ConversationFooterSlotProvider>
</Body>
diff --git a/src/web/src/components/community/machines/machine-list.readiness.dom.test.tsx b/src/web/src/components/community/machines/machine-list.readiness.dom.test.tsx
index d7b2d8f4f..82b48881f 100644
--- a/src/web/src/components/community/machines/machine-list.readiness.dom.test.tsx
+++ b/src/web/src/components/community/machines/machine-list.readiness.dom.test.tsx
@@ -27,7 +27,7 @@ function deferred<T>() {
it.each([false, true])("keeps the real empty target unknown until its list is available (restoring=%s)", async restoring => {
const { client } = await createCommunityQueryOwner()
- const primary = deferred<{ machines: [] }>()
+ const primary = deferred<{ machines: []; complete: true }>()
const observations = deferred<{ quotas: []; machineCapacity: { plan: { id: string; displayName: string }; isFounder: boolean; limit: number; ownedCount: number; onlineCount: number } }>()
load.mockImplementation((url: string) => url.endsWith("view=list") ? primary.promise : observations.promise)
const node = (restore: boolean) => <CommunityTestProvider client={client}>
@@ -43,7 +43,7 @@ it.each([false, true])("keeps the real empty target unknown until its list is av
await waitFor(() => expect(load).toHaveBeenCalledWith("/api/community/machines?view=list", expect.anything()))
expect(client.getQueryState(communityKeys.machines())).toMatchObject({ status: "pending", fetchStatus: "fetching", data: undefined })
expect(view.queryByText("No machines yet")).toBeNull()
- await act(async () => { primary.resolve({ machines: [] }) })
+ await act(async () => { primary.resolve({ machines: [], complete: true }) })
expect(await view.findByText("No machines yet")).toBeVisible()
expect(view.getByRole("button", { name: "Connect a machine" })).toBeDisabled()
await act(async () => { observations.resolve({ quotas: [], machineCapacity: { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 0, onlineCount: 0 } }) })
@@ -52,7 +52,7 @@ it.each([false, true])("keeps the real empty target unknown until its list is av
it.each([false, true])("shows a complete cached empty list while its capacity remains unknown (restoring=%s)", async restoring => {
const { client } = await createCommunityQueryOwner()
- const primary = deferred<{ machines: [] }>()
+ const primary = deferred<{ machines: []; complete: true }>()
const observations = deferred<{ quotas: [] }>()
client.setQueryData(communityKeys.machines(), { machines: [], complete: true, observed: false, source: "restored_idb" })
load.mockImplementation((url: string) => url.endsWith("view=list") ? primary.promise : observations.promise)
@@ -69,6 +69,6 @@ it.each([false, true])("shows a complete cached empty list while its capacity re
view.rerender(node(false))
await waitFor(() => expect(load).toHaveBeenCalledWith("/api/community/machines?view=list", expect.anything()))
expect(view.getByText("No machines yet")).toBe(empty)
- await act(async () => { primary.resolve({ machines: [] }); observations.resolve({ quotas: [] }) })
+ await act(async () => { primary.resolve({ machines: [], complete: true }); observations.resolve({ quotas: [] }) })
expect(view.getByText("No machines yet")).toBe(empty)
})
diff --git a/src/web/src/components/community/members/add-members-dialog.dom.test.tsx b/src/web/src/components/community/members/add-members-dialog.dom.test.tsx
index 7161e9051..73410f5cd 100644
--- a/src/web/src/components/community/members/add-members-dialog.dom.test.tsx
+++ b/src/web/src/components/community/members/add-members-dialog.dom.test.tsx
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, CommunityMembersReadSchema } from "@alook/shared"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent, render, screen, waitFor, within } from "@/test/react-dom-harness"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
@@ -55,6 +56,11 @@ async function fixture() {
const roster = new Map<string, Set<string>>([
["thread", new Set(["viewer"])], ["other", new Set(["viewer"])],
])
+ const memberRead = (channelId: string, relation: "access" | "notify", rows: ChannelMember[]) => CommunityMembersReadSchema.parse({
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId, relation,
+ members: rows.map(row => ({ channelId, userId: row.userId, relation, source: relation === "notify" ? row.userId === "viewer" ? "spoke" : "added" : row.source, isCreator: row.isCreator, role: row.role, memberId: row.id })),
+ profiles: rows.map(row => ({ id: row.userId, name: row.name, discriminator: row.discriminator, avatar: null, avatarVersion: row.avatarVersion, statusEmoji: row.statusEmoji, statusText: row.statusText })),
+ })
const requests: Array<{ channelId: string; userId: string; signal: AbortSignal }> = []
let nextGate = deferred()
mocks.apiFetch.mockImplementation((url: string, options?: RequestInit) => {
@@ -62,7 +68,7 @@ async function fixture() {
return Promise.resolve({ members: parentMembers, hasMore: false, limit: 50, total: 3 })
}
if (url === "/api/community/channels/parent/members?relation=access") {
- return Promise.resolve({ members: parentMembers })
+ return Promise.resolve(memberRead("parent", "access", parentMembers))
}
const match = /^\/api\/community\/channels\/(thread|other)\/(members|participants)(?:\?relation=(?:access|notify))?$/.exec(url)
if (!match) throw new Error(`Unexpected request: ${url}`)
@@ -76,9 +82,7 @@ async function fixture() {
return { success: true }
})
}
- return Promise.resolve({ members: parentMembers
- .filter((member) => roster.get(channelId)!.has(member.userId))
- .map((member) => ({ ...member, source: member.userId === "viewer" ? "spoke" : "added" })) })
+ return Promise.resolve(memberRead(channelId, "notify", parentMembers.filter(member => roster.get(channelId)!.has(member.userId))))
})
const element = (channelId = "thread") => <CommunityTestProvider client={owner.client} registry={owner.registry}>
<Harness key={channelId} channelId={channelId} />
diff --git a/src/web/src/components/community/messages/composer-file-utils.ts b/src/web/src/components/community/messages/composer-file-utils.ts
index b5e02d11f..032ab32c5 100644
--- a/src/web/src/components/community/messages/composer-file-utils.ts
+++ b/src/web/src/components/community/messages/composer-file-utils.ts
@@ -1,5 +1,6 @@
-import type { PendingFile } from "@/hooks/use-file-attachments"
+import type { PendingFile, useFileAttachments } from "@/hooks/use-file-attachments"
import type { SendAttachment } from "@/lib/community/models/message"
+import type { ComposerViewProps } from "./composer-view"
export const LONG_PASTE_ATTACHMENT_THRESHOLD = 1_000
@@ -52,3 +53,47 @@ export function clipboardFiles(
}
return files
}
+
+type AttachmentViewHandlers = Pick<ComposerViewProps,
+ "onDragEnter" | "onDragLeave" | "onDragOver" | "onDrop" |
+ "onFileSelect" | "removePendingFile" | "onUploadFile">
+type AttachmentInputOwner = Pick<ReturnType<typeof useFileAttachments>,
+ "handleDragEnter" | "handleDragLeave" | "handleDragOver" | "handleDrop" |
+ "handleFileSelect" | "removePendingFile" | "fileInputRef">
+
+export function createComposerAttachmentInputHandlers(
+ isActive: () => boolean,
+ attachments: AttachmentInputOwner,
+ focusAfterDrop: () => void,
+): AttachmentViewHandlers {
+ const guardDrag = (handler: ComposerViewProps["onDrop"]): ComposerViewProps["onDrop"] => (event) => {
+ if (!isActive()) {
+ event.preventDefault()
+ event.stopPropagation()
+ return
+ }
+ handler(event)
+ }
+ return {
+ onDragEnter: guardDrag(attachments.handleDragEnter),
+ onDragLeave: attachments.handleDragLeave,
+ onDragOver: guardDrag(attachments.handleDragOver),
+ onDrop: guardDrag((event) => {
+ attachments.handleDrop(event)
+ focusAfterDrop()
+ }),
+ onFileSelect: (event) => {
+ if (!isActive()) {
+ event.currentTarget.value = ""
+ return
+ }
+ attachments.handleFileSelect(event)
+ },
+ removePendingFile: (index) => {
+ if (isActive()) attachments.removePendingFile(index)
+ },
+ onUploadFile: () => {
+ if (isActive()) attachments.fileInputRef.current?.click()
+ },
+ }
+}
diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
index 26ba64916..57f3392f7 100644
--- a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
@@ -4,6 +4,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { USE_SERVER_DEFAULT } from "@alook/shared"
import { act, fireEvent, screen, setupUser, waitFor } from "@/test/react-dom-harness"
import { renderCommunity as render } from "@/test/community-owner-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { conversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
import { readComposerDraft, writeComposerDraft } from "@/lib/community/composer-draft"
import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import type { Member } from "@/lib/community/models/people"
@@ -11,6 +14,7 @@ import { CommunityMentionList, ChannelRefList } from "./composer-suggestion-popu
import type { ComposerHandle, ComposerProps } from "./composer-types"
import { useComposerController } from "./use-composer-controller"
import { TextChannelSurface } from "../channels/text-channel-surface"
+import { ThreadChannelSurface } from "../channels/thread-channel-surface"
import { NATIVE_MOBILE_BACK_EVENT, useNativeMobileBack } from "@/hooks/community/use-native-mobile-back"
import type { MessageChannelControllerValue } from "./message-channel-controller"
@@ -26,17 +30,22 @@ vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))
const surfaces = vi.hoisted(() => ({
breakpoint: "desktop" as "unknown" | "mobile" | "desktop",
+ navigationBlocked: false,
probes: new Map<string, { current: ReturnType<typeof useComposerController> | null }>(),
}))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => surfaces.breakpoint }))
vi.mock("@/hooks/community/use-channel-message-feed", () => ({
- useChannelMessageFeed: () => ({ messages: [], isLoading: false, readSnapshotFetching: false, anchorInCache: true }),
+ useChannelMessageFeed: () => ({ messages: [], isLoading: false, readSnapshotFetching: false, anchorInCache: true, navigationBlocked: surfaces.navigationBlocked }),
}))
vi.mock("@/components/community/channels/channel-header", () => ({ ChannelHeader: () => null }))
vi.mock("@/components/community/channels/channel-shell", () => ({ ChannelShell: ({ body }: { body: ReactNode }) => body }))
vi.mock("@/components/community/shell/community-panel", () => ({ CommunityPanel: () => null }))
vi.mock("@/components/community/messages/message-list", () => ({ MessageList: () => null }))
vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))
+vi.mock("@/hooks/community/thread-opener-read-handoff", () => ({ useClaimThreadOpenerReadHandoff: () => {} }))
+vi.mock("@/components/community/messages/thread-opener", () => ({ ThreadOpener: () => null }))
+vi.mock("@/contexts/community/module-route", () => ({ useCommunityRouter: () => ({ push: vi.fn(), replace: vi.fn() }) }))
+vi.mock("@/hooks/community/mutations", () => ({ useToggleReactionApi: () => vi.fn() }))
vi.mock("@/components/community/messages/composer", async () => {
const { forwardRef } = await import("react")
return {
@@ -48,8 +57,8 @@ vi.mock("@/components/community/messages/composer", async () => {
}
})
vi.mock("@/components/community/messages/message-channel-controller", () => ({
- MessageChannelController: ({ children }: { children: (value: MessageChannelControllerValue) => ReactNode }) => children({
- feed: {} as MessageChannelControllerValue["feed"],
+ MessageChannelController: ({ children, feed }: { children: (value: MessageChannelControllerValue) => ReactNode; feed: MessageChannelControllerValue["feed"] }) => children({
+ feed,
pinnedIds: new Set(), replyTo: null, setReplyTo: vi.fn(),
scrollTargetId: null, setScrollTargetId: vi.fn(), consumeScrollTarget: vi.fn(),
contextTarget: null, setContextTarget: vi.fn(), openContextSeq: vi.fn(),
@@ -115,6 +124,96 @@ function BackListener({ replacePath }: { replacePath: (path: string) => void })
}
describe("composer suggestion focus with installed TipTap", () => {
+ it.each([
+ ["text", false], ["text", true], ["thread", false], ["thread", true],
+ ] as const)("keeps a %s editor and draft through window qualification with embedded=%s", async (kind, embedded) => {
+ const channelId = kind === "text" ? "parent" : "child"
+ const key = `server-one/${channelId}`
+ const draft = { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Keep this draft" }] }] }
+ writeComposerDraft(`viewer:${key}`, draft)
+ const node = (routeActive = true) => <ConversationActivityContext value={routeActive}>
+ {kind === "text" ? <TextChannelSurface {...textSurfaceProps} embedded={embedded} /> : <ThreadChannelSurface
+ {...textSurfaceProps} channelId="child" channelName="child" parentChannelId="parent" parentMessageId="opener"
+ parentIsForum={false} canRenameThread={false} onNavigateParent={vi.fn()} onOpenChild={vi.fn()} embedded={embedded}
+ />}
+ </ConversationActivityContext>
+ surfaces.navigationBlocked = true
+ const view = render(node())
+ const probe = surfaces.probes.get(key)!
+ const editor = await editorOf(probe)
+ const input = editor.view.dom
+ const footer = screen.getByTestId("community-composer-shell")
+ await waitFor(() => expect(editor.getJSON()).toEqual(draft))
+ expect(input.getAttribute("contenteditable")).toBe("false")
+ expect(footer).toBeVisible()
+ expect(footer.hasAttribute("inert")).toBe(true)
+ expect(document.activeElement).not.toBe(input)
+ expect(view.container.querySelectorAll('[contenteditable="true"]')).toHaveLength(0)
+
+ surfaces.navigationBlocked = false
+ view.rerender(node())
+ expect(editor.isEditable).toBe(true)
+ expect(footer.hasAttribute("inert")).toBe(false)
+ await type(editor, " + edit")
+ const edited = editor.getJSON()
+ const retainedEmoji = probe.current!.onEmojiPick
+ for (const [routeActive, blocked] of [[true, true], [false, false], [true, true], [true, false]] as const) {
+ surfaces.navigationBlocked = blocked
+ view.rerender(node(routeActive))
+ const active = routeActive && !blocked
+ expect(probe.current!.editor).toBe(editor)
+ expect(editor.view.dom).toBe(input)
+ expect(screen.getByTestId("community-composer-shell")).toBe(footer)
+ expect(footer).toBeVisible()
+ expect(editor.isEditable).toBe(active)
+ expect(input.getAttribute("contenteditable")).toBe(String(active))
+ expect(footer.hasAttribute("inert")).toBe(!active)
+ if (!active) {
+ await act(async () => { retainedEmoji("🙂") })
+ await waitFor(() => expect(editor.isFocused).toBe(false))
+ expect(view.container.querySelectorAll('[contenteditable="true"]')).toHaveLength(0)
+ }
+ expect(editor.getJSON()).toEqual(edited)
+ expect(readComposerDraft(`viewer:${key}`)).toEqual(edited)
+ }
+ await act(async () => { probe.current!.onEmojiPick("🙂") })
+ expect(editor.getText()).toContain("🙂")
+ })
+
+ it("defers a canonical reply mention until active and applies it once to the retained editor", async () => {
+ const owner = await createCommunityQueryOwner()
+ await seedConversationEntry(owner.client, conversationEntryFixture())
+ const probeRef: Probe = { current: null }
+ const reply = { id: "m1", authorId: "peer", authorName: "Peer", text: "Body" }
+ const node = (active: boolean) => <CommunityTestProvider client={owner.client} registry={owner.registry}>
+ <ConversationActivityContext value={active}>
+ <Harness {...props} probeRef={probeRef} draftKey="deferred-reply" replyingTo={reply} />
+ </ConversationActivityContext>
+ </CommunityTestProvider>
+ const view = render(node(false))
+ const editor = await editorOf(probeRef)
+ const original = editor.getJSON()
+ const mentions = () => {
+ const ids: string[] = []
+ editor.state.doc.descendants((node) => { if (node.type.name === "mention") ids.push(node.attrs.id) })
+ return ids
+ }
+ expect(mentions()).toEqual([])
+ expect(editor.isFocused).toBe(false)
+ view.rerender(node(false))
+ expect(editor.getJSON()).toEqual(original)
+ view.rerender(node(true))
+ await waitFor(() => expect(mentions()).toEqual(["peer"]))
+ await waitFor(() => expect(editor.isFocused).toBe(true))
+ const replied = editor.getJSON()
+ for (const active of [true, false, true]) {
+ view.rerender(node(active))
+ expect(probeRef.current!.editor).toBe(editor)
+ expect(mentions()).toEqual(["peer"])
+ expect(editor.getJSON()).toEqual(replied)
+ }
+ })
+
it("retains the editor and draft while background focus and submission are disabled", async () => {
const probeRef: Probe = { current: null }, handle = createRef<ComposerHandle>()
const accept = vi.fn(() => true)
@@ -143,6 +242,7 @@ describe("composer suggestion focus with installed TipTap", () => {
beforeEach(() => {
localStorage.clear()
surfaces.breakpoint = "desktop"
+ surfaces.navigationBlocked = false
surfaces.probes.clear()
const rect = new DOMRect(10, 20, 1, 18)
Object.defineProperty(Range.prototype, "getBoundingClientRect", { configurable: true, value: () => rect })
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
index a1c1f4e4c..b2fb1f77a 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
@@ -1,3 +1,5 @@
+import { messageSeedFixture } from "@/test/community-resource-fixtures"
+import { communityUserProfilePatch, writeCommunityProfilePatches } from "@/lib/community/profile-seed"
import React from "react"
import { act } from "@/test/react-dom-harness"
import { render as renderDom } from "@/test/react-dom-harness"
@@ -114,6 +116,7 @@ const feed = {
messages: [{ id: "m1", seq: 1, type: "chat", authorName: "Alice", content: "hi" }],
pinned: [],
isError: false,
+ navigationBlocked: false,
} as MessageChannelControllerProps["feed"]
function props(overrides: Partial<MessageChannelControllerProps> = {}): Omit<MessageChannelControllerProps, "children"> {
@@ -135,7 +138,7 @@ function props(overrides: Partial<MessageChannelControllerProps> = {}): Omit<Mes
let latest: MessageChannelControllerValue
function Probe({ value }: { value: Omit<MessageChannelControllerProps, "children"> }) {
- React.useLayoutEffect(() => { ingestMessages(fixtureOwner.registry, value.channelId, value.feed.messages) }, [value.channelId, value.feed.messages])
+ React.useLayoutEffect(() => { ingestMessages(fixtureOwner.registry, value.channelId, messageSeedFixture(value.channelId, value.feed.messages)) }, [value.channelId, value.feed.messages])
const controller = useMessageChannelController(value)
React.useLayoutEffect(() => { latest = controller }, [controller])
return null
@@ -146,7 +149,7 @@ function PassiveActionProbe({
}: {
value: Omit<MessageChannelControllerProps, "children">
}) {
- React.useLayoutEffect(() => { ingestMessages(fixtureOwner.registry, value.channelId, value.feed.messages) }, [value.channelId, value.feed.messages])
+ React.useLayoutEffect(() => { ingestMessages(fixtureOwner.registry, value.channelId, messageSeedFixture(value.channelId, value.feed.messages)) }, [value.channelId, value.feed.messages])
const controller = useMessageChannelController(value)
React.useLayoutEffect(() => { latest = controller }, [controller])
React.useEffect(() => { controller.messageActions.onReply("probe") })
@@ -230,6 +233,45 @@ describe("useMessageChannelController", () => {
expect(mocks.apiFetch).not.toHaveBeenCalled()
})
+ it("rejects new send admission while the current feed window is blocked without consuming reply or uploads", () => {
+ const reply = { id: "reply", authorName: "Alice", text: "keep reply" }
+ rtlRender(React.createElement(Probe, { value: props({ feed: { ...feed, navigationBlocked: true } }) }))
+ act(() => latest.setReplyTo(reply))
+ let accepted = true
+ act(() => { accepted = latest.acceptMessage("keep draft", [{ file: {} as File }]) })
+ expect(accepted).toBe(false)
+ expect(mocks.accept).not.toHaveBeenCalled()
+ expect(mocks.run).not.toHaveBeenCalled()
+ expect(mocks.uploadMutation).not.toHaveBeenCalled()
+ expect(mocks.sendMutation).not.toHaveBeenCalled()
+ expect(latest.replyTo).toEqual(reply)
+ expect(latest.localSubmitVersion).toBe(0)
+ })
+
+ it("rejects a retained earlier send callback after its current committed feed loses readiness", () => {
+ const value = props()
+ const view = rtlRender(React.createElement(Probe, { value }))
+ const earlier = latest.acceptMessage
+ view.rerender(React.createElement(Probe, { value: { ...value, feed: { ...feed, navigationBlocked: true } } }))
+ let accepted = true
+ act(() => { accepted = earlier("keep draft") })
+ expect(accepted).toBe(false)
+ expect(mocks.accept).not.toHaveBeenCalled()
+ expect(mocks.run).not.toHaveBeenCalled()
+ })
+
+ it("keeps an already accepted command under its original guards when the feed later blocks new sends", async () => {
+ const value = props()
+ const view = rtlRender(React.createElement(Probe, { value }))
+ act(() => { expect(latest.acceptMessage("accepted draft")).toBe(true) })
+ const accepted = mocks.accept.mock.calls.at(-1)?.[0] as { runAcceptedIntent: (nonce: string) => Promise<void> }
+ view.rerender(React.createElement(Probe, { value: { ...value, feed: { ...feed, navigationBlocked: true } } }))
+ await act(async () => { await accepted.runAcceptedIntent("accepted-nonce") })
+ expect(mocks.run).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ nonce: "accepted-nonce", assertCommand: expect.any(Function) }))
+ const command = mocks.run.mock.calls[0]?.[0] as { assertCommand: () => void }
+ expect(() => command.assertCommand()).not.toThrow()
+ })
+
it("forwards complete accept input, run-helper wiring, and helper-owned reply clearing", async () => {
const reply = { id: "r1", authorName: "Alice", text: "reply" }
const attachments = [{ file: {} as File }]
@@ -506,8 +548,9 @@ describe("useMessageChannelController", () => {
const runtime = fixtureOwner.registry.runtime
const scope = { kind: "channel" as const, id: "channel_1", serverId: "server_1" }
act(() => {
- ingestMessages(fixtureOwner.registry, scope.id, [{ id: "m1", seq: 1, type: "chat", content: "current body", authorId: "u1", authorName: "Current Author", authorAvatar: "current.png", authorAvatarVersion: 7 }])
- ingestMessages(fixtureOwner.registry, "other_channel", [{ id: "other", seq: 2, type: "chat", content: "private other" }])
+ writeCommunityProfilePatches([communityUserProfilePatch("u1", { name: "Current Author", discriminator: "0001", avatar: "current.png", avatarVersion: 7 })], fixtureOwner.registry)
+ ingestMessages(fixtureOwner.registry, scope.id, messageSeedFixture(scope.id, [{ id: "m1", seq: 1, type: "chat", content: "current body", authorId: "u1", authorName: "Current Author", authorAvatar: "current.png", authorAvatarVersion: 7 }]))
+ ingestMessages(fixtureOwner.registry, "other_channel", messageSeedFixture("other_channel", [{ id: "other", seq: 2, type: "chat", content: "private other" }]))
runtime.messageStream.actions.accept(scope, { nonce: "clicked_failed", tempId: "temp_clicked_failed", message: { type: "chat", authorId: "u1", content: "local body" }, localUploads: [] })
runtime.messageStream.actions.dispatch(scope, { type: "postFail", nonce: "clicked_failed" })
})
@@ -515,7 +558,7 @@ describe("useMessageChannelController", () => {
expect(getMessage("temp_clicked_failed")).toMatchObject({ content: "local body", failed: true, clientNonce: "clicked_failed", authorName: "Current Author", authorAvatarVersion: 7 })
expect(getMessage("other")).toBeUndefined()
act(() => {
- const confirmed = { id: "confirmed", seq: 3, type: "chat" as const, content: "confirmed body", authorId: "u1", clientNonce: "clicked_failed" }
+ const confirmed = messageSeedFixture(scope.id, [{ id: "confirmed", seq: 3, content: "confirmed body", authorId: "u1", clientNonce: "clicked_failed" }])[0]
ingestMessages(fixtureOwner.registry, scope.id, [confirmed])
runtime.messageStream.actions.dispatch(scope, { type: "wsMessage", message: confirmed })
})
@@ -557,4 +600,20 @@ describe("useMessageChannelController", () => {
expect(Object.keys(latest.threadActions)).toEqual(actionKeys)
expect(latest.threadActions.onCreateThread).toBeUndefined()
})
+
+ it("rejects direct and retained typing admission after the committed window blocks", () => {
+ const value = props()
+ const view = rtlRender(React.createElement(Probe, { value }))
+ const earlier = latest.handleTyping
+ act(() => earlier())
+ expect(mocks.sendTyping).toHaveBeenCalledOnce()
+ view.rerender(React.createElement(Probe, { value: { ...value, feed: { ...feed, navigationBlocked: true } } }))
+ mocks.sendTyping.mockClear()
+ act(() => { earlier(); latest.handleTyping() })
+ expect(mocks.sendTyping).not.toHaveBeenCalled()
+ view.rerender(React.createElement(Probe, { value }))
+ act(() => latest.handleTyping())
+ expect(mocks.sendTyping).toHaveBeenCalledOnce()
+ })
+
})
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index ec36cef74..a9965963c 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -8,7 +8,7 @@ import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotTo
import { useCommunityRuntime } from "@/stores/community/runtime"
-import { useCallback, useEffect, useLayoutEffect, useMemo } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"
import { materializeIntent } from "@/lib/community/message-stream"
import { presentCanonicalMessage } from "@/lib/community/message-wire"
import { messageScopeKey } from "@/stores/community/message-stream-store"
@@ -67,6 +67,8 @@ export function useMessageChannelController({
resolveUserName,
}: Omit<MessageChannelControllerProps, "children">): MessageChannelControllerValue {
const active = useConversationActivity()
+ const committedFeed = useRef(feed)
+ useLayoutEffect(() => { committedFeed.current = feed }, [feed])
const profileQueryClient = useQueryClient()
const communityRuntime = useCommunityRuntime()
const source = useCommunityViewSource(`message-actions:${serverId}:${channelId}`)
@@ -240,6 +242,7 @@ export function useMessageChannelController({
attachments?: SendAttachment[],
mentionType?: MentionType,
): boolean => {
+ if (committedFeed.current.navigationBlocked) return false
const command = captureSendCommand()
const accepted = acceptChannelMessage({
runtime: communityRuntime,
@@ -277,7 +280,10 @@ export function useMessageChannelController({
threadActions: { ...messageActions, onCreateThread: undefined },
acceptMessage,
localSubmitVersion,
- handleTyping: () => communityWsSendTyping(communityRuntime, { channelId }),
+ handleTyping: () => {
+ if (committedFeed.current.navigationBlocked) return
+ communityWsSendTyping(communityRuntime, { channelId })
+ },
typingUsers: typingUserIds.map((id) => typingNames[id] ?? resolveUserName(id)),
}), [feed, pinnedIds, replyTo, setReplyTo, scrollTargetId, setScrollTargetId, consumeScrollTarget, contextTarget, setContextTarget, openContextSeq, onSheetReply, jumpToSeq, messageActions, acceptMessage, localSubmitVersion, typingUserIds, communityRuntime, channelId, typingNames, resolveUserName])
}
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 4ad346470..7c959f5db 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
@@ -1,3 +1,5 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act } from "@/test/react-dom-harness"
@@ -6,6 +8,7 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { beginCommunityProfileSeed } from "@/lib/community/profile-seed"
import type { MessageInput } from "@/lib/community/models/message"
+let navigationOwner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
const mocks = vi.hoisted(() => ({
push: vi.fn(),
cancel: vi.fn(),
@@ -49,19 +52,7 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({ ...await importOri
isLoading: false,
isError: false,
}),
- useQueryClient: () => ({
- getQueryData: () => ({
- notFound: false,
- anchorId: "message_1",
- messages: [{
- id: "message_1",
- seq: 1,
- type: "chat",
- reactions: [],
- }],
- }),
- setQueryData: mocks.setQueryData,
- }),
+ useQueryClient: () => navigationOwner.client,
}))
vi.mock("@/components/community/shell/community-sheet", () => ({
CommunitySheet: ({ children }: { children: React.ReactNode }) => children,
@@ -120,7 +111,7 @@ 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: mocks.canonicalMessages }
+ return { ...actual, useCanonicalMessagesById: mocks.canonicalMessages, useCanonicalProfilesProjection: () => ({ resourceProfiles: new Map(navigationOwner ? [...navigationOwner.registry.collections.profiles.values()].map(row => [row.id, row]) : []), isReady: true, isError: false }) }
})
import {
@@ -133,15 +124,15 @@ describe("MessageContextSheet native query publication", () => {
beforeEach(() => mocks.apiFetch.mockReset())
afterEach(() => vi.restoreAllMocks())
- it("publishes author profiles once with the sorted canonical context window and ID-only sheet cache", async () => {
+ it("publishes sorted complete context messages without inventing full author profiles from history hints", async () => {
const owner = await createCommunityQueryOwner("context_viewer")
const writer = await import("@/lib/community-db/write")
const write = vi.spyOn(writer, "writeCommunityCollectionRows")
const signal = new AbortController().signal
- mocks.apiFetch.mockResolvedValueOnce({ id: "anchor" }).mockResolvedValueOnce({ messages: [
- { id: "after", seq: 3, type: "chat", content: "after", authorId: "author", authorName: "Author" },
- { id: "anchor", seq: 2, type: "chat", content: "anchor", authorId: "author", authorName: "Author" },
- ], hasMore: false })
+ mocks.apiFetch.mockResolvedValueOnce({ id: "anchor" }).mockResolvedValueOnce(messageReadPageFixture({ messages: [
+ messageResourceFixture({ id: "after", channelId: "context_channel", seq: 3, content: "after", authorId: "author", authorName: "Author" }),
+ messageResourceFixture({ id: "anchor", channelId: "context_channel", seq: 2, content: "anchor", authorId: "author", authorName: "Author" }),
+ ], hasMore: false }))
await expect(messageContextQueryFn("channel", "context_channel", 2, owner.client)({ signal })).resolves.toEqual({
notFound: false, anchorId: "anchor", messages: [{ id: "anchor" }, { id: "after" }],
})
@@ -150,9 +141,9 @@ describe("MessageContextSheet native query publication", () => {
"/api/community/channels/context_channel/messages?anchor=anchor&limit=11",
])
expect(mocks.apiFetch.mock.calls.every(([, options]) => options.signal === signal)).toBe(true)
- expect(write.mock.calls.filter(([, collection]) => collection === "profiles")).toHaveLength(1)
+ expect(write.mock.calls.filter(([, collection]) => collection === "profiles")).toHaveLength(2)
expect(owner.registry.collections.messages.get("anchor")).toMatchObject({ content: "anchor", channelId: "context_channel", authorId: "author" })
- expect(owner.registry.collections.profiles.get("author")).toMatchObject({ name: "Author" })
+ expect(owner.registry.collections.profiles.get("author")).toMatchObject({ id: "author", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 })
write.mockRestore()
})
@@ -175,7 +166,7 @@ describe("MessageContextSheet native query publication", () => {
const pending = messageContextQueryFn("channel", "context_channel", 2, owner.client)().catch((error) => error)
while (!resolvePage) await Promise.resolve()
retireCommunityChannelReading(owner.registry, "context_channel", { reason: "read-denied", serverId: "context_server" })
- resolvePage({ messages: [{ id: "anchor", seq: 2, type: "chat", content: "late", authorId: "author", authorName: "Late Author" }], hasMore: false })
+ resolvePage({ messages: [messageResourceFixture({ id: "anchor", channelId: "context_channel", seq: 2, content: "late", authorId: "author", authorName: "Late Author" })], hasMore: false })
expect(await pending).toMatchObject({ name: "AbortError" })
expect(owner.registry.collections.messages.get("anchor")).toBeUndefined()
expect(owner.registry.collections.profiles.get("author")).toBeUndefined()
@@ -183,7 +174,10 @@ describe("MessageContextSheet native query publication", () => {
})
describe("MessageContextSheet thread navigation", () => {
- beforeEach(() => {
+ beforeEach(async () => {
+ navigationOwner = await createCommunityQueryOwner("viewer_1")
+ const { publishCommunityMessages, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
+ publishCommunityMessages(navigationOwner.client, { channelId: "parent_1", messages: [messageResourceFixture({ id: "message_1", channelId: "parent_1", authorId: "author_1", authorName: "Author" })], profiles: [{ id: "author_1", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }], proof: { token: captureCommunityLiveSnapshotToken(navigationOwner.client) } })
vi.clearAllMocks()
mocks.openThread = undefined
mocks.pin = undefined
diff --git a/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
index f82544f93..17af0aceb 100644
--- a/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
+++ b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
@@ -1,9 +1,12 @@
+import { messageProfilesFixture, messageReadPageFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { act } from "@/test/react-dom-harness"
import { render } from "@/test/react-dom-harness"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { publishCommunityMessages, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { writeCommunityCollectionRows } from "@/lib/community-db/write"
import { communityKeys } from "@/lib/query-keys"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -71,7 +74,8 @@ function sheetCache(me: boolean) {
return {
notFound: false,
anchorId: "message_1",
- messages: [{
+ messages: [messageResourceFixture({
+ channelId: "channel_1",
id: "message_1",
seq: 1,
type: "chat",
@@ -82,13 +86,13 @@ function sheetCache(me: boolean) {
reactions: me
? [{ emoji: "👍", count: 1, me: true, userIds: ["viewer_1"] }]
: [],
- }],
+ })],
}
}
async function renderSheet(me: boolean) {
const initial = sheetCache(me)
- publishCommunityMessages(owner.client, { channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
+ publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
owner.client.setQueryData(communityKeys.messageContext("channel", "channel_1", 1), { ...initial, messages: initial.messages.map(({ id }) => ({ id })) })
const rendered = render(React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer_1", retainOwner: true }, React.createElement(MessageContextSheet, {
open: true, onOpenChange: vi.fn(), channelId: "channel_1", targetSeq: 1,
@@ -123,6 +127,28 @@ describe("MessageContextSheet reaction coordinator", () => {
})
})
+ it("rereads fresh context IDs with a missing author before exposing row actions", async () => {
+ const initial = sheetCache(false)
+ publishCommunityMessages(owner.client, { profiles: messageProfilesFixture(initial.messages), channelId: "channel_1", messages: initial.messages, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
+ owner.client.setQueryData(communityKeys.messageContext("channel", "channel_1", 1), { ...initial, messages: [{ id: "message_1" }] })
+ await writeCommunityCollectionRows(owner.registry, "profiles", [], row => row.id)
+ let release!: (value: ReturnType<typeof messageReadPageFixture>) => void
+ const held = new Promise<ReturnType<typeof messageReadPageFixture>>(resolve => { release = resolve })
+ mocks.apiFetch.mockResolvedValueOnce({ id: "message_1" }).mockImplementationOnce(() => held)
+ render(React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer_1", retainOwner: true }, React.createElement(MessageContextSheet, {
+ open: true, onOpenChange: vi.fn(), channelId: "channel_1", targetSeq: 1,
+ })))
+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ expect(mocks.onAdd).toBeUndefined()
+ expect(mocks.onToggle).toBeUndefined()
+ await act(async () => { release(messageReadPageFixture({ messages: initial.messages, hasMore: false })); await held; await vi.advanceTimersByTimeAsync(0) })
+ expect(mocks.onAdd).toEqual(expect.any(Function))
+ expect(owner.registry.collections.profiles.get("author_1")).toMatchObject({ id: "author_1", name: "Author", discriminator: expect.any(String), avatarVersion: 0 })
+ expect(owner.client.getQueryData(communityKeys.messageContext("channel", "channel_1", 1))).toMatchObject({ messages: [{ id: "message_1" }] })
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ })
+
it("repeats picker add without a rerender and preserves the first timer deadline", async () => {
mocks.apiFetch.mockResolvedValue(undefined)
await renderSheet(false)
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 71eb26ab4..e3b63eb46 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -6,7 +6,7 @@ import { useCallback, useEffect, useMemo, useRef } from "react"
import { useCommunityRouter } from "@/contexts/community/module-route"
import { toast } from "sonner"
import { useQuery, useQueryClient } from "@tanstack/react-query"
-import { deriveThreadName } from "@alook/shared"
+import { CommunityMessageResourcesSchema, CommunityResourceProfileSchema, communityMessageProfileIds, deriveThreadName } from "@alook/shared"
import { CommunitySheet } from "@/components/community/shell/community-sheet"
import { MessageRow } from "./message-row"
import { MessageShareDialog } from "./message-share-dialog"
@@ -27,19 +27,22 @@ import {
useUnpinMessage,
type ReactionArgs,
} from "@/hooks/community/mutations"
-import type { FileAttachment, ImagePreview, MessagesPage, Msg, RenderMsg, ReplyTarget } from "@/lib/community/models/message"
+import type { FileAttachment, ImagePreview, MessagesReadPage, Msg, RenderMsg, ReplyTarget } from "@/lib/community/models/message"
import { apiFetchCommunity, communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { isAbortError } from "@/lib/errors"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { useHoverCapable } from "@/hooks/use-hover-capable"
import { channelHref } from "@/lib/community/community-route"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { communityKeys } from "@/lib/query-keys"
import {
materializeCanonicalMessage,
materializeCanonicalMessages,
useCanonicalMessagesById,
+ useCanonicalProfilesProjection,
} from "@/lib/community-db/projections"
import {
+ getCanonicalCommunityMessageResources,
captureCommunityLiveSnapshotToken,
assertCommunityLiveSnapshotTokenCurrent,
publishCommunityEmbeddedMessages,
@@ -117,13 +120,14 @@ export function messageContextQueryFn(
throw error
}
assert()
- const page = await apiFetchCommunity<MessagesPage>(
+ const page = await apiFetchCommunity<MessagesReadPage>(
anchorFetchUrl(type, channelId, lookup.id, CONTEXT_LIMIT),
{ signal, assertActive: assert }, publicationToken,
)
const messages = (page.messages ?? []).slice().sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
publishCommunityEmbeddedMessages(queryClient, {
entries: messages.map((message) => ({ channelId, message })),
+ profiles: page.profiles,
proof: { token: publicationToken, signal },
})
assert()
@@ -214,6 +218,20 @@ export function MessageContextSheet({
})
const selectedIds = useMemo(() => query.data?.messages?.map((message) => message.id) ?? [], [query.data?.messages])
const canonicalMessages = useCanonicalMessagesById(selectedIds)
+ const registry = getCommunityDbRegistry(queryClient)
+ const selectedResources = selectedIds.map(id => registry?.collections.messages.get(id))
+ const graph = getCanonicalCommunityMessageResources(queryClient, selectedResources)
+ const profiles = useCanonicalProfilesProjection(graph ? communityMessageProfileIds(graph.messages) : [])
+ const nativeGraph = graph && CommunityMessageResourcesSchema.safeParse({ messages: graph.messages, profiles: [...profiles.resourceProfiles.values()].flatMap(profile => {
+ const parsed = CommunityResourceProfileSchema.strip().safeParse(profile)
+ return parsed.success ? [parsed.data] : []
+ }) })
+ const graphReady = !!graph && profiles.isReady && !profiles.isError && nativeGraph?.success === true
+ const refetch = query.refetch
+ useEffect(() => {
+ if (open && query.data && !query.data.notFound && !graph && query.isSuccess && !query.isFetching) void refetch({ cancelRefetch: false })
+ }, [open, query.data, graph, query.isSuccess, query.isFetching, refetch])
+
const renderRows = useMemo<RenderMsg[]>(() => {
if (!query.data || query.data.notFound || !query.data.messages) return []
@@ -238,8 +256,8 @@ export function MessageContextSheet({
const anchorId = query.data && !query.data.notFound ? (query.data.anchorId ?? null) : null
- const canonicalPending = !!query.data && !query.data.notFound && canonicalMessages === undefined
- const anchorMissing = canonicalMessages !== undefined && !!anchorId && !canonicalMessages.has(anchorId)
+ const canonicalPending = !!query.data && !query.data.notFound && (canonicalMessages === undefined || !graphReady)
+ const anchorMissing = !canonicalPending && canonicalMessages !== undefined && !!anchorId && !canonicalMessages.has(anchorId)
// ── Sheet-local actions ──────────────────────────────────────────────────
const findMessage = useCallback(
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index 5afeca1e7..168603f9c 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -2,7 +2,7 @@ import type { ReactNode } from "react"
import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
import type { MessagePositionState, MessageRequest } from "@/lib/community/message-position"
-import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
export type MessageListProps = {
observation?: import("@/lib/observability/regions").ResourceObservation
@@ -34,7 +34,7 @@ export type MessageListProps = {
scrollToMessageId?: string | null
initialPositionMessageId?: string | null
positionEntry?: object | null
- positionScope?: VirtualListPositionScope
+ positionScope?: ConversationListScope
positionDataState?: MessagePositionState
targetPositionDataState?: MessagePositionState
messageWindow?: object
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 3447279d4..09541d940 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,7 +6,7 @@ import { act, fireEvent, render } from "@/test/react-dom-harness"
import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
-import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
import { tid } from "@/lib/community/testids"
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
@@ -62,9 +62,9 @@ describe("MessageList loading-to-loaded mount identity", () => {
expect(root.querySelector('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")
})
- it("initializes from the qualified snapshot after loading and then retains the mounted list", async () => {
+ it("uses ordinary entry after loading and then retains the mounted list", async () => {
const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ const positionScope: ConversationListScope = { proof: captureChannelMetadataToken(client, "A"), tag: null }
const messages = Array.from({ length: 40 }, (_, index) => ({ id: `m${index}`, type: "chat" as const,
authorId: "peer", authorName: "Alice", content: "Message", createdAt: new Date(index * 1000).toISOString() }))
const props = { channel: "A", onOpenThread: () => {}, positionScope }
@@ -76,18 +76,18 @@ describe("MessageList loading-to-loaded mount identity", () => {
runFrames()
resize()
const before = root.scrollTop
- expect(client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))?.offset).toBe(before)
first.unmount()
const second = render(React.createElement(MessageList, { ...props, messages: [], loading: true, initialScrollReady: false }))
resize()
- second.rerender(React.createElement(MessageList, { ...props, messages, initialScrollReady: true }))
+ second.rerender(React.createElement(MessageList, { ...props, messages, initialScrollReady: true, initialPositionMessageId: "m25" }))
resize()
const restored = second.getByTestId(tid.messageScroller)
- expect(restored.scrollTop).toBeCloseTo(before, 0)
+ expect(restored.scrollTop).not.toBe(before)
+ const entered = restored.scrollTop
expect(restored.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "true")
- second.rerender(React.createElement(MessageList, { ...props, messages, initialScrollReady: true, isFetching: true }))
+ second.rerender(React.createElement(MessageList, { ...props, positionScope: { ...positionScope, proof: captureChannelMetadataToken(client, "A") }, messages, initialScrollReady: true, initialPositionMessageId: "m25", isFetching: true }))
resize()
expect(second.getByTestId(tid.messageScroller)).toBe(restored)
- expect(restored.scrollTop).toBeCloseTo(before, 0)
+ expect(restored.scrollTop).toBeCloseTo(entered, 0)
})
})
diff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsx
index 59aa97aad..d840eaad4 100644
--- a/src/web/src/components/community/messages/message-list.tsx
+++ b/src/web/src/components/community/messages/message-list.tsx
@@ -5,7 +5,7 @@ import { useObservedRegion } from "@/lib/observability/regions"
import { visibleVirtualItems } from "@/lib/observability/virtual-window"
import { useContext, useLayoutEffect, useState } from "react"
import { hashKey } from "@tanstack/react-query"
-import { virtualListPositionKey } from "@/lib/community/virtual-list-position"
+import { conversationListScopeKey } from "@/lib/community/conversation-qualification"
import { useMessageListController } from "./message-list-controller"
import { useHoverCapable } from "@/hooks/use-hover-capable"
import { useConversationFooterSlot } from "./conversation-footer-shell"
@@ -16,7 +16,7 @@ import { VirtualRows } from "./virtual-cursor-list"
import { ConversationPresentationContext, useConversationActivity } from "@/contexts/community/conversation-activity"
export function MessageList(props: MessageListProps) {
- return <MessageListEntry key={props.positionScope ? hashKey(virtualListPositionKey(props.positionScope)) : undefined} {...props} />
+ return <MessageListEntry key={props.positionScope ? hashKey(conversationListScopeKey(props.positionScope)) : undefined} {...props} />
}
function MessageListEntry({
diff --git a/src/web/src/components/community/messages/message-route.dom.test.tsx b/src/web/src/components/community/messages/message-route.dom.test.tsx
index 7f82722e3..e225becd5 100644
--- a/src/web/src/components/community/messages/message-route.dom.test.tsx
+++ b/src/web/src/components/community/messages/message-route.dom.test.tsx
@@ -1,4 +1,6 @@
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION, CommunityChannelReadSchema } from "@alook/shared"
+import { singleMessageReadFixture, messageResourceFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createElement, type PropsWithChildren } from "react"
import { act, fireEvent, render, screen, waitFor } from "@/test/react-dom-harness"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
@@ -9,10 +11,14 @@ import { normalizeCommunityHref } from "@/lib/community/community-route"
import { communityKeys } from "@/lib/query-keys"
import { ApiError } from "@/lib/errors"
import { MessageRoute } from "./message-route"
-const api = vi.hoisted(()=>({read:vi.fn()}))
+const api = vi.hoisted(()=>({read:vi.fn(), realBoundary:false}))
vi.mock("@/lib/community/account-cache-lifecycle", async importOriginal => ({
...await importOriginal<typeof import("@/lib/community/account-cache-lifecycle")>(),
- apiFetchCommunity: async (path:string, options:{assertActive?:()=>void}) => {
+ apiFetchCommunity: async (path:string, options:{assertActive?:()=>void}, ...rest: unknown[]) => {
+ if (api.realBoundary) {
+ const actual = await importOriginal<typeof import("@/lib/community/account-cache-lifecycle")>()
+ return actual.apiFetchCommunity(path, options, rest[0] as Parameters<typeof actual.apiFetchCommunity>[2])
+ }
options.assertActive?.()
try { const result=await api.read(path); options.assertActive?.();return result }
catch(error){options.assertActive?.();throw error}
@@ -26,16 +32,39 @@ let navigation:CommunityNavigationController
const openInbox=vi.fn()
beforeEach(async()=>{
owner=await createCommunityQueryOwner("viewer")
- vi.clearAllMocks();api.read.mockReset();revision=0;href="/c/messages/message_1"
+ vi.clearAllMocks();api.read.mockReset();api.realBoundary=false;revision=0;href="/c/messages/message_1"
navigation={publishedHref:href,navigationPending:false,pendingHref:null,
captureIntent:()=>{const original=revision;return()=>original===revision},
push:vi.fn(),pushImmediate:vi.fn(),replace:vi.fn(()=>{revision++}),resolveAndPush:vi.fn(),cancelPendingNavigation:vi.fn()}
})
const wrapper=({children}:PropsWithChildren)=>createElement(CommunityTestProvider,{client:owner.client,registry:owner.registry,userId:"viewer",retainOwner:true},
createElement(CommunityRouteContext,{value:{breakpoint:"desktop",ownerDeleteRouteScope:undefined,frame:{...normalizeCommunityHref(href),revision},navigation,openInbox}},children))
+function currentMessageRead(channelId: string) {
+ return singleMessageReadFixture(messageResourceFixture({ id: "message_1", channelId, authorId: "author", authorName: "Author", authorAvatarVersion: 0 }))
+}
describe("ordinary message page",()=>{
+ it.each(["dm", "text"] as const)("uses actual HTTP decoding for a complete %s single message before navigation", async type => {
+ api.realBoundary = true
+ const wire = singleMessageReadFixture(messageResourceFixture({ id: "message_1", channelId: "actual_channel", authorId: "author", authorName: "Author", authorAvatarVersion: 0 }))
+ const metadata = CommunityChannelReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "actual_channel",
+ channel: channelResourceFixture({ id: "actual_channel", type, serverId: type === "dm" ? null : "actual_server" }),
+ access: { channelId: "actual_channel", canRead: true, canSend: true, canCreateDiscussion: type === "text" } })
+ const requests: string[] = []
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, options?: RequestInit) => {
+ const path = new URL(input instanceof Request ? input.url : String(input), "http://localhost").pathname
+ requests.push(path)
+ expect(new Headers(options?.headers).get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ if (!["/api/community/messages/message_1", "/api/community/channels/actual_channel"].includes(path)) throw new Error(`Unexpected read ${path}`)
+ return new Response(JSON.stringify(path.includes("/messages/") ? wire : metadata), { headers: { "content-type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+ }))
+ render(<MessageRoute messageId="message_1"/>,{wrapper})
+ await waitFor(() => expect(navigation.replace).toHaveBeenCalledExactlyOnceWith(type === "dm" ? "/c/me/actual_channel" : "/c/channels/actual_server/actual_channel"))
+ expect(requests).toEqual(["/api/community/messages/message_1", "/api/community/channels/actual_channel"])
+ expect(api.read).not.toHaveBeenCalled()
+ })
+
it.each(["dm","text","forum","thread"])("resolves a %s through the permission door then replaces with its bare conversation URL",async type=>{
- api.read.mockResolvedValueOnce({id:"message_1",channelId:"actual_channel"})
+ api.read.mockResolvedValueOnce(currentMessageRead("actual_channel"))
.mockResolvedValueOnce({id:"actual_channel",type,serverId:type==="dm"?null:"actual_server",archived:false})
render(<MessageRoute messageId="message_1"/>,{wrapper})
await waitFor(()=>expect(navigation.replace).toHaveBeenCalledExactlyOnceWith(type==="dm"?"/c/me/actual_channel":"/c/channels/actual_server/actual_channel"))
@@ -52,7 +81,7 @@ describe("ordinary message page",()=>{
expect(api.read).toHaveBeenCalledExactlyOnceWith("/api/community/messages/message_1")
})
it.each(["archived","denied","wrong channel"])("shows the normal unavailable state for %s metadata",async reason=>{
- api.read.mockResolvedValueOnce({id:"message_1",channelId:"channel_1"}).mockResolvedValueOnce({
+ api.read.mockResolvedValueOnce(currentMessageRead("channel_1")).mockResolvedValueOnce({
id:reason==="wrong channel"?"other":"channel_1",type:"text",serverId:"server_1",
archived:reason==="archived",accessDecision:{canRead:reason!=="denied"},
})
@@ -72,7 +101,7 @@ describe("ordinary message page",()=>{
expect(await screen.findByRole("alert", {}, {timeout:4000})).toHaveTextContent("Could not open this conversation")
expect(api.read).toHaveBeenCalledTimes(2)
expect(navigation.replace).not.toHaveBeenCalled()
- api.read.mockResolvedValueOnce({id:"message_1",channelId:"channel_1"})
+ api.read.mockResolvedValueOnce(currentMessageRead("channel_1"))
.mockResolvedValueOnce({id:"channel_1",type:"dm",serverId:null,archived:false})
fireEvent.click(screen.getByRole("button",{name:"Retry"}))
await waitFor(()=>expect(navigation.replace).toHaveBeenCalledExactlyOnceWith("/c/me/channel_1"))
@@ -87,12 +116,12 @@ describe("ordinary message page",()=>{
render(<MessageRoute messageId="message_1"/>,{wrapper})
await waitFor(()=>expect(api.read).toHaveBeenCalledOnce())
revision++
- await act(async()=>release({id:"message_1",channelId:"channel_1"}))
+ await act(async()=>release(currentMessageRead("channel_1")))
expect(api.read).toHaveBeenCalledOnce();expect(navigation.replace).not.toHaveBeenCalled()
})
it("ignores delayed channel authorization after the originating account retires",async()=>{
let release!:(value:unknown)=>void
- api.read.mockResolvedValueOnce({id:"message_1",channelId:"channel_1"})
+ api.read.mockResolvedValueOnce(currentMessageRead("channel_1"))
.mockReturnValueOnce(new Promise(resolve=>{release=resolve}))
render(<MessageRoute messageId="message_1"/>,{wrapper})
await waitFor(()=>expect(api.read).toHaveBeenCalledTimes(2))
@@ -101,3 +130,5 @@ describe("ordinary message page",()=>{
expect(navigation.replace).not.toHaveBeenCalled()
})
})
+
+afterEach(() => { vi.unstubAllGlobals() })
diff --git a/src/web/src/components/community/messages/message-route.tsx b/src/web/src/components/community/messages/message-route.tsx
index 26dad68b7..3d6ff67b5 100644
--- a/src/web/src/components/community/messages/message-route.tsx
+++ b/src/web/src/components/community/messages/message-route.tsx
@@ -6,7 +6,7 @@ import { useCommunityRouteFrame } from "../shell/community-route-context"
import { CommunityPendingFrame } from "../shell/community-pending-frame"
import { Button } from "@/components/ui/button"
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
-import type { OpenerPayload } from "@/hooks/community/use-message"
+import type { CommunityMessageRead } from "@alook/shared"
import type { ChannelMetadata } from "@/hooks/community/channel-metadata"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
@@ -42,9 +42,10 @@ export function MessageRoute({ messageId }: { messageId: string }) {
}
return withConversationReadDeadline(AbortSignal.any([signal, original.signal]), async (readSignal) => {
assertCurrent()
- const message = await apiFetchCommunity<OpenerPayload>(`/api/community/messages/${encodeURIComponent(messageId)}`,
+ const read = await apiFetchCommunity<CommunityMessageRead>(`/api/community/messages/${encodeURIComponent(messageId)}`,
{ signal: readSignal, assertActive: assertCurrent }, account)
assertCurrent()
+ const message = read.message
if (message.id !== messageId || !message.channelId || !SAFE_ID.test(message.channelId)) throw new ApiError("Conversation unavailable", 404)
const channel = captureCommunityLiveSnapshotToken(client, message.channelId)
const assertChannel = () => { assertCurrent(); assertCommunityLiveSnapshotTokenCurrent(client, channel, readSignal) }
diff --git a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
index b50bebce2..684ce48f2 100644
--- a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
@@ -3,6 +3,7 @@ import { resolve } from "node:path"
import { forwardRef, createElement, createRef } from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act } from "@/test/react-dom-harness"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import { renderCommunity as render } from "@/test/community-owner-harness"
const mocks = vi.hoisted(() => ({
@@ -141,6 +142,7 @@ type TestEditor = {
}
setEditable: ReturnType<typeof vi.fn>
commands: {
+ blur: ReturnType<typeof vi.fn>
clearContent: ReturnType<typeof vi.fn>
focus: ReturnType<typeof vi.fn>
liftEmptyBlock: ReturnType<typeof vi.fn>
@@ -221,6 +223,7 @@ describe("useComposerController", () => {
view: { dispatch, dom: { setAttribute: setDomAttribute } },
setEditable: vi.fn(),
commands: {
+ blur: vi.fn(),
clearContent,
focus,
liftEmptyBlock: vi.fn(() => false),
@@ -1369,4 +1372,103 @@ describe("useComposerController", () => {
.toBeLessThan(source.indexOf("editor.commands.clearContent()"))
expect(source).toContain("typingTimer.current = null")
})
+
+ it.each(["emoji", "upload", "file", "drop", "paste", "remove", "cancel", "send", "drag-enter", "drag-over"] as const)("rejects a retained %s input callback after activity is lost", async kind => {
+ const accept = vi.fn(() => true), cancel = vi.fn()
+ const node = (active: boolean) => createElement(ConversationActivityContext.Provider, { value: active },
+ createElement(Harness, { ...acceptedProps(accept), onCancelReply: cancel }))
+ const view = render(node(true))
+ const retained = controllerView
+ const attachment = mocks.useFileAttachments.mock.results.at(-1)!.value
+ view.rerender(node(false))
+ vi.clearAllMocks()
+ const event = { preventDefault: vi.fn(), stopPropagation: vi.fn(), currentTarget: { value: "picked" },
+ clipboardData: { items: [], getData: () => "paste" } }
+ await act(async () => {
+ if (kind === "emoji") retained.onEmojiPick("x")
+ if (kind === "upload") retained.onUploadFile()
+ if (kind === "file") retained.onFileSelect(event as unknown as Parameters<typeof retained.onFileSelect>[0])
+ if (kind === "drop") retained.onDrop(event as unknown as Parameters<typeof retained.onDrop>[0])
+ if (kind === "paste") editorOptions.editorProps.handlePaste({}, event as unknown as ClipboardEvent)
+ if (kind === "remove") retained.removePendingFile(0)
+ if (kind === "cancel") retained.onCancelReply?.()
+ if (kind === "send") retained.onSend()
+ if (kind === "drag-enter") retained.onDragEnter(event as unknown as Parameters<typeof retained.onDragEnter>[0])
+ if (kind === "drag-over") retained.onDragOver(event as unknown as Parameters<typeof retained.onDragOver>[0])
+ })
+ expect(accept).not.toHaveBeenCalled()
+ expect(cancel).not.toHaveBeenCalled()
+ expect(insertContent).not.toHaveBeenCalled()
+ expect(filePickerClick).not.toHaveBeenCalled()
+ expect(handleDropRaw).not.toHaveBeenCalled()
+ expect(attachment.handleFileSelect).not.toHaveBeenCalled()
+ expect(attachment.removePendingFile).not.toHaveBeenCalled()
+ expect(attachment.handleDragEnter).not.toHaveBeenCalled()
+ expect(attachment.handleDragOver).not.toHaveBeenCalled()
+ expect(mocks.addPendingFiles).not.toHaveBeenCalled()
+ expect(mocks.preservePlainTextPaste).not.toHaveBeenCalled()
+ expect(mocks.clearDraft).not.toHaveBeenCalled()
+ expect(controllerView.sendDisabled).toBe(true)
+ view.rerender(node(true))
+ expect(editor.setEditable).toHaveBeenLastCalledWith(true, false)
+ view.unmount()
+ })
+
+ it.each(["upload", "file", "drop", "remove", "drag-enter", "drag-over"] as const)("delegates retained %s attachment input before and after reactivation", async kind => {
+ const accept = vi.fn(() => true)
+ const node = (active: boolean) => createElement(ConversationActivityContext.Provider, { value: active },
+ createElement(Harness, acceptedProps(accept)))
+ const view = render(node(true))
+ const retained = controllerView
+ const attachment = mocks.useFileAttachments.mock.results.at(-1)!.value
+ const raw = { upload: filePickerClick, file: attachment.handleFileSelect, drop: handleDropRaw,
+ remove: attachment.removePendingFile, "drag-enter": attachment.handleDragEnter, "drag-over": attachment.handleDragOver }[kind]
+ for (const active of [true, false, true]) {
+ view.rerender(node(active))
+ vi.clearAllMocks()
+ const event = { preventDefault: vi.fn(), stopPropagation: vi.fn(), currentTarget: { value: "picked" } }
+ await act(async () => {
+ if (kind === "upload") retained.onUploadFile()
+ if (kind === "file") retained.onFileSelect(event as unknown as Parameters<typeof retained.onFileSelect>[0])
+ if (kind === "drop") retained.onDrop(event as unknown as Parameters<typeof retained.onDrop>[0])
+ if (kind === "remove") retained.removePendingFile(0)
+ if (kind === "drag-enter") retained.onDragEnter(event as unknown as Parameters<typeof retained.onDragEnter>[0])
+ if (kind === "drag-over") retained.onDragOver(event as unknown as Parameters<typeof retained.onDragOver>[0])
+ })
+ expect(raw).toHaveBeenCalledTimes(active ? 1 : 0)
+ expect(editor.commands.focus).toHaveBeenCalledTimes(active && kind === "drop" ? 1 : 0)
+ if (active && kind === "drop") {
+ expect(handleDropRaw.mock.invocationCallOrder[0]).toBeLessThan(editor.commands.focus.mock.invocationCallOrder[0])
+ }
+ if (active && ["file", "drop", "drag-enter", "drag-over"].includes(kind)) expect(raw).toHaveBeenCalledWith(event)
+ if (active && kind === "remove") expect(raw).toHaveBeenCalledWith(0)
+ if (!active && kind === "file") expect(event.currentTarget.value).toBe("")
+ if (!active && ["drop", "drag-enter", "drag-over"].includes(kind)) {
+ expect(event.preventDefault).toHaveBeenCalledOnce()
+ expect(event.stopPropagation).toHaveBeenCalledOnce()
+ }
+ expect(accept).not.toHaveBeenCalled()
+ expect(mocks.clearDraft).not.toHaveBeenCalled()
+ }
+ view.unmount()
+ })
+
+ it("retains drag-leave cleanup while attachment input is inactive", () => {
+ const node = (active: boolean) => createElement(ConversationActivityContext.Provider, { value: active },
+ createElement(Harness, acceptedProps(vi.fn(() => true))))
+ const view = render(node(true))
+ const retained = controllerView
+ const attachment = mocks.useFileAttachments.mock.results.at(-1)!.value
+ for (const active of [true, false, true]) {
+ view.rerender(node(active))
+ vi.clearAllMocks()
+ const event = { relatedTarget: null }
+ act(() => retained.onDragLeave(event as unknown as Parameters<typeof retained.onDragLeave>[0]))
+ expect(attachment.handleDragLeave).toHaveBeenCalledExactlyOnceWith(event)
+ expect(editor.commands.focus).not.toHaveBeenCalled()
+ expect(mocks.addPendingFiles).not.toHaveBeenCalled()
+ }
+ view.unmount()
+ })
+
})
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index 4dc44b9b3..d99986607 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -8,7 +8,6 @@ import {
useImperativeHandle,
useLayoutEffect,
useRef,
- type DragEvent,
type ForwardedRef,
} from "react"
import { useEditor, type Editor, type JSONContent } from "@tiptap/react"
@@ -27,6 +26,7 @@ import { detectMentionType } from "@/lib/community/mention-extension"
import { buildPasteDom } from "@/lib/community/paste-plain-text"
import {
clipboardFiles,
+ createComposerAttachmentInputHandlers,
createLongPasteAttachment,
pendingFilesToSendAttachments,
} from "./composer-file-utils"
@@ -88,13 +88,7 @@ export function useComposerController(
awaitPendingFiles,
addPendingFiles,
fileInputRef,
- handleFileSelect,
- removePendingFile,
dragging,
- handleDragEnter,
- handleDragLeave,
- handleDragOver,
- handleDrop: handleDropRaw,
} = attachments
const typingTimer = useRef<NodeJS.Timeout | null>(null)
const sendRef = useRef<() => void>(() => {})
@@ -168,6 +162,7 @@ export function useComposerController(
undoInputRule: () => editorRef.current?.commands.undoInputRule() ?? false,
}),
handlePaste: (view, event, slice) => {
+ if (!protocol.get().active) { event.preventDefault(); return true }
const files = clipboardFiles(event.clipboardData?.items)
if (files.length > 0) {
event.preventDefault()
@@ -357,40 +352,34 @@ export function useComposerController(
useComposerReplyMention({ editor, channelType, isForumThreadBody, replyingTo, members, suppressSuggestions })
- const handleDrop = (event: DragEvent<HTMLDivElement>) => {
- handleDropRaw(event)
- suppressSuggestions(() => editor?.commands.focus())
- }
+ const attachmentInputHandlers = createComposerAttachmentInputHandlers(
+ () => protocol.get().active,
+ attachments,
+ () => suppressSuggestions(() => editor?.commands.focus()),
+ )
return {
+ ...attachmentInputHandlers,
isForumThreadBody,
- dragging,
- onDragEnter: handleDragEnter,
- onDragLeave: handleDragLeave,
- onDragOver: handleDragOver,
- onDrop: handleDrop,
+ dragging: active && dragging,
mentionPopup: suggestions.mentionPopup,
mentionPresentation: suggestions.mentionPresentation,
mentionPagination: suggestions.mentionPagination,
channelRefPopup: suggestions.channelRefPopup,
channelRefPresentation: suggestions.channelRefPresentation,
replyingTo,
- onCancelReply,
+ onCancelReply: onCancelReply ? () => { if (protocol.get().active) onCancelReply() } : undefined,
pendingFiles,
- removePendingFile,
fileInputRef,
- onFileSelect: handleFileSelect,
editor,
hideAttach,
hideEmoji,
showSend: !isForumThreadBody && !hoverCapable,
sendDisabled:
- sendInFlight || (!editorHasContent && pendingFiles.length === 0),
+ !active || sendInFlight || (!editorHasContent && pendingFiles.length === 0),
onSend: send,
- onUploadFile: () => {
- fileInputRef.current?.click()
- },
onEmojiPick: (emoji) => {
+ if (!protocol.get().active) return
editor?.chain().focus().insertContent(emoji).run()
},
}
diff --git a/src/web/src/components/community/messages/use-composer-reply-mention.ts b/src/web/src/components/community/messages/use-composer-reply-mention.ts
index 5b97da446..e552a88c9 100644
--- a/src/web/src/components/community/messages/use-composer-reply-mention.ts
+++ b/src/web/src/components/community/messages/use-composer-reply-mention.ts
@@ -5,6 +5,7 @@ import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import type { Member } from "@/lib/community/models/people"
import type { ComposerProps, ComposerReplyTarget } from "./composer-types"
import { prependReplyMention } from "./prepend-reply-mention"
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
export function useComposerReplyMention({
editor, channelType, isForumThreadBody, replyingTo, members, suppressSuggestions,
@@ -17,12 +18,14 @@ export function useComposerReplyMention({
suppressSuggestions: (operation: () => void) => void
}) {
const replyProfiles = useCanonicalProfilesByUserId()
+ const active = useConversationActivity()
const previousReplyingToRef = useRef<ComposerReplyTarget | undefined>(undefined)
useEffect(() => {
if (!replyingTo) {
previousReplyingToRef.current = undefined
return
}
+ if (!active) return
if (previousReplyingToRef.current === replyingTo || !editor || isForumThreadBody) return
if (channelType !== "dm") {
const authorId = replyingTo.authorId
@@ -41,5 +44,5 @@ export function useComposerReplyMention({
}
previousReplyingToRef.current = replyingTo
suppressSuggestions(() => editor.commands.focus("end"))
- }, [replyingTo, replyProfiles, members, editor, channelType, isForumThreadBody, suppressSuggestions])
+ }, [active, replyingTo, replyProfiles, members, editor, channelType, isForumThreadBody, suppressSuggestions])
}
diff --git a/src/web/src/components/community/onboarding/initialize-community-onboarding.test.ts b/src/web/src/components/community/onboarding/initialize-community-onboarding.test.ts
index d2e00f67e..24c9d9451 100644
--- a/src/web/src/components/community/onboarding/initialize-community-onboarding.test.ts
+++ b/src/web/src/components/community/onboarding/initialize-community-onboarding.test.ts
@@ -52,8 +52,8 @@ describe("initializeCommunityOnboarding", () => {
beforeEach(async () => {
owner = await createCommunityQueryOwner()
writeCommunityProfilePatches([
- { id: "bot-a", identityAbout: { name: "Maya", discriminator: "0001", kind: "bot" } },
- { id: "bot-b", identityAbout: { name: "Sol", discriminator: "0002", kind: "bot" } },
+ { id: "bot-a", identityAbout: { name: "Maya", discriminator: "0001", kind: "bot" }, avatar: { avatar: null, avatarVersion: 0 } },
+ { id: "bot-b", identityAbout: { name: "Sol", discriminator: "0002", kind: "bot" }, avatar: { avatar: null, avatarVersion: 0 } },
], owner.registry)
apiFetch.mockReset()
randomBotName.mockReset().mockReturnValueOnce("Ari").mockReturnValueOnce("Bo")
diff --git a/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx b/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx
index 89201d8be..f17ef2c74 100644
--- a/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx
+++ b/src/web/src/components/community/settings/account-deletion-flow.dom.test.tsx
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import React from "react"
import { QueryClient } from "@tanstack/react-query"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
@@ -6,6 +7,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { tid } from "@/lib/community/testids"
import { AccountDeletionFlow } from "./account-deletion-flow"
+function currentResponse(body: unknown, init?: ResponseInit) {
+ return Response.json(body, { ...init, headers: { ...init?.headers, [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+}
+function currentError(message: string, status: number) {
+ return currentResponse({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: status >= 500 ? "temporarily_unavailable" : "invalid_input", message, retryable: status >= 500 } }, { status })
+}
+
const authTransition = vi.hoisted(() => ({
begin: vi.fn(),
cancel: vi.fn(),
@@ -46,8 +54,8 @@ describe("AccountDeletionFlow", () => {
it("does not send on open and never deletes when digit six is entered", async () => {
const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
const fetchMock = vi.fn()
- .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
- .mockResolvedValueOnce(Response.json({ ok: true }))
+ .mockResolvedValueOnce(currentResponse({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockResolvedValueOnce(currentResponse({ ok: true }))
vi.stubGlobal("fetch", fetchMock)
const onDeleted = vi.fn().mockResolvedValue(undefined)
render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={onDeleted} />)
@@ -67,15 +75,15 @@ describe("AccountDeletionFlow", () => {
expect(authTransition.cancel).not.toHaveBeenCalled()
expect(fetchMock).toHaveBeenLastCalledWith(
"/api/community/users/me/account-deletion",
- expect.objectContaining({ body: JSON.stringify({ otp: "123456" }) }),
+ expect.objectContaining({ body: JSON.stringify({ otp: "123456" }), headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }),
)
})
it("clears an invalid code, returns focus to the OTP, and preserves the resend cooldown after Back", async () => {
const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
const fetchMock = vi.fn()
- .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
- .mockResolvedValueOnce(Response.json({ error: "INVALID_OTP" }, { status: 400 }))
+ .mockResolvedValueOnce(currentResponse({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockResolvedValueOnce(currentError("INVALID_OTP", 400))
vi.stubGlobal("fetch", fetchMock)
render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={vi.fn()} />)
@@ -99,7 +107,7 @@ describe("AccountDeletionFlow", () => {
it("restores normal auth navigation when the deletion request cannot complete", async () => {
const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
const fetchMock = vi.fn()
- .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockResolvedValueOnce(currentResponse({ ok: true, expires_in: 300, resend_after: 60 }))
.mockRejectedValueOnce(new TypeError("offline"))
vi.stubGlobal("fetch", fetchMock)
render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={vi.fn()} />)
@@ -117,8 +125,8 @@ describe("AccountDeletionFlow", () => {
it.each([200, 202])("preserves the accepted deletion status %s when local cleanup rejects", async (status) => {
const user = setupUser({ advanceTimers: (delay) => vi.advanceTimersByTime(delay) })
const fetchMock = vi.fn()
- .mockResolvedValueOnce(Response.json({ ok: true, expires_in: 300, resend_after: 60 }))
- .mockResolvedValueOnce(Response.json({ ok: true }, { status }))
+ .mockResolvedValueOnce(currentResponse({ ok: true, expires_in: 300, resend_after: 60 }))
+ .mockResolvedValueOnce(currentResponse({ ok: true }, { status }))
vi.stubGlobal("fetch", fetchMock)
const replace = vi.fn()
vi.stubGlobal("location", { replace })
@@ -146,14 +154,14 @@ describe("retired deletion UI commands", () => {
vi.stubGlobal("fetch", vi.fn((_path, options) => { signal = options.signal; return new Promise<Response>((resolve) => { complete = resolve }) }))
const onDeleted = vi.fn(); const mounted = render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={onDeleted} />)
fireEvent.click(screen.getByTestId(tid.accountDeletionSendCode)); await waitFor(() => expect(complete).toBeTypeOf("function")); mounted.rerender(<output>Current screen</output>)
- await act(async () => complete(Response.json({}, { status: 401 }))); expect(signal.aborted).toBe(true); expect(onDeleted).not.toHaveBeenCalled(); expect(screen.queryByTestId(tid.accountDeletionOtp)).not.toBeInTheDocument()
+ await act(async () => complete(currentResponse({}, { status: 401 }))); expect(signal.aborted).toBe(true); expect(onDeleted).not.toHaveBeenCalled(); expect(screen.queryByTestId(tid.accountDeletionOtp)).not.toBeInTheDocument()
})
it("held failed delete after view retirement cannot publish its old error or invoke completion", async () => {
let complete!: (response: Response) => void; let signal!: AbortSignal
- vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(Response.json({ resend_after: 0 })).mockImplementationOnce((_path, options) => { signal = options.signal; return new Promise<Response>((resolve) => { complete = resolve }) }))
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(currentResponse({ ok: true, expires_in: 300, resend_after: 0 })).mockImplementationOnce((_path, options) => { signal = options.signal; return new Promise<Response>((resolve) => { complete = resolve }) }))
const onDeleted = vi.fn(); const mounted = render(<AccountDeletionFlow email="[email protected]" onCancel={vi.fn()} onDeleted={onDeleted} />)
fireEvent.click(screen.getByTestId(tid.accountDeletionSendCode)); const input = await screen.findByTestId(tid.accountDeletionOtp); fireEvent.change(input, { target: { value: "123456" } }); fireEvent.click(screen.getByTestId(tid.accountDeletionSubmit))
await waitFor(() => expect(complete).toBeTypeOf("function")); mounted.rerender(<output>Current screen</output>)
- await act(async () => complete(Response.json({ error: "ACCOUNT_DELETION_FAILED" }, { status: 500 }))); expect(signal.aborted).toBe(true); expect(onDeleted).not.toHaveBeenCalled(); expect(screen.queryByRole("alert")).not.toBeInTheDocument()
+ await act(async () => complete(currentError("ACCOUNT_DELETION_FAILED", 500))); expect(signal.aborted).toBe(true); expect(onDeleted).not.toHaveBeenCalled(); expect(screen.queryByRole("alert")).not.toBeInTheDocument()
})
})
diff --git a/src/web/src/components/community/settings/account-deletion-flow.tsx b/src/web/src/components/community/settings/account-deletion-flow.tsx
index d02aab6e9..a77317b9d 100644
--- a/src/web/src/components/community/settings/account-deletion-flow.tsx
+++ b/src/web/src/components/community/settings/account-deletion-flow.tsx
@@ -16,6 +16,9 @@ import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
import { communityRequestOptions, retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
import { clearPersistedCache } from "@/lib/query-persister"
+import { z } from "zod"
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION, CommunityReadErrorSchema } from "@alook/shared"
+import { BusinessSchemaMismatch, requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
import { isAbortError } from "@/lib/errors"
import { parseRetryAfterSeconds } from "@/lib/retry-after"
import { tid } from "@/lib/community/testids"
@@ -28,10 +31,19 @@ type Props = {
onDeleted: () => Promise<void>
}
-async function responseError(response: Response): Promise<string> {
+const AccountDeletionCodeReceiptSchema = z.strictObject({ ok: z.literal(true), expires_in: z.number().int().nonnegative(), resend_after: z.number().int().nonnegative() })
+
+function confirmResponse(response: Response) {
+ if (response.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) throw requestBusinessSchemaUpdate(Number(response.headers.get(COMMUNITY_CONTRACT_HEADER)))
+}
+
+async function responseError(response: Response, assertActive: () => void): Promise<string> {
try {
- const body = await response.json() as { error?: string }
- switch (body.error) {
+ confirmResponse(response)
+ const raw: unknown = await response.json()
+ assertActive()
+ const body = CommunityReadErrorSchema.parse(raw)
+ switch (body.error.message) {
case "INVALID_OTP": return "That code is incorrect. Try again."
case "OTP_EXPIRED": return "That code expired. Send a new code."
case "TOO_MANY_ATTEMPTS": return "Too many incorrect attempts. Send a new code."
@@ -39,7 +51,11 @@ async function responseError(response: Response): Promise<string> {
case "CODE_SEND_FAILED": return "We couldn’t send the code. Try again."
case "ACCOUNT_DELETION_FAILED": return "Your account wasn’t deleted. Try again."
}
- } catch {}
+ } catch (error) {
+ assertActive()
+ if (isAbortError(error) || error instanceof BusinessSchemaMismatch) throw error
+ throw requestBusinessSchemaUpdate()
+ }
return "Something went wrong. Try again."
}
@@ -99,7 +115,7 @@ export function AccountDeletionFlow({ email, onCancel, onDeleted }: Props) {
}
const request = useMutation({ meta: { observabilityAction: "account.deletion.command" }, mutationFn: async ({ action, body, source }: { action: "code" | "delete"; body: string; source: ReturnType<typeof capture> }) => {
source.assertActive()
- const response = await fetch(`/api/community/users/me/account-deletion${action === "code" ? "/code" : ""}`, { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body, signal: source.controller.signal })
+ const response = await fetch(`/api/community/users/me/account-deletion${action === "code" ? "/code" : ""}`, { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, body, signal: source.controller.signal })
if (action === "code" || !response.ok) source.assertActive()
return response
} })
@@ -114,11 +130,17 @@ export function AccountDeletionFlow({ email, onCancel, onDeleted }: Props) {
if (response.status === 401) { if (await source.options.onUnauthorized?.()) redirectToSignIn(source.registry.accountId); return }
if (!response.ok) {
const retryAfter = response.status === 429 ? parseRetryAfterSeconds(response.headers) : null
- const message = await responseError(response); source.assertActive()
+ const message = await responseError(response, source.assertActive); source.assertActive()
if (retryAfter) setResendAfter(retryAfter)
setError(message); return
}
- const body = await response.json() as { resend_after: number }; source.assertActive()
+ confirmResponse(response)
+ let raw: unknown
+ try { raw = await response.json(); source.assertActive() }
+ catch (error) { source.assertActive(); if (isAbortError(error)) throw error; throw requestBusinessSchemaUpdate() }
+ const parsed = AccountDeletionCodeReceiptSchema.safeParse(raw)
+ if (!parsed.success) throw requestBusinessSchemaUpdate()
+ const body = parsed.data
setOtp(""); setResendAfter(body.resend_after); setStep("code")
} catch (error) {
if (isAbortError(error)) return
@@ -138,7 +160,7 @@ export function AccountDeletionFlow({ email, onCancel, onDeleted }: Props) {
try {
const response = await request.mutateAsync({ action: "delete", body: JSON.stringify({ otp }), source })
if (!response.ok) {
- const message = await responseError(response); source.assertActive()
+ const message = await responseError(response, source.assertActive); source.assertActive()
cancelAccountDeletionAuthTransition(lease); transition.current = undefined
setOtp(""); setError(message); return
}
diff --git a/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx b/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx
index 4535c6e46..69420ca2a 100644
--- a/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx
+++ b/src/web/src/components/community/settings/account-deletion-owner.dom.test.tsx
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -36,7 +37,7 @@ async function deleteRequest() {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] })
fireEvent.click(screen.getByTestId(tid.accountDeletionSendCode))
await act(async () => { await vi.waitFor(() => expect(held).toHaveLength(1)) })
- await act(async () => held[0].resolve(Response.json({ ok: true, resend_after: 60 })))
+ await act(async () => held[0].resolve(Response.json({ ok: true, expires_in: 300, resend_after: 60 }, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })))
const input = screen.getByTestId(tid.accountDeletionOtp)
await act(async () => { await vi.advanceTimersByTimeAsync(50) })
await act(async () => { fireEvent.change(input, { target: { value: "123456" } }) })
@@ -54,7 +55,7 @@ describe("actual account deletion original root settlement", () => {
await act(async () => { await b.restoreClient(); }) ; await act(async () => { await set(legacyB, "retained legacy B") })
act(() => current.queryClient.setQueryData(["private", "B"], { current: "B" }))
await act(async () => { await set("alook:qc:v2:A:client", "late original A"); }) ; await act(async () => { await set("alook:qc:v2:B:client", "current B") })
- await act(async () => request.resolve(Response.json({ ok: true })))
+ await act(async () => request.resolve(Response.json({ ok: true }, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })))
await waitFor(async () => expect(await get("alook:qc:v2:A:client")).toBeUndefined())
expect(await get("alook:qc:v2:B:client")).toBe("current B"); expect(await b.isCurrent()).toBe(true); expect(await get(legacyB)).toBe("retained legacy B")
expect(original.runtime.lifecycle.get().active).toBe(false); expect(original.queryClient.getQueryCache().getAll()).toHaveLength(0)
@@ -64,14 +65,14 @@ describe("actual account deletion original root settlement", () => {
it("current positive deletion retires its actual parent and navigates even if the parent callback rejects", async () => {
onDeleted.mockRejectedValue(new Error("parent callback failed"))
render(<App />); const request = await deleteRequest(); const original = registry
- await act(async () => request.resolve(Response.json({ ok: true })))
+ await act(async () => request.resolve(Response.json({ ok: true }, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })))
await act(async () => { await vi.waitFor(() => expect(replace).toHaveBeenCalledOnce()) })
expect(onDeleted).toHaveBeenCalledOnce(); expect(original.runtime.lifecycle.get().active).toBe(false); expect(replace).toHaveBeenCalledWith("/sign-in?account_deleted=1")
})
it("a successful deletion callback held across B replacement cannot navigate B on completion", async () => {
let finish!: () => void; onDeleted.mockImplementation(() => new Promise<void>((resolve) => { finish = resolve }))
const view = render(<App />); const request = await deleteRequest()
- await act(async () => request.resolve(Response.json({ ok: true })))
+ await act(async () => request.resolve(Response.json({ ok: true }, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })))
await act(async () => { await vi.waitFor(() => expect(finish).toBeTypeOf("function")) })
sdk.id = "B"; await act(async () => { view.rerender(<App id="B" deletion={false} />) }); await act(async () => { await vi.advanceTimersByTimeAsync(0) }); vi.useRealTimers(); await waitFor(() => expect(registry.accountId).toBe("B")); await waitFor(() => expect(restoring).toBe(false))
await act(async () => finish()); expect(replace).not.toHaveBeenCalled(); expect(registry.runtime.lifecycle.get().active).toBe(true)
diff --git a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
index f6c3b5aea..661b2a04c 100644
--- a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
+++ b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
@@ -12,8 +12,6 @@ import { installMessageScrollFixture, restoreMessageScrollFixture, resize, scrol
import { useCommunityNavigationController } from "./use-community-navigation-controller"
import { normalizeCommunityHref } from "@/lib/community/community-route"
import { resolveCommunityLandingHref } from "@/lib/community/last-channel"
-import { virtualListPositionKey } from "@/lib/community/virtual-list-position"
-import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
import { disposeReadCoordinator, getLocalReadingPosition } from "@/hooks/community/read-coordinator"
import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"
@@ -100,7 +98,7 @@ async function mount(restoring = false, target = href) {
}
describe("cached target through the real route, entry and message consumers", () => {
- it.each([false, true])("keeps the restored offset through an already-active row selection after a server return (StrictMode=%s)", async strict => {
+ it.each([false, true])("uses ordinary tail entry after a server return and preserves an already-active selection (StrictMode=%s)", async strict => {
const entry = conversationEntryFixture()
entry.channel = { ...entry.channel, type: "text", messageCount: 42 }
entry.messages = Array.from({ length: 42 }, (_, index) => ({ ...entry.messages[0], id: `m${index + 1}`, seq: index + 1,
@@ -137,13 +135,7 @@ describe("cached target through the real route, entry and message consumers", ()
fireEvent.wheel(previous, { deltaY: -600 })
act(() => previous.scrollTo({ top: previous.scrollHeight - previous.clientHeight - 600 }))
resize()
- const body = Array.from(previous.querySelectorAll<HTMLElement>("[data-msg-id]"))
- .find(row => row.getBoundingClientRect().bottom > 0)!
- const id = body.dataset.msgId!
- const top = body.getBoundingClientRect().top
const offset = previous.scrollTop
- const scope = { proof: captureChannelMetadataToken(owner.client, "c1"), kind: "messages" as const, tag: null }
- expect(owner.client.getQueryData(virtualListPositionKey(scope))).toMatchObject({ offset })
const go = async (target: string) => {
await act(async () => navigation.push(target))
mocks.href = target
@@ -162,13 +154,14 @@ describe("cached target through the real route, entry and message consumers", ()
await go(serverTarget)
expect(serverTarget).toBe(href)
expect(mocks.load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true)
- expect(root().scrollTop).toBeCloseTo(offset, 0)
- expect(root().querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(top, 0)
+ expect(root().scrollTop).not.toBe(offset)
+ expect(root().scrollHeight - root().clientHeight - root().scrollTop).toBeLessThanOrEqual(1)
+ expect(root().querySelector('[data-message-list-content]')).toHaveAttribute("aria-hidden", "false")
+ const entered = root().scrollTop
const admitted = navigation.entryIntent
await act(async () => { navigation.cancelPendingNavigation(); navigation.push(href) })
resize()
- expect(root().scrollTop).toBeCloseTo(offset, 0)
- expect(root().querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(top, 0)
+ expect(root().scrollTop).toBeCloseTo(entered, 0)
expect(navigation.entryIntent).toBe(admitted)
expect(mocks.load.mock.calls.filter(([url, options]) => String(url).endsWith("/read") && options?.method === "PUT")).toEqual([])
})
diff --git a/src/web/src/components/community/shell/community-list-errors.dom.test.tsx b/src/web/src/components/community/shell/community-list-errors.dom.test.tsx
index db81c062e..0b5a48017 100644
--- a/src/web/src/components/community/shell/community-list-errors.dom.test.tsx
+++ b/src/web/src/components/community/shell/community-list-errors.dom.test.tsx
@@ -1,3 +1,4 @@
+import { friendBucketScenarioFixture, dmListRowFixture } from "@/test/community-resource-fixtures"
import { beforeEach, expect, it, vi } from "vitest"
import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
@@ -21,16 +22,16 @@ vi.mock("@/hooks/community/use-inbox", () => ({ useInboxUnreads: () => ({ friend
beforeEach(() => { load.mockReset() })
type Kind = "friends" | "dms"
-const friend = { id: "friendship", userId: "peer", name: "Cached person", discriminator: "0001", avatar: "P", status: "offline", sub: "" }
-const dm = { id: "dm", userId: "peer", name: "Cached person", discriminator: "0001", avatar: "P", status: "offline", preview: "Cached conversation" }
+const friend = { id: "friendship", userId: "peer", name: "Cached person", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline" as const, sub: "" }
+const dm = { id: "dm", userId: "peer", name: "Cached person", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline" as const, preview: "Cached conversation" }
const primaryPath = (kind: Kind) => kind === "friends" ? "/api/community/friends/accepted" : "/api/community/users/me/dms"
const key = (kind: Kind) => kind === "friends" ? communityKeys.friends() : communityKeys.dms()
const emptyText = (kind: Kind) => kind === "friends" ? "No friends yet. Add someone from the New tab." : "Your direct messages will appear here."
function response(path: string, populated = false) {
- if (path.endsWith("/accepted")) return { friends: populated ? [friend] : [] }
- if (path.endsWith("/blocked")) return { blocked: [] }
- if (path.endsWith("/pending")) return { pending: [] }
- if (path.endsWith("/dms")) return { conversations: populated ? [dm] : [] }
+ if (path.endsWith("/accepted")) return friendBucketScenarioFixture("friends", populated ? [friend] : [])
+ if (path.endsWith("/blocked")) return friendBucketScenarioFixture("blocked", [])
+ if (path.endsWith("/pending")) return friendBucketScenarioFixture("pending", [])
+ if (path.endsWith("/dms")) return { conversations: populated ? [dmListRowFixture(dm)] : [] }
throw new Error(`Unexpected list request: ${path}`)
}
function SharedAccountReader() { useFriends(); return null }
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 562b432b9..3628c84b3 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,3 +1,5 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent, render as renderDom, screen, setupUser, waitFor } from "@/test/react-dom-harness"
@@ -104,7 +106,7 @@ describe("CommunityWsReconnectBoundary", () => {
expect(screen.queryByTestId(tid.wsReconnectOverlay)).not.toBeInTheDocument()
expect(renderer.container.querySelector(".contents")).not.toHaveAttribute("inert")
expect(apiFetchMock).toHaveBeenCalledTimes(3)
- apiFetchMock.mockResolvedValue({ messages: [{ id: "m_1", seq: 1, content: "recovered" }], latestSeq: 1 })
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({ messages: [messageResourceFixture({ id: "m_1", channelId: "repair-status", content: "recovered" })], latestSeq: 1 }))
const retry = screen.getByTestId(tid.messageRepairRetry)
retry.focus()
await setupUser().keyboard("{Enter}")
diff --git a/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
index a2d494af1..d647ffa34 100644
--- a/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
@@ -1,3 +1,4 @@
+import { serverDirectoryFixture, serverRailResponseFixture, channelResourceFixture, categoryResourceFixture } from "@/test/community-resource-fixtures"
import { beforeEach, expect, it, vi } from "vitest"
import { useLayoutEffect } from "react"
import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"
@@ -31,22 +32,21 @@ async function setup(method: "push" | "pushImmediate", { cold = false, empty = f
const { client, registry } = await createCommunityQueryOwner()
const server = { id: "target", name: "Target", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
mocks.breakpoint = mobile ? "mobile" : "desktop"
- mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })
+ mocks.load.mockResolvedValueOnce(serverRailResponseFixture({ servers: [{ ...server, role: "owner", memberId: "membership" }] }))
await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client) })
const channels = empty ? [] : [{ id: "channel", name: "Channel", active: false, unread: false, muted: false, type: "text" as const }]
if (!cold) {
publishCommunityLiveSnapshot(client, {
- snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: "", private: 0, channels }] } },
+ snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: "", private: false, channels }] }) },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
- client.setQueryData(communityKeys.server(server.id), server.id)
}
let release!: () => void
const response = new Promise<void>(resolve => { release = resolve })
mocks.load.mockImplementation(async (path: string) => {
await response
- if (path.endsWith("/categories")) return { categories: [{ id: "category", name: "", private: 0 }] }
- if (path.endsWith("/channels")) return { channels: channels.map(channel => ({ ...channel, categoryId: "category" })) }
+ if (path.endsWith("/categories")) return { categories: [categoryResourceFixture({ id: "category", serverId: server.id, name: "", private: false })] }
+ if (path.endsWith("/channels")) return { channels: channels.map(channel => channelResourceFixture({ id: channel.id, name: channel.name, type: channel.type, serverId: server.id, categoryId: "category" })) }
throw new Error(`Unexpected request ${path}`)
})
const calls: string[] = []
@@ -111,7 +111,7 @@ it("finishes the current root after an older server deletion retires its in-flig
const token = createOwnerServerDeleteRouteToken(client)
act(() => {
publishCommunityLiveSnapshot(client, {
- snapshot: { kind: "server-detail", data: { id: "deleted", name: "Deleted", discriminator: "0002", description: "", icon: null, ownerId: "viewer", categories: [{ id: "old-category", name: "", private: 0, channels: [{ id: "old-channel", name: "Old", active: false, unread: false }] }] } },
+ snapshot: { kind: "server-detail", data: serverDirectoryFixture({ id: "deleted", name: "Deleted", discriminator: "0002", description: "", icon: null, ownerId: "viewer", categories: [{ id: "old-category", name: "", private: false, channels: [{ id: "old-channel", name: "Old", active: false, unread: false }] }] }) },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
beginOwnerServerDelete(client, "deleted", token)
@@ -133,7 +133,7 @@ it("finishes the current root after an older server deletion retires its in-flig
})
expect(client.getQueryCache().find({ queryKey: communityKeys.server("target"), exact: true })).toBe(original)
expect(registry.collections.servers.get("deleted")).toBeUndefined()
- expect(registry.collections.servers.get("target")?.detailComplete).toBe(true)
+ expect(registry.collections.servers.has("target")).toBe(true)
expect(original.state.error).toBeNull()
expect(mocks.load.mock.calls.filter(([path]) => String(path).endsWith("/target/categories"))).toHaveLength(2)
})
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
index faf047e4d..f7478d045 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { serverRailResponseFixture, serverDirectoryFixture, resourceBundleFixture } from "@/test/community-resource-fixtures"
import { IsRestoringProvider } from "@tanstack/react-query"
import { useLayoutEffect } from "react"
import { beforeEach, expect, it, vi } from "vitest"
@@ -30,12 +32,13 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
const { client, registry } = await createCommunityQueryOwner()
const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
const proof = { kind: "structural" as const, token: captureCommunityLiveSnapshotToken(client), signal: undefined }
- mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })
+ mocks.load.mockResolvedValueOnce(serverRailResponseFixture({ servers: [{ ...server, role: "owner", isOwner: true, memberId: "membership" }] }))
await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client) })
mocks.load.mockClear()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: grouped ? "Group" : "", private: 0, channels: [{ id: "channel", name: "Target channel", active: false, unread: true, muted: false, type: "text" }] }] } }, proof })
- client.setQueryData(communityKeys.server(server.id), server.id)
- client.setQueryData(communityKeys.forumSidebarThreads(server.id), { threads: [], verifiedEpoch: 0, serverNow: new Date().toISOString(), serverClockOffsetMs: 0, window: { version: 1, accountId: registry.accountId, serverId: server.id, parents: ["channel"], base: [], retained: null } })
+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: grouped ? "Group" : "", private: false, channels: [{ id: "channel", name: "Target channel", active: false, unread: true, muted: false, type: "text" }] }] }) }, proof })
+ client.setQueryData(communityKeys.forumSidebarThreads(server.id), { threads: [], verifiedEpoch: 0, serverNow: new Date().toISOString(), serverClockOffsetMs: 0, window: { version: BUSINESS_SCHEMA_VERSION, accountId: registry.accountId, serverId: server.id, parents: ["channel"], base: [], retained: null } })
+ registry.collections.channelMemberships.utils.writeUpsert({ id: "channel:viewer:access", channelId: "channel", userId: "viewer", relation: "access", source: "explicit" })
+ registry.runtime.ws.actions.rememberChannelAccess(server.id, "channel")
const token = createOwnerServerDeleteRouteToken(client)
function Harness({ frame }: { frame: CommunityCommittedFrame }) {
const navigation = useCommunityNavigationController(frame)
@@ -61,7 +64,7 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
const indicator = () => row.querySelector('[data-slot="community-channel-unread-indicator"]')
expect(indicator()).toHaveClass("h-0")
const attention = (seq: number) => publishAccountAttentionSnapshot(client, {
- snapshot: { scopes: [{ scopeId: "channel", channelId: "channel", serverId: server.id, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: seq, attentionCount: 0, lastAttentionSeq: null }], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
+ snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: "channel", channelId: "channel", serverId: server.id, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: seq, attentionCount: 0, lastAttentionSeq: null }], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
await act(async () => { attention(4) })
@@ -76,7 +79,7 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
await waitFor(() => expect(indicator()).toHaveClass("h-2.5"))
await act(async () => {
restoreAttentionScopeOptimisticSnapshot(registry, optimistic)
- publishAccountAttentionSnapshot(client, { snapshot: { scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }, proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ publishAccountAttentionSnapshot(client, { snapshot: { resources: resourceBundleFixture(), scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }, proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
})
await waitFor(() => expect(indicator()).toHaveClass("h-0"))
const title = view.getByRole("button", { name: "Target server" })
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
index 82dd12e5e..43b88b03a 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { serverDirectoryFixture, serverRailResponseFixture, channelResourceFixture, serverResourceFixture, fullResourceBundleFixture } from "@/test/community-resource-fixtures"
import { IsRestoringProvider } from "@tanstack/react-query"
import { beforeEach, expect, it, vi } from "vitest"
import { act, fireEvent, render, waitFor } from "@/test/react-dom-harness"
@@ -29,10 +31,9 @@ it("uses the canonical target sidebar before commit, retaining its node while de
const { client, registry } = await createCommunityQueryOwner()
const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
const proof = { kind: "structural" as const, token: captureCommunityLiveSnapshotToken(client), signal: undefined }
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: { servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0, isOwner: true, role: "owner", memberId: "membership" }] } }, proof })
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: "Main", private: 0, channels: [{ id: "channel", name: "Target channel", active: false, unread: false, muted: false, type: "text" }] }] } }, proof })
+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0, isOwner: true, role: "owner", memberId: "membership" }] }, "viewer") }, proof })
+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [{ id: "category", name: "Main", private: false, channels: [{ id: "channel", name: "Target channel", active: false, unread: false, muted: false, type: "text" }] }] }) }, proof })
client.setQueryData(communityKeys.servers(), [server.id])
- client.setQueryData(communityKeys.server(server.id), server.id)
const sourceToken = createOwnerServerDeleteRouteToken(client)
const targetToken = createOwnerServerDeleteRouteToken(client)
const node = (committed: boolean) => <CommunityTestProvider client={client} registry={registry}>
@@ -67,7 +68,7 @@ it.each(["primary", "forum"])("ends a failed cold %s read with retry", async kin
const { client, registry } = await createCommunityQueryOwner()
const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
publishCommunityLiveSnapshot(client, {
- snapshot: { kind: "servers", data: { servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0 }] } },
+ snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ ...server, initial: "T", active: false, unread: false, mentions: 0 }] }, "viewer") },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
client.setQueryData(communityKeys.servers(), [server.id])
@@ -76,9 +77,9 @@ it.each(["primary", "forum"])("ends a failed cold %s read with retry", async kin
if (url === "/api/community/servers/target/categories") {
return kind === "primary" && fail ? Promise.reject(new Error("Temporary read failure")) : Promise.resolve({ categories: [] })
}
- if (url === "/api/community/servers/target/channels") return Promise.resolve({ channels: kind === "forum" ? [{ id: "forum", name: "Forum", type: "forum", categoryId: null, position: 0 }] : [] })
+ if (url === "/api/community/servers/target/channels") return Promise.resolve({ channels: kind === "forum" ? [channelResourceFixture({ id: "forum", serverId: "target", name: "Forum", type: "forum" })] : [] })
if (url.startsWith("/api/community/servers/target/channels?")) {
- return kind === "forum" && fail ? Promise.reject(new Error("Forum unavailable")) : Promise.resolve({ channels: [], included: { parentMessages: [] }, serverNow: new Date().toISOString() })
+ return kind === "forum" && fail ? Promise.reject(new Error("Forum unavailable")) : Promise.resolve({ schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: "target", channels: [], canonicalChannels: [], retainedChannel: null, retainedDisposition: null, serverNow: new Date().toISOString(), resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "target", name: "Target server", ownerId: "viewer" })], kind === "forum" ? [channelResourceFixture({ id: "forum", serverId: "target", name: "Forum", type: "forum" })] : []) })
}
return new Promise(() => {})
})
@@ -99,7 +100,7 @@ it.each(["primary", "forum"])("ends a failed cold %s read with retry", async kin
await waitFor(() => expect(view.queryByRole("alert")).toBeNull())
expect(view.getByText("Target server")).toBeVisible()
expect(mocks.load.mock.calls.filter(([path]) => path === "/api/community/servers/target/categories")).toHaveLength(kind === "primary" ? 2 : 1)
- expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ categories: kind === "primary" ? [] : expect.arrayContaining([expect.objectContaining({ channels: [expect.objectContaining({ id: "forum" })] })]), primaryReady: true, forumProjectionMissing: false }))
+ await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ categories: kind === "primary" ? [] : expect.arrayContaining([expect.objectContaining({ channels: [expect.objectContaining({ id: "forum" })] })]), primaryReady: true, forumProjectionMissing: false })))
})
@@ -128,7 +129,7 @@ it.each([
mocks.search = `keep=${marker}`
view.rerender(node())
const qualify = async () => {
- mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role, memberId: "membership" }] })
+ mocks.load.mockResolvedValueOnce(serverRailResponseFixture({ servers: [{ ...server, role, isOwner: role === "owner", memberId: "membership" }] }, "viewer"))
await act(async () => { await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client), staleTime: 0 }) })
}
if (order === "owner-first") {
@@ -136,15 +137,18 @@ it.each([
await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ onOpenSettings: expect.any(Function) })))
expect(view.queryByText("Server settings")).toBeNull()
}
- act(() => { publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: { ...server, categories: [] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } }) })
- await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ serverName: "Target server", onOpenSettings: undefined, onInvitePopoverOpenChange: undefined })))
- expect(view.queryByText("Server settings")).toBeNull()
- if (order === "detail-first") await qualify()
- act(() => { client.setQueryData(communityKeys.server(server.id), server.id) })
+ act(() => { publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: [] }) }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } }) })
+ view.rerender(node())
+ await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ serverName: "Target server", primaryReady: true })))
+ if (order === "detail-first") {
+ expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ onOpenSettings: undefined }))
+ expect(view.queryByText("Server settings")).toBeNull()
+ await qualify()
+ }
view.rerender(node())
if (role === "member") {
expect(view.queryByText("Server settings")).toBeNull()
- mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })
+ mocks.load.mockResolvedValueOnce(serverRailResponseFixture({ servers: [{ ...server, role: "owner", isOwner: true, memberId: "membership" }] }, "viewer"))
await act(async () => { await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client), staleTime: 0 }) })
await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ onOpenSettings: expect.any(Function) })))
expect(view.queryByText("Server settings")).toBeNull()
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsx
index da3f971bd..053431e92 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx
@@ -1,4 +1,5 @@
"use client"
+import { getServerDirectoryWindow } from "@/lib/community/server-directory-window"
import { readCommunityServerRailServers } from "@/lib/community-db/server-rail"
import { useAtom, useCreateAtom, useSelector } from "@tanstack/react-store";
import { getCommunityRuntime } from "@/stores/community/runtime"
@@ -194,7 +195,7 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; h
const serverDestination = useCallback(async (id: string) => {
const lastChannel = getLastChannel(id)
const read = () => communityDb ? Array.from(communityDb.collections.channels.values()).filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending).map((channel) => channel.id) : []
- if (!communityDb?.collections.servers.get(id)?.detailComplete && !lastChannel && read().length === 0) {
+ if (!getServerDirectoryWindow(communityDb, id) && !lastChannel && read().length === 0) {
try {
await queryClient.query({ queryKey: communityKeys.server(id), queryFn: ({ signal }) => serverProjectedQueryFn(queryClient, id, signal)(), staleTime: Infinity, select: undefined })
} catch {}
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 69ed2201d..96b39d823 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
@@ -2,10 +2,9 @@ import { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
import { describe, expect, it } from "vitest"
import { UnresolvedMainSkeleton } from "./unresolved-main-skeleton"
-import { appBackdropClassName } from "@/components/ui/app-edge-fade"
describe("UnresolvedMainSkeleton", () => {
- it("keeps neutral loading motion on the shared translucent backdrop with four inert edges", () => {
+ it("keeps neutral loading motion on an opaque app background", () => {
const markup = renderToStaticMarkup(createElement(UnresolvedMainSkeleton))
expect(markup).not.toContain('data-slot="skeleton"')
@@ -18,16 +17,13 @@ describe("UnresolvedMainSkeleton", () => {
expect(markup).toContain('data-community-unresolved-main=""')
expect(markup).toContain('aria-hidden="true"')
expect(markup).toContain("h-full w-full flex-1 overflow-hidden")
- for (const token of appBackdropClassName.split(" ")) expect(markup).toContain(token)
- expect(markup).not.toMatch(/class="[^"]*\sbg-\(--app-bg\)/)
+ expect(markup).toContain("bg-(--app-bg)")
+ expect(markup).not.toContain("bg-black/10")
+ expect(markup).not.toContain("backdrop-blur")
+ expect(markup).toContain('data-connecting-motion=""')
expect(markup).not.toContain("animate-pulse")
- expect(markup.match(/data-slot="app-edge-fade"/g)).toHaveLength(1)
- expect(markup.match(/h-\(--app-edge-fade-size\)/g)).toHaveLength(2)
- expect(markup.match(/w-\(--app-edge-fade-size\)/g)).toHaveLength(2)
- expect(markup.match(/data-app-edge=/g)).toHaveLength(4)
- expect(markup).toContain("from-(--app-bg) to-transparent")
- expect(markup).toContain("from-transparent to-(--app-bg)")
- expect(markup).toContain("pointer-events-none")
+ expect(markup).not.toContain('data-slot="app-edge-fade"')
+ expect(markup).not.toContain("data-app-edge=")
expect(markup).not.toContain("safe-area")
expect(markup).not.toMatch(/rounded-(?:sm|md|lg|xl|2xl|3xl|full)(?:\s|")/)
})
diff --git a/src/web/src/components/community/shell/unresolved-main-skeleton.tsx b/src/web/src/components/community/shell/unresolved-main-skeleton.tsx
index 6446eaa8e..ffad765ec 100644
--- a/src/web/src/components/community/shell/unresolved-main-skeleton.tsx
+++ b/src/web/src/components/community/shell/unresolved-main-skeleton.tsx
@@ -1,17 +1,14 @@
import { CommunityConnectingIndicator } from "./community-connecting-indicator"
-import { AppEdgeFade, appBackdropClassName } from "@/components/ui/app-edge-fade"
-import { cn } from "@/lib/utils"
export function UnresolvedMainSkeleton() {
return (
<div
data-community-unresolved-main=""
- className={cn("relative grid place-items-center min-h-0 h-full w-full flex-1 overflow-hidden", appBackdropClassName)}
+ className="relative grid place-items-center min-h-0 h-full w-full flex-1 overflow-hidden bg-(--app-bg)"
>
<div className="relative z-20 flex w-full max-w-xs flex-col items-center text-center text-foreground">
<CommunityConnectingIndicator />
</div>
- <AppEdgeFade />
</div>
)
}
diff --git a/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx b/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
index d5e26a6b4..aa35a0ed9 100644
--- a/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-community-rail-hrefs.dom.test.tsx
@@ -1,3 +1,7 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { serverResourceFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
import { createElement } from "react"
import { renderToString } from "react-dom/server"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -29,12 +33,12 @@ afterEach(() => { vi.restoreAllMocks() })
describe("rail hrefs derived from canonical rows and existing navigation memory", () => {
it.each(["desktop", "mobile", "unknown"] as const)("server-renders deterministic %s links without reading client memory or subscribing", (breakpoint) => {
- const servers = collection([["s", { detailComplete: true }], ["other", { detailComplete: true }]])
+ const servers = collection([["s", serverResourceFixture({ id: "s" })], ["other", serverResourceFixture({ id: "other" })]])
const channels = collection([
- ["first", { id: "first", serverId: "s", type: "text" }],
- ["second", { id: "second", serverId: "other", type: "text" }],
+ ["first", channelResourceFixture({ id: "first", serverId: "s" })],
+ ["second", channelResourceFixture({ id: "second", serverId: "other" })],
])
- owner.registry = { collections: { servers, channels } } as unknown as CommunityDbRegistry
+ owner.registry = { queryClient: new QueryClient(), accountId: "viewer", scopeId: "viewer", collections: { servers, categories: collection([]), channels } } as unknown as CommunityDbRegistry
setLastMeLocation("/c/me/machines")
setLastChannel("s", "remembered")
setLastChannel("other", "other-remembered")
@@ -78,19 +82,22 @@ describe("rail hrefs derived from canonical rows and existing navigation memory"
})
it("subscribes to complete canonical channels, filters placeholders/threads, and follows the latest memory", () => {
- const servers = collection<{ detailComplete: boolean }>([["s", { detailComplete: false }]])
- const channels = collection<{ id: string; serverId: string; type: string; pending?: boolean }>([
- ["pending", { id: "pending", serverId: "s", type: "text", pending: true }],
- ["thread", { id: "thread", serverId: "s", type: "thread" }],
- ["first", { id: "first", serverId: "s", type: "text" }],
- ["foreign", { id: "foreign", serverId: "other", type: "text" }],
+ const servers = collection([["s", serverResourceFixture({ id: "s" })]])
+ const channels = collection<ReturnType<typeof channelResourceFixture> & { pending?: boolean }>([
+ ["pending", { ...channelResourceFixture({ id: "pending", serverId: "s" }), pending: true }],
+ ["thread", channelResourceFixture({ id: "thread", serverId: "s", type: "thread", parentChannelId: "first", parentMessageId: "opener" })],
+ ["first", channelResourceFixture({ id: "first", serverId: "s" })],
+ ["foreign", channelResourceFixture({ id: "foreign", serverId: "other" })],
])
- owner.registry = { collections: { servers, channels } } as unknown as CommunityDbRegistry
+ owner.registry = { queryClient: new QueryClient(), accountId: "viewer", scopeId: "viewer", collections: { servers, categories: collection([]), channels } } as unknown as CommunityDbRegistry
const rows = [{ id: "s" }]
const view = renderHook(({ breakpoint }: { breakpoint: "desktop" | "mobile" }) =>
useCommunityRailHrefs(rows, breakpoint), { initialProps: { breakpoint: "desktop" } })
expect(view.result.current.serverHrefs.s).toBe("/c/channels/s")
- act(() => servers.put("s", { detailComplete: true }))
+ act(() => {
+ owner.registry!.queryClient.setQueryData(communityKeys.server("s"), { schemaVersion: BUSINESS_SCHEMA_VERSION, accountId: "viewer", serverId: "s", categoryIds: [], channelIds: ["first"] })
+ servers.put("s", serverResourceFixture({ id: "s" }))
+ })
expect(view.result.current.serverHrefs.s).toBe("/c/channels/s/first")
act(() => setLastChannel("s", "latest"))
expect(view.result.current.serverHrefs.s).toBe("/c/channels/s/latest")
diff --git a/src/web/src/components/community/shell/use-community-rail-hrefs.ts b/src/web/src/components/community/shell/use-community-rail-hrefs.ts
index 58880d7f7..3251b22e3 100644
--- a/src/web/src/components/community/shell/use-community-rail-hrefs.ts
+++ b/src/web/src/components/community/shell/use-community-rail-hrefs.ts
@@ -1,5 +1,6 @@
"use client"
+import { getServerDirectoryWindow } from "@/lib/community/server-directory-window"
import { useCallback, useMemo, useSyncExternalStore } from "react"
import type { Breakpoint } from "@/hooks/use-mobile"
import type { CommunityDbRegistry } from "@/lib/community-db/collections"
@@ -11,7 +12,7 @@ import { readNavigationMemory, subscribeNavigationMemory } from "@/lib/community
export function communityServerLandingHref(
registry: CommunityDbRegistry | null, id: string, last: string | null, breakpoint: Breakpoint, canonicalChannelIds?: readonly string[],
) {
- const complete = registry?.collections.servers.get(id)?.detailComplete === true
+ const complete = Boolean(getServerDirectoryWindow(registry, id))
const channelIds = registry && complete
? canonicalChannelIds ?? Array.from(registry.collections.channels.values())
.filter((channel) => channel.serverId === id && channel.type !== "thread" && !channel.pending)
diff --git a/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx b/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx
index 0102dc348..1934b483b 100644
--- a/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-daemon-update-controller.restore.dom.test.tsx
@@ -17,7 +17,7 @@ it.each([false, true])("preserves collapsed preference through native restored l
const owner = await createCommunityQueryOwner("user-1")
const disk = createIdbPersister("user-1")
const seed = new QueryClient()
- seed.setQueryData(communityKeys.machines(), { machines: empty ? [] : [machine] })
+ seed.setQueryData(communityKeys.machines(), { machines: empty ? [] : [machine], complete: true })
await disk.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(seed) })
const restored = await disk.restoreClient()
expect(restored).toBeDefined()
@@ -40,12 +40,12 @@ it.each([false, true])("preserves collapsed preference through native restored l
try {
await waitFor(() => expect(transport.load).toHaveBeenCalledWith("/api/community/machines?view=list", expect.anything()))
expect(window.localStorage.getItem(key)).toBe("1")
- await act(async () => { release({ machines: [machine] }) })
+ await act(async () => { release({ machines: [machine], complete: true }) })
await waitFor(() => expect(state.update?.phase).toBe("collapsedBadge"))
expect(state.active).toBe("none")
expect(window.localStorage.getItem(key)).toBe("1")
} finally {
- await act(async () => { release({ machines: [machine] }) })
+ await act(async () => { release({ machines: [machine], complete: true }) })
view.unmount();seed.clear();owner.client.clear()
window.localStorage.removeItem(key)
}
@@ -55,7 +55,7 @@ it("clears a restored collapse preference after a qualified fresh empty list", a
const owner = await createCommunityQueryOwner("user-1")
const disk = createIdbPersister("user-1")
const seed = new QueryClient()
- seed.setQueryData(communityKeys.machines(), { machines: [machine] })
+ seed.setQueryData(communityKeys.machines(), { machines: [machine], complete: true })
await disk.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(seed) })
const restored = await disk.restoreClient()
hydrate(owner.client, restored!.clientState)
@@ -76,12 +76,12 @@ it("clears a restored collapse preference after a qualified fresh empty list", a
try {
await waitFor(() => expect(transport.load).toHaveBeenCalledWith("/api/community/machines?view=list", expect.anything()))
expect(window.localStorage.getItem(key)).toBe("1")
- await act(async () => { release({ machines: [] }) })
+ await act(async () => { release({ machines: [], complete: true }) })
await waitFor(() => expect(window.localStorage.getItem(key)).toBeNull())
expect(owner.client.getQueryData<MachinesResponse>(communityKeys.machines())).toMatchObject({ machines: [], source: "network" })
expect(state).toEqual(initialUserBarExtensionState)
} finally {
- await act(async () => { release({ machines: [] }) })
+ await act(async () => { release({ machines: [], complete: true }) })
view.unmount(); seed.clear(); owner.client.clear()
window.localStorage.removeItem(key)
}
@@ -124,7 +124,7 @@ it("syncs the same eligible machine identity only when its partial list becomes
expect(transport.load.mock.calls.filter(([url]) => String(url).includes("view=list"))).toHaveLength(1)
} finally {
view.unmount(); owner.client.clear()
- await act(async () => { release({ machines: rows }) })
+ await act(async () => { release({ machines: rows, complete: true }) })
window.localStorage.removeItem(key)
}
})
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 9704721cb..95f7210ee 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.dom.test.ts
@@ -1,3 +1,4 @@
+import { attentionSnapshotScenarioFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import { createElement } from "react"
import { type QueryClient, useQueryClient, useIsRestoring } from "@tanstack/react-query"
@@ -5,7 +6,7 @@ import { act, waitFor, renderHook, render as rtlRender } from "@/test/react-dom-
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { QueryProvider } from "@/app/c/QueryProvider"
import { communityKeys } from "@/lib/query-keys"
-import { getCanonicalCommunityChannels, retireCommunityChannelReading } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishAccountAttentionSnapshot, getCanonicalCommunityChannels, retireCommunityChannelReading } from "@/lib/community-db/sync"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { channelMetadataOptions, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"
@@ -380,9 +381,16 @@ describe("useShellInboxController", () => {
})
- it("upserts a DM after projection/cancel and starts the common entry at push", async () => {
+ it("uses the complete Attention DM resource and starts the common entry at push", async () => {
const hook = await renderController()
order.length = 0
+ await act(async () => { publishAccountAttentionSnapshot(hook.queryClient, {
+ snapshot: attentionSnapshotScenarioFixture({ scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], messages: [],
+ dms: [{ id: "dm1", userId: "u2", name: "Peer", discriminator: "2222", avatar: "P", avatarVersion: 0, lastMessageAt: unreadDm.lastMessageAt, lastUnreadSeq: 1 }],
+ profiles: [{ userId: "u2", name: "Peer", discriminator: "2222", avatar: "P", avatarVersion: 0 }] } }),
+ proof: { token: captureCommunityLiveSnapshotToken(hook.queryClient) },
+ }) })
+ order.length = 0
await act(async () => hook.current.popoverProps.onOpenDm?.(unreadDm))
expect(order).toEqual([
"project",
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 524ffa7e5..022b17306 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
@@ -43,7 +43,7 @@ vi.mock("sonner", () => ({ toast: mocks.toast }))
vi.mock("@/lib/api/client", () => ({
ACCOUNT_DELETED_SIGN_IN_PATH: "/sign-in?account_deleted=1",
toastApiError: mocks.toastApiError,
- apiFetch: (path: string, options: { method?: string; body?: string }) => Promise.resolve(options?.method === "PATCH" ? mocks.updateProfile(JSON.parse(options.body!)) : mocks.query(path, options)).then((data) => path.startsWith("/api/community/users/search?") ? { users: [], ...data } : ({ id: path.split("/").at(-2), name: "Remote", discriminator: "0001", image: null, avatarVersion: 0, bannerColor: null, aboutMe: "", mutualServers: 0, statusEmoji: null, statusText: null, kind: "human", ...data })),
+ apiFetch: (path: string, options: { method?: string; body?: string }) => Promise.resolve(options?.method === "PATCH" ? mocks.updateProfile(JSON.parse(options.body!)) : mocks.query(path, options)).then((data) => options?.method === "PATCH" ? data : path.startsWith("/api/community/users/search?") ? { users: [], ...data } : ({ id: path.split("/").at(-2), name: "Remote", discriminator: "0001", image: null, avatarVersion: 0, bannerColor: null, aboutMe: "", mutualServers: 0, statusEmoji: null, statusText: null, kind: "human", ...data })),
}))
vi.mock("@/lib/community/image-crop", () => ({ validateIconSourceFile: mocks.validate }))
vi.mock("@/contexts/community/current-user", () => ({
@@ -183,6 +183,21 @@ describe("useShellProfileController", () => {
vi.restoreAllMocks()
})
+ it.each(["cold", "warm", "newer"])("keeps a null handle lookup avatar canonical with mode=%s", async mode => {
+ const { writeCommunityProfilePatches } = await import("@/lib/community/profile-seed")
+ const request = deferred<{ users: Array<{ id: string; name: string; discriminator: string; image: null; avatarVersion: number }> }>()
+ mocks.query.mockImplementation((path: string) => path.startsWith("/api/community/users/search?") ? request.promise : new Promise(() => {}))
+ const hook = await renderController()
+ if (mode !== "cold") writeCommunityProfilePatches([{ id: "lookup", identityAbout: { name: "Alice", discriminator: "0042", aboutMe: "Keep complete", bannerColor: "#123456" }, avatar: { avatar: "old-image", avatarVersion: 2 }, status: { statusText: "Keep status", statusEmoji: "🙂" } }], hook.registry)
+ await act(async () => hook.current.openProfile("Alice", { clientX: 4, clientY: 5 } as never, "0042"))
+ await waitFor(() => expect(mocks.query.mock.calls.some(([path]) => path.startsWith("/api/community/users/search?"))).toBe(true))
+ if (mode === "newer") writeCommunityProfilePatches([{ id: "lookup", identityAbout: { name: "Newer Alice" }, avatar: { avatar: "newer-image", avatarVersion: 3 }, status: { statusText: "Newer status" } }], hook.registry, { command: true })
+ await act(async () => request.resolve({ users: [{ id: "lookup", name: "Alice", discriminator: "0042", image: null, avatarVersion: 2 }] }))
+ await waitFor(() => expect(hook.queryClient.getQueryData(["community", "user-search", "Alice#0042"])).toEqual(["lookup"]))
+ expect(hook.registry.collections.profiles.get("lookup")).toMatchObject({ avatar: mode === "newer" ? "newer-image" : null, avatarVersion: mode === "newer" ? 3 : 2, name: mode === "newer" ? "Newer Alice" : "Alice", discriminator: "0042", ...(mode !== "cold" ? { aboutMe: "Keep complete", bannerColor: "#123456", statusText: mode === "newer" ? "Newer status" : "Keep status" } : {}) })
+ hook.renderer.unmount()
+ })
+
it.each(["settings=billing", "billing=checkout", "billing=cancel", "billing=portal"])("opens billing settings from %s and clears only billing navigation on close", async (marker) => {
mocks.search = `${marker}&audit=bot1`
window.history.replaceState(null, "", `/c/me/bots?${mocks.search}#details`)
@@ -436,7 +451,7 @@ describe("useShellProfileController", () => {
statusText: "",
kind: "bot",
ownerProfile: { id: "owner", handle: "Owner#0042" },
- ownedByViewer: true,
+ ownedByViewer: false,
}).mockResolvedValueOnce({
id: "owner",
aboutMe: "owner",
@@ -458,7 +473,7 @@ describe("useShellProfileController", () => {
expect(hook.current.profile?.data.identity).toEqual({
kind: "bot",
ownerProfile: { id: "owner", handle: "Owner#0042" },
- ownedByViewer: true,
+ ownedByViewer: false,
})
await act(async () => hook.current.openOwnerProfile({ id: "owner", handle: "Owner#0042" }))
@@ -525,6 +540,7 @@ describe("useShellProfileController", () => {
it("seeds canonical mutation responses through the captured request snapshot", async () => {
const hook = await renderController()
+ hook.registry.collections.profiles.utils.writeUpsert({ id: "self", name: "Self", discriminator: "0001", avatar: null, avatarVersion: 0 })
await act(async () => hook.current.updateOwnStatus("🌱", "Growing"))
expect(mocks.updateProfile).toHaveBeenLastCalledWith({
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.relationship.dom.test.tsx b/src/web/src/components/community/shell/use-shell-profile-controller.relationship.dom.test.tsx
index 325c93022..18b62d247 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.relationship.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.relationship.dom.test.tsx
@@ -1,3 +1,4 @@
+import { friendBucketScenarioFixture, staleFriendBucketFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import React from "react"
import { useQueryClient, type QueryClient } from "@tanstack/react-query"
@@ -39,11 +40,12 @@ vi.mock("@/hooks/community/use-server-members", () => ({
const peer = { id: "relationship-peer", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", sub: "" }
const empty = { friends: [], pending: [], blocked: [] }
type Buckets = { friends: unknown[]; pending: unknown[]; blocked: unknown[] }
-function response(path: string, buckets: Buckets = { ...empty, friends: [peer] }) {
- if (path.endsWith("/accepted")) return { friends: buckets.friends }
- if (path.endsWith("/pending")) return { pending: buckets.pending }
- if (path.endsWith("/blocked")) return { blocked: buckets.blocked }
- if (path.endsWith("/profile")) return { id: path.split("/").at(-2), name: "Peer", discriminator: "0001", image: null, avatarVersion: 0, kind: "human", aboutMe: "", mutualServers: 0, statusEmoji: null, statusText: null }
+function response(path: string, buckets: Buckets = { ...empty, friends: [peer] }, viewerId = mocks.viewer) {
+ const data = (bucket: "friends" | "pending" | "blocked") => friendBucketScenarioFixture(bucket, buckets[bucket] as Array<typeof peer>, viewerId)
+ if (path.endsWith("/accepted")) return data("friends")
+ if (path.endsWith("/pending")) return data("pending")
+ if (path.endsWith("/blocked")) return data("blocked")
+ if (path.endsWith("/profile")) return { id: path.split("/").at(-2), name: "Peer", discriminator: "0001", image: null, avatarVersion: 0, kind: "human", aboutMe: "", bannerColor: null, mutualServers: 0, statusEmoji: null, statusText: null }
throw new Error("Unexpected relationship fixture request: " + path)
}
type Held = { viewer: string; path: string; signal: AbortSignal; resolve: (value: unknown) => void }
@@ -122,7 +124,7 @@ describe("profile message visibility from the existing relationship owner", () =
await act(async () => getCommunityDbRegistry(hook.client)!.collections.friendships.utils.writeUpsert({ id: peer.id, userId: peer.userId, kind: "accepted" }))
hook.open("peer")
expect(hook.current.canMessage).toBe(false)
- await act(async () => { for (const request of held) request.resolve(response(request.path, empty)) })
+ await act(async () => { for (const request of held) request.resolve(response(request.path, empty, request.viewer)) })
await waitFor(() => expect(hook.client.getQueryData(communityKeys.friends())).toBeDefined())
expect(hook.current.canMessage).toBe(false)
hook.view.unmount()
@@ -151,7 +153,7 @@ describe("profile message visibility from the existing relationship owner", () =
await waitFor(() => expect(hook.client.getQueryData(communityKeys.friends())).toBeDefined())
hook.open("peer")
await waitFor(() => expect(hook.current.canMessage).toBe(true))
- mocks.api.mockImplementation((path: string) => !path.includes("/friends/") ? Promise.resolve(response(path)) : mode === "error" ? Promise.reject(new Error("refresh failed")) : Promise.resolve({ ...response(path), stale: true }))
+ mocks.api.mockImplementation((path: string) => !path.includes("/friends/") ? Promise.resolve(response(path)) : mode === "error" ? Promise.reject(new Error("refresh failed")) : Promise.resolve(staleFriendBucketFixture(path.endsWith("/accepted") ? "friends" : path.endsWith("/pending") ? "pending" : "blocked")))
await act(async () => { await hook.client.refetchQueries({ queryKey: communityKeys.friends(), exact: true }) })
expect(hook.client.getQueryState(communityKeys.friends())?.status).toBe("error")
expect(hook.client.getQueryData(communityKeys.friends())).toBeDefined()
@@ -169,7 +171,7 @@ describe("profile message visibility from the existing relationship owner", () =
await waitFor(() => expect(held).toHaveLength(3))
act(() => projectCommunityWsEventToDb(hook.client, { type: "community:friend.block", userId: "peer", blockedByViewer: true }))
await waitFor(() => expect(hook.current.canMessage).toBe(false))
- await act(async () => { for (const request of held) request.resolve(response(request.path)); await refresh })
+ await act(async () => { for (const request of held) request.resolve(response(request.path, undefined, request.viewer)); await refresh })
expect(hook.current.canMessage).toBe(false)
expect(getCommunityDbRegistry(hook.client)!.collections.friendships.get("blocked:peer")?.kind).toBe("blocked")
})
@@ -189,9 +191,9 @@ describe("profile message visibility from the existing relationship owner", () =
expect(hook.current.canMessage).toBe(false)
const fromA = held.filter((request) => request.viewer === "A")
await waitFor(() => expect(fromA.every((request) => request.signal.aborted)).toBe(true))
- await act(async () => { for (const request of fromA) request.resolve(response(request.path)) })
+ await act(async () => { for (const request of fromA) request.resolve(response(request.path, undefined, request.viewer)) })
expect(hook.current.canMessage).toBe(false)
- await act(async () => { for (const request of held.filter((request) => request.viewer === "B")) request.resolve(response(request.path, empty)) })
+ await act(async () => { for (const request of held.filter((request) => request.viewer === "B")) request.resolve(response(request.path, empty, request.viewer)) })
await waitFor(() => expect(hook.client.getQueryData(communityKeys.friends())).toBeDefined())
expect(hook.current.canMessage).toBe(false)
expect([...getCommunityDbRegistry(hook.client)!.collections.friendships.values()]).toHaveLength(0)
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 b68c023ce..aec0a0a42 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
@@ -1,4 +1,6 @@
"use client"
+
+import { CommunityUserSearchReadSchema, type CommunityUserSearchRead } from "@alook/shared"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useCommunityRuntime } from "@/stores/community/runtime"
@@ -17,7 +19,6 @@ import { communityKeys } from "@/lib/query-keys"
import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"
import { apiFetchProfiles } from "@/lib/community/profile-seed"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
-import { avatarInitial } from "@/lib/community/avatar"
import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"
import type {
@@ -128,12 +129,10 @@ export function useShellProfileController({
enabled: !!lookupHandle,
retry: false,
queryFn: async ({ signal, client }) => {
- const data = await apiFetchProfiles<{
- users: Array<{ id: string; name: string; discriminator: string; image: string | null; avatarVersion: number }>
- }>(`/api/community/users/search?q=${encodeURIComponent(lookupHandle)}`, (response) => response.users.map((user) => ({
+ const data = await apiFetchProfiles<CommunityUserSearchRead>(`/api/community/users/search?q=${encodeURIComponent(lookupHandle)}`, (response) => CommunityUserSearchReadSchema.parse(response).users.map((user) => ({
id: user.id,
identityAbout: { name: user.name, discriminator: user.discriminator },
- avatar: { avatar: user.image ?? avatarInitial(user.name), avatarVersion: user.avatarVersion },
+ avatar: { avatar: user.image, avatarVersion: user.avatarVersion },
})), { signal }, getCommunityDbRegistry(client))
return data.users.map((user) => user.id)
},
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 642b90311..d324bc77b 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts
@@ -1,3 +1,8 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { QueryClient } from "@tanstack/react-query"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
+import { communityKeys } from "@/lib/query-keys"
+import { serverResourceFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
import { createElement } from "react"
import { act, render as rtlRender } from "@/test/react-dom-harness"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -17,10 +22,7 @@ const mocks = vi.hoisted(() => ({
toastApiError: vi.fn(),
lastChannel: { current: null as string | null },
lastMeLeaf: { current: null as string | null },
- communityDb: { current: null as null | { collections: {
- servers: { get: (id: string) => { detailComplete?: boolean } | undefined; subscribeChanges: (notify: () => void) => { unsubscribe: () => void } }
- channels: { values: () => IterableIterator<Record<string, unknown>>; subscribeChanges: (notify: () => void) => { unsubscribe: () => void } }
- } } },
+ communityDb: { current: null as CommunityDbRegistry | null },
}))
vi.mock("sonner", () => ({ toast: mocks.toast }))
@@ -269,21 +271,24 @@ describe("useShellRailController", () => {
expect(hook.pushed).toEqual(["/c/channels/s1/cached"])
})
- it("uses canonical channels only when the restored server detail is complete", async () => {
+ it("uses canonical channels only when the restored directory window is complete", async () => {
const servers = new Map([
- ["s1", { id: "s1", detailComplete: true }],
- ["s2", { id: "s2", detailComplete: false }],
+ ["s1", serverResourceFixture({ id: "s1" })],
+ ["s2", serverResourceFixture({ id: "s2" })],
])
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 }],
+ ["pending", { ...channelResourceFixture({ id: "pending", serverId: "s1" }), pending: true }],
+ ["thread", { ...channelResourceFixture({ id: "thread", serverId: "s1", type: "thread", parentChannelId: "canonical", parentMessageId: "opener" }), pending: false }],
+ ["canonical", { ...channelResourceFixture({ id: "canonical", serverId: "s1" }), pending: false }],
+ ["foreign", { ...channelResourceFixture({ id: "foreign", serverId: "s2" }), pending: false }],
])
- mocks.communityDb.current = { collections: {
- servers: { get: (id) => servers.get(id), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
+ const directoryClient = new QueryClient()
+ directoryClient.setQueryData(communityKeys.server("s1"), { schemaVersion: BUSINESS_SCHEMA_VERSION, accountId: "viewer", serverId: "s1", categoryIds: [], channelIds: ["canonical"] })
+ mocks.communityDb.current = { queryClient: directoryClient, scopeId: "viewer", accountId: "viewer", collections: {
+ categories: { values: () => [][Symbol.iterator]() },
+ servers: { get: (id: string) => servers.get(id), values: () => servers.values(), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
channels: { values: () => channels.values(), subscribeChanges: () => ({ unsubscribe: vi.fn() }) },
- } }
+ } } as unknown as CommunityDbRegistry
const hook = await renderController()
await act(async () => hook.current.navigate("s1"))
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
index 138747fc6..b7f1e4b50 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
@@ -1,3 +1,4 @@
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect, useMemo } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -73,7 +74,7 @@ async function mount(sidebar = false, extraServer = false) {
if (options.method === "POST") return held
if (seen.has(path)) return new Promise((_, fail) => options.signal?.addEventListener("abort", () => fail(new DOMException("cancelled", "AbortError")), { once: true }))
seen.add(path)
- return Promise.resolve(path.endsWith("server-folders") ? { folders: [] } : { servers: [{ id: "s1", name: "One", discriminator: "0001", icon: null, ownerId: sidebar ? "other-owner" : "A", role: sidebar ? "member" : "owner" }, ...((sidebar || extraServer) ? [{ id: "s2", name: "Two", discriminator: "0002", icon: null, ownerId: "other-owner", role: "member" }] : []), ...(extraServer ? [{ id: "s3", name: "Three", discriminator: "0003", icon: null, ownerId: "other-owner", role: "member" }] : [])] })
+ return Promise.resolve(path.endsWith("server-folders") ? { folders: [] } : serverRailResponseFixture({ servers: [{ id: "s1", name: "One", discriminator: "0001", icon: null, ownerId: sidebar ? "other-owner" : "A", role: sidebar ? "member" : "owner" }, ...((sidebar || extraServer) ? [{ id: "s2", name: "Two", discriminator: "0002", icon: null, ownerId: "other-owner", role: "member" }] : []), ...(extraServer ? [{ id: "s3", name: "Three", discriminator: "0003", icon: null, ownerId: "other-owner", role: "member" }] : [])] }, "A"))
})
const view = render(<Root sidebar={sidebar} />)
await waitFor(() => expect(controller.railProps.servers).toHaveLength(extraServer ? 3 : sidebar ? 2 : 1))
diff --git a/src/web/src/components/community/social/friends-page.dom.test.tsx b/src/web/src/components/community/social/friends-page.dom.test.tsx
index 709a4f922..24452c46f 100644
--- a/src/web/src/components/community/social/friends-page.dom.test.tsx
+++ b/src/web/src/components/community/social/friends-page.dom.test.tsx
@@ -97,7 +97,7 @@ describe("FriendsPage actionable requests", () => {
const onAccept = vi.fn((_id: string) => new Promise<void>((next) => { resolve = next }))
const onOpenProfile = vi.fn()
const { client, registry } = await createCommunityQueryOwner()
- publishCommunityFriendships(client, pending, { token: captureCommunityLiveSnapshotToken(client), signal: undefined })
+ publishCommunityFriendships(client, pending.map(({ id, userId, kind, needsOwnerApproval }) => ({ id, userId, kind, needsOwnerApproval })), { token: captureCommunityLiveSnapshotToken(client), signal: undefined })
function NativeRequests() {
const rows = useFriendshipRows()
const command = useMutation({ mutationKey: ["community", "friend-request", "accept"], mutationFn: async ({ friendshipId }: { friendshipId: string }) => {
@@ -130,6 +130,26 @@ describe("FriendsPage actionable requests", () => {
})
describe("FriendsPage search owner", () => {
+ it.each(["cold", "warm", "newer"])("keeps a null search avatar canonical with mode=%s", async mode => {
+ const { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } = await import("@alook/shared")
+ const { writeCommunityProfilePatches } = await import("@/lib/community/profile-seed")
+ const { client, registry } = await createCommunityQueryOwner()
+ if (mode !== "cold") writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alice", discriminator: "0042", aboutMe: "Keep complete", bannerColor: "#123456" }, avatar: { avatar: "old-image", avatarVersion: 2 }, status: { statusText: "Keep status", statusEmoji: "🙂" } }], registry)
+ let release!: () => void
+ const pending = new Promise<void>(done => { release = done })
+ const fetch = vi.fn(async () => { await pending; return new Response(JSON.stringify({ users: [{ id: "alice", name: "Alice", discriminator: "0042", image: null, avatarVersion: 2 }] }), { headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_CONTRACT_VERSION) } }) })
+ vi.stubGlobal("fetch", fetch)
+ const view = render(<QueryClientProvider client={client} registry={registry} retainOwner><FriendsPage friends={[]} pending={[]} blocked={[]} activeTab="new" /></QueryClientProvider>)
+ try {
+ fireEvent.change(view.getByPlaceholderText("Search by username"), { target: { value: "alice" } })
+ await waitFor(() => expect(fetch).toHaveBeenCalledOnce())
+ if (mode === "newer") writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Newer Alice" }, avatar: { avatar: "newer-image", avatarVersion: 3 }, status: { statusText: "Newer status" } }], registry, { command: true })
+ await act(async () => release())
+ await waitFor(() => expect(client.getQueryData(["community", "user-search", "alice"])).toEqual(["alice"]))
+ expect(registry.collections.profiles.get("alice")).toMatchObject({ avatar: mode === "newer" ? "newer-image" : null, avatarVersion: mode === "newer" ? 3 : 2, name: mode === "newer" ? "Newer Alice" : "Alice", discriminator: "0042", ...(mode !== "cold" ? { aboutMe: "Keep complete", bannerColor: "#123456", statusText: mode === "newer" ? "Newer status" : "Keep status" } : {}) })
+ } finally { view.unmount(); vi.unstubAllGlobals() }
+ })
+
it.each([false, true])("held search failure after retirement=%s only shows a current error", async (retired) => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })
const registry = createCommunityDbRegistry(queryClient, "viewer")
diff --git a/src/web/src/components/community/social/friends-page.tsx b/src/web/src/components/community/social/friends-page.tsx
index 946bb59a3..27d013e85 100644
--- a/src/web/src/components/community/social/friends-page.tsx
+++ b/src/web/src/components/community/social/friends-page.tsx
@@ -1,4 +1,6 @@
"use client"
+
+import { CommunityUserSearchReadSchema, type CommunityUserSearchRead } from "@alook/shared"
import { useCommunityPreviewProfiles } from "@/stores/community/profile-preview"
import { useObservedRegion } from "@/lib/observability/regions"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
@@ -18,7 +20,6 @@ import { Input } from "@/components/ui/input"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from "@/components/ui/context-menu"
import { Avatar } from "../avatar"
-import { avatarInitial } from "@/lib/community/avatar"
import { EmptyState } from "../empty-state"
import { FriendRowsSkeleton, FriendsPageSkeleton } from "./friends-page-skeleton"
import { hasStatus } from "./status-presets"
@@ -126,14 +127,12 @@ export function FriendsPage({
const token = captureCommunityLiveSnapshotToken(profileQueryClient)
const assertActive = () => assertCommunityLiveSnapshotTokenCurrent(profileQueryClient, token, signal)
try {
- const data = await apiFetchProfiles<{
- users: Array<{ id: string; name: string; image: string | null; avatarVersion: number; discriminator: string }>
- }>(
+ const data = await apiFetchProfiles<CommunityUserSearchRead>(
`/api/community/users/search?q=${encodeURIComponent(searchTerm)}`,
- (response) => response.users.map((user) => ({
+ (response) => CommunityUserSearchReadSchema.parse(response).users.map((user) => ({
id: user.id,
identityAbout: { name: user.name, discriminator: user.discriminator },
- avatar: { avatar: user.image ?? avatarInitial(user.name), avatarVersion: user.avatarVersion },
+ avatar: { avatar: user.image, avatarVersion: user.avatarVersion },
})),
{ signal, assertActive }, getCommunityDbRegistry(profileQueryClient),
)
diff --git a/src/web/src/components/service-worker-registration.dom.test.tsx b/src/web/src/components/service-worker-registration.dom.test.tsx
index f4460f4f4..1c6f3801d 100644
--- a/src/web/src/components/service-worker-registration.dom.test.tsx
+++ b/src/web/src/components/service-worker-registration.dom.test.tsx
@@ -1,6 +1,8 @@
import { act, render, screen } from "@/test/react-dom-harness"
import { afterEach, describe, expect, it, vi } from "vitest"
import { ServiceWorkerRegistration } from "./service-worker-registration"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { businessDocumentVersionBootstrapScript, DOCUMENT_VERSION_PROBE } from "@/lib/service-worker/business-upgrade"
afterEach(() => {
vi.unstubAllEnvs()
@@ -15,10 +17,57 @@ async function mount() {
}
describe("public asset service worker registration", () => {
+ it("answers before React mounts and retains one document responder across component remounts", async () => {
+ vi.stubEnv("NODE_ENV", "production")
+ const reply = vi.fn()
+ const event = () => new MessageEvent("message", { data: { type: DOCUMENT_VERSION_PROBE }, ports: [{ postMessage: reply } as unknown as MessagePort] })
+ const container = Object.assign(new EventTarget(), {
+ register: vi.fn().mockResolvedValue({}),
+ startMessages: vi.fn((): void => { container.dispatchEvent(event()) }),
+ })
+ const addListener = vi.spyOn(container, "addEventListener")
+ vi.stubGlobal("navigator", { serviceWorker: container })
+ new Function("navigator", businessDocumentVersionBootstrapScript)(navigator)
+ expect(reply).toHaveBeenCalledExactlyOnceWith({ schemaVersion: BUSINESS_SCHEMA_VERSION })
+ expect(container.startMessages).toHaveBeenCalledOnce()
+ for (const count of [2, 3]) {
+ const view = render(<ServiceWorkerRegistration />)
+ view.unmount()
+ container.dispatchEvent(event())
+ expect(reply).toHaveBeenCalledTimes(count)
+ expect(reply).toHaveBeenLastCalledWith({ schemaVersion: BUSINESS_SCHEMA_VERSION })
+ }
+ expect(addListener).toHaveBeenCalledOnce()
+ expect(addListener).toHaveBeenCalledWith("message", expect.any(Function))
+ expect(container.register).toHaveBeenCalledTimes(2)
+ })
+
+ it("ignores unrelated messages and safely receives a probe without a response port", () => {
+ const container = Object.assign(new EventTarget(), { startMessages: vi.fn() })
+ vi.stubGlobal("navigator", { serviceWorker: container })
+ new Function("navigator", businessDocumentVersionBootstrapScript)(navigator)
+ const reply = vi.fn()
+ container.dispatchEvent(new MessageEvent("message", { data: { type: "unrelated" }, ports: [{ postMessage: reply } as unknown as MessagePort] }))
+ expect(reply).not.toHaveBeenCalled()
+ expect(() => container.dispatchEvent(new MessageEvent("message", { data: { type: DOCUMENT_VERSION_PROBE } }))).not.toThrow()
+ })
+
+ it.each(["unsupported", "security getter", "start failure"])("keeps the page usable when bootstrap meets %s", async failure => {
+ vi.stubEnv("NODE_ENV", "production")
+ vi.spyOn(console, "warn").mockImplementation(() => {})
+ const value = failure === "unsupported" ? {} : failure === "security getter"
+ ? Object.defineProperty({}, "serviceWorker", { get() { throw new Error("denied") } })
+ : { serviceWorker: Object.assign(new EventTarget(), { startMessages() { throw new Error("unavailable") }, register: vi.fn().mockResolvedValue({}) }) }
+ vi.stubGlobal("navigator", value)
+ expect(() => new Function("navigator", businessDocumentVersionBootstrapScript)(navigator)).not.toThrow()
+ await mount()
+ expect(screen.getByText("Online app content")).toBeVisible()
+ })
+
it("registers the production script with root scope and no HTTP update cache", async () => {
vi.stubEnv("NODE_ENV", "production")
const register = vi.fn().mockResolvedValue({})
- vi.stubGlobal("navigator", { serviceWorker: { register } })
+ vi.stubGlobal("navigator", { serviceWorker: Object.assign(new EventTarget(), { register }) })
await mount()
expect(register).toHaveBeenCalledWith("/sw.js", { scope: "/", updateViaCache: "none" })
})
@@ -26,7 +75,7 @@ describe("public asset service worker registration", () => {
it("does not install a worker in development", async () => {
vi.stubEnv("NODE_ENV", "development")
const register = vi.fn()
- vi.stubGlobal("navigator", { serviceWorker: { register } })
+ vi.stubGlobal("navigator", { serviceWorker: Object.assign(new EventTarget(), { register }) })
await mount()
expect(register).not.toHaveBeenCalled()
})
@@ -42,7 +91,7 @@ describe("public asset service worker registration", () => {
vi.stubEnv("NODE_ENV", "production")
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
const navigator = failure === "rejection"
- ? { serviceWorker: { register: vi.fn().mockRejectedValue(new Error("unavailable")) } }
+ ? { serviceWorker: Object.assign(new EventTarget(), { register: vi.fn().mockRejectedValue(new Error("unavailable")) }) }
: Object.defineProperty({}, "serviceWorker", { get() { throw new Error("denied") } })
vi.stubGlobal("navigator", navigator)
await mount()
diff --git a/src/web/src/components/service-worker-registration.tsx b/src/web/src/components/service-worker-registration.tsx
index a0a19c0e7..9f2aab378 100644
--- a/src/web/src/components/service-worker-registration.tsx
+++ b/src/web/src/components/service-worker-registration.tsx
@@ -1,16 +1,27 @@
"use client"
import { useEffect } from "react"
+import { useSelector } from "@tanstack/react-store"
+import { businessSchemaLifecycle, rememberBusinessUpdateAttempt, retryBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
+import { AnimatedAlookLogo } from "@/components/community/shell/animated-alook-logo"
+import { Button } from "@/components/ui/button"
export function ServiceWorkerRegistration() {
+ const phase = useSelector(businessSchemaLifecycle, state => state.phase)
useEffect(() => {
- if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return
+ rememberBusinessUpdateAttempt()
+ if (!("serviceWorker" in navigator)) return
const register = async () => {
+ if (process.env.NODE_ENV !== "production") return
await navigator.serviceWorker.register("/sw.js", { scope: "/", updateViaCache: "none" })
}
void register().catch(() => {
console.warn("Public asset service worker registration unavailable")
})
}, [])
- return null
+ if (phase === "current") return null
+ return <div className="fixed inset-0 z-100 flex flex-col items-center justify-center gap-4 bg-background p-8 text-foreground" data-testid="business-schema-update" role={phase === "failed" ? "alert" : "status"} aria-busy={phase === "updating"}>
+ <AnimatedAlookLogo className="size-16" />
+ {phase === "failed" && <><p>Couldn&apos;t update this page.</p><Button variant="outline" onClick={retryBusinessSchemaUpdate}>Retry</Button></>}
+ </div>
}
diff --git a/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts b/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
index 8bbf35ab0..1a2b7a695 100644
--- a/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
+++ b/src/web/src/hooks/community/accepted-send-lifecycle.dom.test.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityMessagePostedSchema } from "@alook/shared"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { afterEach, describe, expect, it, vi } from "vitest"
import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -14,7 +16,8 @@ import { materializeMessageStream } from "@/lib/community/message-stream"
function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done }); return { promise, resolve } }
const author = { id: "u_me", name: "Me", avatar: "M" }
-const posted = { message: { id: "confirmed", seq: 12, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T01:00:00Z", embeds: [] } }
+const posted = CommunityMessagePostedSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "scope", deduped: false, profiles: [{ id: "u_me", name: "Me", discriminator: "0042", avatar: null, avatarVersion: 0 }], message: messageResourceFixture({ id: "confirmed", channelId: "scope", seq: 12, content: "hello", authorId: "u_me", authorName: "Me", authorAvatar: null, authorAvatarVersion: 0, clientNonce: "nonce", createdAt: "2026-10-09T01:00:00Z", embeds: [] }) })
+const postedResponse = () => Response.json(posted, { status: 201, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
afterEach(() => vi.unstubAllGlobals())
describe("accepted IO survives real view retirement", () => {
@@ -24,8 +27,9 @@ describe("accepted IO survives real view retirement", () => {
owner.runtime.ws.actions.rememberChannelAccess(kind === "dm" ? null : "server", "scope", kind === "dm" ? null : "parent")
const scope = kind === "dm" ? { kind, id: "scope" } : { kind, id: "scope", serverId: "server" }
const gate = deferred<Response>(), decode = deferred<void>()
- const response = new Response(JSON.stringify(posted), { status: 201 })
- const json = vi.spyOn(response, "json").mockImplementation(async () => { await decode.promise; return posted })
+ const response = postedResponse()
+ const readText = response.text.bind(response)
+ const body = vi.spyOn(response, "text").mockImplementation(async () => { await decode.promise; return readText() })
const fetchMock = vi.fn(async (path: string) => {
if (path.endsWith("/attachments")) return gate.promise
if (phase === "post") return gate.promise
@@ -50,18 +54,18 @@ describe("accepted IO survives real view retirement", () => {
}
if (phase === "preparation") view.unmount()
})
- if (phase === "decode") await waitFor(() => expect(json).toHaveBeenCalledOnce())
+ if (phase === "decode") await waitFor(() => expect(body).toHaveBeenCalledOnce())
else if (phase !== "preparation") await waitFor(() => expect(fetchMock).toHaveBeenCalledOnce())
if (phase !== "preparation") view.unmount()
owner.runtime.ws.actions.beginChannelMembershipChange("other-server", "other-channel")
await act(async () => {
- gate.resolve(phase === "upload" ? new Response(JSON.stringify({ id: "attachment", filename: "x.txt", contentType: "text/plain", size: 1 }), { status: 201 }) : new Response(JSON.stringify(posted), { status: 201 }))
+ gate.resolve(phase === "upload" ? new Response(JSON.stringify({ id: "attachment", filename: "x.txt", contentType: "text/plain", size: 1 }), { status: 201 }) : postedResponse())
decode.resolve()
await committed
})
expect(owner.registry.collections.messages.get("confirmed")).toMatchObject({ channelId: "scope", authorId: "u_me", clientNonce: "nonce" })
for (const [, options] of fetchMock.mock.calls as unknown as [string, RequestInit][]) expect(options.signal?.aborted).toBe(false)
- const base = [{ id: "confirmed", seq: 12, clientNonce: "nonce", authorId: "u_me", type: "chat" as const, content: "hello" }]
+ const base = [posted.message]
owner.runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: base })
const rows = materializeMessageStream(base, getMessageStreamState(owner.client, scope), canonicalMessageReader(owner.client))
expect(rows).toHaveLength(1)
diff --git a/src/web/src/hooks/community/channel-metadata.test.ts b/src/web/src/hooks/community/channel-metadata.test.ts
index f8a542520..3feb48818 100644
--- a/src/web/src/hooks/community/channel-metadata.test.ts
+++ b/src/web/src/hooks/community/channel-metadata.test.ts
@@ -24,7 +24,7 @@ describe("channel resource options use the common entry", () => {
expect(metadata.queryKey).toEqual(conversationEntryOptions(client, { channelId: "c1", serverId }).queryKey)
await client.query({ ...metadata, select: undefined })
expect(load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/c1/messages?entry=1"])
- expect(registry.collections.channels.get("c1")).toMatchObject({ id: "c1", type, serverId, resourceComplete: true })
+ expect(registry.collections.channels.get("c1")).toMatchObject(packet.channel)
})
it("validates scope before exposing identity or body", async () => {
diff --git a/src/web/src/hooks/community/channel-metadata.ts b/src/web/src/hooks/community/channel-metadata.ts
index f48b30669..e3864173c 100644
--- a/src/web/src/hooks/community/channel-metadata.ts
+++ b/src/web/src/hooks/community/channel-metadata.ts
@@ -1,11 +1,9 @@
import type { QueryClient } from "@tanstack/react-query"
import type { ApiRequestOptions } from "@/lib/api/client"
import { conversationEntryOptions } from "@/lib/community/conversation-entry"
-import type { CommunityChannelResource, CommunityAccessDecision } from "@alook/shared"
+export type ChannelMetadata = import("@alook/shared").CommunityChannelResource & { accessDecision?: import("@alook/shared").CommunityAccessDecision }
export { captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/lib/community/conversation-qualification"
-export type ChannelMetadata = CommunityChannelResource & { resourceComplete: true; accessDecision?: CommunityAccessDecision }
-
export function channelMetadataOptions(client: QueryClient, serverId: string | null, channelId: string, observation?: ApiRequestOptions["observation"]) {
return conversationEntryOptions(client, { channelId, serverId }, observation)
}
diff --git a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
index df2d3edb0..0134d58e3 100644
--- a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
@@ -3,8 +3,10 @@ import { act } from "@/test/react-dom-harness"
import { getCapturedRuntime, seedCanonicalStream, canonicalMessage } from "./test-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
+ BUSINESS_SCHEMA_VERSION,
+ computeCommunityDeliveryDigestFromBodies,
COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,
- COMMUNITY_BROWSER_EVENT_BATCH_TYPE,
+ communityBrowserEventBatchType,
deriveCommunityDeliveryOperationId,
encodeCommunityBrowserEventBatch,
encodeCommunityBrowserEventBatchForContract,
@@ -56,10 +58,11 @@ beforeEach(async () => {
afterEach(cleanupCommunityWsHarness)
const message = {
- type: "community:message.create" as const,
+ type: "community:message.create" as const, profiles: [{ id: "author-1", name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 }],
channelId: "ch-1",
serverId: "server-1",
message: {
+ channelId: "ch-1", replyToId: null, clientNonce: null, attachments: [],
id: "message-1",
seq: 1,
authorId: "author-1",
@@ -114,11 +117,27 @@ function attentionReconcileCount(): number {
}
describe("useCommunityWs — operation bundles", () => {
- it("admits a v2 batch only after its exact wire digest verifies", async () => {
+ it.each(["operation-only", "wire-rehashed"] as const)("rejects current %s tampering before operation observation", async mode => {
+ await mountHook()
+ const frame = await batchFor(`digest-${mode}`, [message])
+ const altered = structuredClone(frame)
+ if (mode === "operation-only") altered.operationDigest = "0".repeat(64)
+ else {
+ altered.events[0] = { ...altered.events[0], message: { ...message.message, content: "Changed bytes" } } as typeof altered.events[0]
+ altered.wireDigest = await computeCommunityDeliveryDigestFromBodies(altered.events.map(row => JSON.stringify(row)))
+ }
+ const observation = vi.spyOn(getCapturedRuntime().ws.actions, "observeDeliveryOperation")
+ await act(async () => { await capturedOnMessage!(altered) })
+ expect(observation).not.toHaveBeenCalled()
+ expect(getCapturedRuntime().ws.get().seenDeliveryOperations.size).toBe(0)
+ expect(canonicalMessage(message.message.id)).toBeUndefined()
+ })
+
+ it("admits a current batch only after its exact wire digest verifies", async () => {
await mountHook()
const prepared = await prepareCommunityDeliveryEvents([message])
if (!prepared.ok) throw new Error("Invalid test event")
- const frame = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId("v2-wire"), prepared: prepared.prepared, contract: 2 })
+ const frame = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId("v2-wire"), prepared: prepared.prepared, contract: BUSINESS_SCHEMA_VERSION })
if (!frame.ok) throw new Error("Invalid test batch")
const tampered = JSON.parse(frame.body)
tampered.events[0].message.content = "changed after encoding"
@@ -134,7 +153,7 @@ describe("useCommunityWs — operation bundles", () => {
await mountHook()
const prepared = await prepareCommunityDeliveryEvents([message])
if (!prepared.ok) throw new Error("Invalid test event")
- const frame = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId("v2-retired"), prepared: prepared.prepared, contract: 2 })
+ const frame = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId("v2-retired"), prepared: prepared.prepared, contract: BUSINESS_SCHEMA_VERSION })
if (!frame.ok) throw new Error("Invalid test batch")
let release!: () => void
let retired = false
@@ -160,12 +179,12 @@ describe("useCommunityWs — operation bundles", () => {
const baseKey = communityKeys.forumSidebarThreads("s1")
seedCanonicalForumSidebar("s1", ["post_1", "post_2"])
- capturedOnMessage!(await batchFor("forum-archive", [{
+ await act(async () => { await capturedOnMessage!(await batchFor("forum-archive", [{
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: ["archived"] },
- }]))
+ }])) })
expect(canonicalForumSidebar("s1").threads.map(({ id }) => id)).toEqual(["post_2"])
expect(getCanonicalCommunityChannels(capturedQueryClient)
@@ -174,12 +193,12 @@ describe("useCommunityWs — operation bundles", () => {
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", [{
+ await act(async () => { await capturedOnMessage!(await batchFor("forum-unarchive", [{
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: null },
- }]))
+ }])) })
expect(canonicalForumSidebar("s1").threads.map(({ id }) => id).sort())
.toEqual(["post_1", "post_2"])
@@ -199,17 +218,17 @@ describe("useCommunityWs — operation bundles", () => {
vi.spyOn(capturedQueryClient, "query")
const frame = await batchFor("message-1", mentionEvents)
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
expect(capturedQueryClient.getQueryData<{ servers: Array<{ id: string; mentions: number }> }>(
communityKeys.servers(),
)?.servers[0]?.mentions).toBe(5)
- expect(attentionReconcileCount()).toBe(0)
+ expect(attentionReconcileCount()).toBe(1)
expect(invalidationCount(communityKeys.servers())).toBe(0)
await vi.advanceTimersByTimeAsync(500)
expect(attentionReconcileCount()).toBe(1)
const callsAfterFirst = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
await vi.advanceTimersByTimeAsync(500)
expect(vi.mocked(capturedQueryClient.invalidateQueries)).toHaveBeenCalledTimes(callsAfterFirst)
expect(attentionReconcileCount()).toBe(1)
@@ -228,7 +247,7 @@ describe("useCommunityWs — operation bundles", () => {
{ ...message, message: { ...message.message, id: "ambiguous-2", seq: 2 } },
mentionEvents[1]!,
])
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
})
it("keeps content and refreshes attention regardless of child order", async () => {
@@ -238,7 +257,7 @@ describe("useCommunityWs — operation bundles", () => {
mentionEvents[2]!,
mentionEvents[0]!,
])
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
})
it("does not invent attention from a different mention message id", async () => {
@@ -253,7 +272,7 @@ describe("useCommunityWs — operation bundles", () => {
authorName: "Alice",
},
])
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
})
it("does not cancel or restart an in-flight raw server resource for a projected bump", async () => {
@@ -276,7 +295,7 @@ describe("useCommunityWs — operation bundles", () => {
await vi.waitFor(() => expect(queryCalls).toBe(1))
const cancel = vi.spyOn(capturedQueryClient, "cancelQueries")
- capturedOnMessage!(await batchFor("message-fenced-mention", mentionEvents))
+ await act(async () => { await capturedOnMessage!(await batchFor("message-fenced-mention", mentionEvents)) })
expect(queryCalls).toBe(1)
expect(cancel.mock.calls.filter(([filters]) => JSON.stringify(filters.queryKey) === JSON.stringify(key))).toEqual([])
@@ -296,11 +315,11 @@ describe("useCommunityWs — operation bundles", () => {
vi.spyOn(capturedQueryClient, "invalidateQueries")
vi.spyOn(capturedQueryClient, "query")
- capturedOnMessage!(await batchFor("message-late", mentionEvents))
+ await act(async () => { await capturedOnMessage!(await batchFor("message-late", mentionEvents)) })
expect(capturedQueryClient.getQueryData<{ servers: Array<{ mentions: number }> }>(
communityKeys.servers(),
)?.servers[0]?.mentions).toBe(9)
- expect(attentionReconcileCount()).toBe(0)
+ expect(attentionReconcileCount()).toBe(1)
expect(invalidationCount(communityKeys.servers())).toBe(0)
await vi.advanceTimersByTimeAsync(500)
expect(attentionReconcileCount()).toBe(1)
@@ -312,10 +331,10 @@ describe("useCommunityWs — operation bundles", () => {
it("rejects malformed children without poisoning the operation map", async () => {
await mountHook({ viewerUserId: "viewer-1" })
const frame = await batchFor("message-malformed", mentionEvents)
- capturedOnMessage!({
+ await act(async () => { await capturedOnMessage!({
...frame,
events: [{ ...frame.events[0], contractVersion: 1 }, ...frame.events.slice(1)],
- })
+ }) })
const { useCommunityWsStore } = await import("@/stores/community/ws")
expect(getCapturedRuntime().ws.get().seenDeliveryOperations.size).toBe(0)
@@ -326,15 +345,15 @@ describe("useCommunityWs — operation bundles", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
await mountHook({ viewerUserId: "viewer-1" })
- capturedOnMessage!({
- type: COMMUNITY_BROWSER_EVENT_BATCH_TYPE,
+ await act(async () => { await capturedOnMessage!({
+ type: communityBrowserEventBatchType(),
padding: "x".repeat(COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES),
- })
- capturedOnMessage!({
- type: COMMUNITY_BROWSER_EVENT_BATCH_TYPE,
+ }) })
+ await act(async () => { await capturedOnMessage!({
+ type: communityBrowserEventBatchType(),
extra: true,
- })
- capturedOnMessage!({ ...message, contractVersion: 1 })
+ }) })
+ await act(async () => { await capturedOnMessage!({ ...message, contractVersion: 1 }) })
expect(warn).toHaveBeenCalledWith(
"[ws] frame dropped",
@@ -342,7 +361,7 @@ describe("useCommunityWs — operation bundles", () => {
)
expect(warn).toHaveBeenCalledWith(
"[ws] frame dropped",
- expect.objectContaining({ reason: "invalid-payload", type: COMMUNITY_BROWSER_EVENT_BATCH_TYPE }),
+ expect.objectContaining({ reason: "invalid-payload", type: communityBrowserEventBatchType() }),
)
expect(warn).toHaveBeenCalledWith(
"[ws] frame dropped",
@@ -358,7 +377,7 @@ describe("useCommunityWs — operation bundles", () => {
const conflicting = await batchFor("message-conflict", [
{ ...message, message: { ...message.message, content: "different" } },
])
- capturedOnMessage!(first)
+ await act(async () => { await capturedOnMessage!(first) })
const { useCommunityWsStore } = await import("@/stores/community/ws")
const seenMessages = getCapturedRuntime().ws.get().seenMessageIds.size
const overlayBeforeConflict = getMessageStreamState(capturedQueryClient, {
@@ -368,7 +387,7 @@ describe("useCommunityWs — operation bundles", () => {
})
const invalidationsBeforeConflict = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
- capturedOnMessage!(conflicting)
+ await act(async () => { await capturedOnMessage!(conflicting) })
expect(getCapturedRuntime().ws.get().seenMessageIds.size).toBe(seenMessages)
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" }))
.toStrictEqual(overlayBeforeConflict)
@@ -421,7 +440,7 @@ describe("useCommunityWs — operation bundles", () => {
events[1]!,
])
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
const { useCommunityWsStore } = await import("@/stores/community/ws")
expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(1)
expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId))
@@ -430,7 +449,7 @@ describe("useCommunityWs — operation bundles", () => {
recordArrival.mockRestore()
const invalidationsAfterFailure = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
- capturedOnMessage!(conflicting)
+ await act(async () => { await capturedOnMessage!(conflicting) })
expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(2)
expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId))
.toEqual({ digest: frame.operationDigest, completed: false })
@@ -439,7 +458,7 @@ describe("useCommunityWs — operation bundles", () => {
expect(vi.mocked(capturedQueryClient.invalidateQueries))
.toHaveBeenCalledTimes(invalidationsAfterFailure)
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(2)
expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId))
.toEqual({ digest: frame.operationDigest, completed: true })
@@ -448,7 +467,7 @@ describe("useCommunityWs — operation bundles", () => {
.toBe(1)
const invalidationsAfterCompletion = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
expect(vi.mocked(capturedQueryClient.invalidateQueries))
.toHaveBeenCalledTimes(invalidationsAfterCompletion)
})
@@ -531,7 +550,7 @@ describe("useCommunityWs — operation bundles", () => {
authorName: "Alice",
},
{
- type: "community:channel.member_add",
+ type: "community:channel.membership.change", relation: "notify", present: true,
userId: "viewer-1",
serverId: "s1",
channelId: "ch-1",
@@ -545,7 +564,7 @@ describe("useCommunityWs — operation bundles", () => {
])
try {
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(1)
expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId))
.toEqual({ digest: frame.operationDigest, completed: false })
@@ -565,7 +584,7 @@ describe("useCommunityWs — operation bundles", () => {
publish.mockRestore()
}
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
expect(reconcileCommunityWsReconnect).toHaveBeenCalledTimes(1)
expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId))
.toEqual({ digest: frame.operationDigest, completed: true })
@@ -581,7 +600,7 @@ describe("useCommunityWs — operation bundles", () => {
.toBe(2)
const invalidationsAfterSuccess = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
- capturedOnMessage!(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
expect(vi.mocked(capturedQueryClient.invalidateQueries))
.toHaveBeenCalledTimes(invalidationsAfterSuccess)
})
@@ -595,8 +614,8 @@ describe("useCommunityWs — operation bundles", () => {
{ ...message, message: { ...message.message, content: "different" } },
])
- capturedOnMessage!(first)
- capturedOnMessage!(conflicting)
+ await act(async () => { await capturedOnMessage!(first) })
+ await act(async () => { await capturedOnMessage!(conflicting) })
await vi.waitFor(() => {
expect(warn).toHaveBeenCalledWith(
diff --git a/src/web/src/hooks/community/community-ws/cache.test.ts b/src/web/src/hooks/community/community-ws/cache.test.ts
index 2b2388bad..e54d1f0c7 100644
--- a/src/web/src/hooks/community/community-ws/cache.test.ts
+++ b/src/web/src/hooks/community/community-ws/cache.test.ts
@@ -1,8 +1,10 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { describe, expect, it } from "vitest"
import type { CommunityReactionAdd, CommunityReactionRemove } from "@alook/shared"
import { applyMessageReaction, type Msg } from "@/lib/community/models/message"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { ingestMessages, projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishCommunityMessages, ingestMessages, projectCommunityWsEventToDb } from "@/lib/community-db/sync"
import { findCachedMessage } from "../use-message"
import { removeThreadFromCache, type PageCache } from "./cache"
@@ -15,7 +17,7 @@ const remove: CommunityReactionRemove = { ...add, type: "community:reaction.remo
describe("community WS canonical publication and ID windows", () => {
it("preserves undefined windows and missing canonical entities", async () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
- ingestMessages(registry, "ch_1", [{ id: "m_1", content: "one" }])
+ ingestMessages(registry, "ch_1", [messageResourceFixture({ id: "m_1", channelId: "ch_1", content: "one" })])
const row = registry.collections.messages.get("m_1"), cache = pageCache([{ id: "m_1" }])
projectCommunityWsEventToDb(client, { type: "community:reaction.add", channelId: "ch_1", messageId: "missing", emoji: "👍", userId: "peer" })
expect(registry.collections.messages.get("m_1")).toBe(row)
@@ -25,7 +27,7 @@ describe("community WS canonical publication and ID windows", () => {
})
it("patches canonical approval while preserving non-target rows", async () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
- ingestMessages(registry, "ch_1", [{ id: "m_1", content: "one" }, { id: "m_2", content: "two" }])
+ ingestMessages(registry, "ch_1", [messageResourceFixture({ id: "m_1", channelId: "ch_1", content: "one" }), messageResourceFixture({ id: "m_2", channelId: "ch_1", content: "two", seq: 2 })])
const other = registry.collections.messages.get("m_2")
const profile = { id: "u_1", name: "User", discriminator: "0001", image: null, avatarVersion: 0 }
const approval = { friendshipId: "friendship_1", status: "approved" as const, waitingOn: null, otherProfile: profile, botProfile: { ...profile, id: "bot_1" } }
@@ -53,7 +55,7 @@ describe("community WS canonical publication and ID windows", () => {
})
it("patches canonical reactions and removes the last membership", async () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
- ingestMessages(registry, "ch_1", [{ id: "m_1", reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] }] }])
+ ingestMessages(registry, "ch_1", [messageResourceFixture({ id: "m_1", channelId: "ch_1", reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] }] })])
projectCommunityWsEventToDb(client, remove)
expect(registry.collections.messages.get("m_1")?.reactions).toEqual([])
projectCommunityWsEventToDb(client, add)
@@ -62,7 +64,9 @@ describe("community WS canonical publication and ID windows", () => {
})
it("reads the same canonical entity for every ID window and returns undefined for misses", async () => {
const { client, registry } = await createCommunityQueryOwner("u_me")
- ingestMessages(registry, "ch_1", [{ id: "m_1" }, { id: "m_2", content: "target", authorId: "author", createdAt: "2026-08-15T00:00:02.000Z" }])
+ ingestMessages(registry, "ch_1", [messageResourceFixture({ id: "m_1", channelId: "ch_1" }), messageResourceFixture({ id: "m_2", channelId: "ch_1", seq: 2, content: "target", authorId: "author", createdAt: "2026-08-15T00:00:02.000Z" })])
+ const messages = [...registry.collections.messages.values()].map(row => messageResourceFixture(Object.fromEntries(Object.entries(row).filter(([key]) => !key.startsWith("$")))))
+ publishCommunityMessages(client, { channelId: "ch_1", messages, profiles: messageProfilesFixture(messages), proof: { token: captureCommunityLiveSnapshotToken(client) } })
expect(findCachedMessage(client, "m_2")).toMatchObject({ id: "m_2", content: "target" })
expect(findCachedMessage(client, "missing")).toBeUndefined()
})
diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts
index 303ad2f65..9fc272260 100644
--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.dom.test.ts
@@ -1,3 +1,4 @@
+import { serverDirectoryFixture, channelResourceFixture, currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { getCapturedRuntime } from "./test-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClient } from "@tanstack/react-query"
@@ -33,7 +34,7 @@ it("purges canonical rows for authoritative channel and forum-post eviction", as
const registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestServerDetail(registry, {
+ ingestServerDetail(registry, serverDirectoryFixture({
id: "server", name: "Server", discriminator: "0001", description: "",
icon: null, ownerId: "viewer",
categories: [{
@@ -43,10 +44,10 @@ it("purges canonical rows for authoritative channel and forum-post eviction", as
{ 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" },
+ channel: channelResourceFixture({ id: "thread", serverId: "server", parentChannelId: "forum", parentMessageId: "opener", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" }),
} as CommunityWsEvent)
retireCommunityChannelReading(registry, "channel", { reason: "read-denied", serverId: "server" })
expect(registry.collections.channels.get("channel")).toBeUndefined()
@@ -75,17 +76,8 @@ function seedThreads(serverId: string, parentId: string, children: string[], sha
}
capturedQueryClient.setQueryData(communityKeys.threads(parentId), data)
} else {
- const pages: ForumFeedPage[] = children.map((id) => ({
- serverId,
- parentType: "forum",
- threads: [{
- id, name: id, creatorId: "author", messageCount: 1,
- parentMessageId: `opener_${id}`, lastMessageAt: "2026-09-06T00:00:00Z",
- createdAt: "2026-09-06T00:00:00Z", activityAt: "2026-09-06T00:00:00Z",
- }],
- included: { parentMessages: [], firstMessages: [], tags: [], participants: [] },
- hasMore: true,
- nextCursor: id,
+ const pages: ForumFeedPage[] = children.map(id => ({ serverId, parentType: "forum",
+ threads: [{ id, openerMessageId: `opener_${id}`, participantIds: [] }], hasMore: true, nextCursor: id,
}))
capturedQueryClient.setQueryData(communityKeys.forumFeed(parentId, null), {
pages, pageParams: children.map((_, index) => index === 0 ? null : children[index - 1]),
@@ -100,7 +92,7 @@ const preview = {
}
const controls: CommunityWsEvent[] = [
- { type: "community:channel.member_remove", serverId: "server", channelId: "parent", userId: "u_me" },
+ { type: "community:channel.membership.change", serverId: "server", channelId: "parent", userId: "u_me", relation: "access", present: false },
{ type: "community:channel.delete", serverId: "server", channelId: "parent" },
{ type: "community:member.leave", serverId: "server", userId: "u_me" },
{ type: "community:server.delete", serverId: "server" },
@@ -141,7 +133,7 @@ describe.each(["text", "forum"] as const)("%s canonical thread scope eviction",
const apiCalls = getCommunityApiFetchMock().mock.calls.length
const retireDisk = vi.spyOn(getCommunityDbRegistry(capturedQueryClient)!, "retireReadingDisk")
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(capturedQueryClient.getQueryState(contextKey)).toBeUndefined()
expect(capturedQueryClient.getQueryState(pendingKey)).toBeUndefined()
@@ -179,7 +171,7 @@ it("cancels an unresolved parent thread list before its child rows can arrive",
},
}).catch(() => undefined)
- capturedOnMessage!({ type: "community:channel.delete", serverId: "server", channelId: "parent" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.delete", serverId: "server", channelId: "parent" }))
expect(requestSignal.aborted).toBe(true)
expect(capturedQueryClient.getQueryState(key)).toBeUndefined()
@@ -198,9 +190,9 @@ it("preserves readable previews when leaving only a thread's notify membership",
const key = communityKeys.messageContext("channel", "preview_child", 1)
capturedQueryClient.setQueryData(key, preview)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.membership.change", serverId: "server", channelId: "preview_child", userId: "u_me", relation: "notify", present: false,
- })
+ }))
expect(capturedQueryClient.getQueryData(key)).toEqual(preview)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("preview_child", "server")).toBe(false)
diff --git a/src/web/src/hooks/community/community-ws/current-membership-transport.dom.test.ts b/src/web/src/hooks/community/community-ws/current-membership-transport.dom.test.ts
new file mode 100644
index 000000000..eea91bc71
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/current-membership-transport.dom.test.ts
@@ -0,0 +1,87 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+/// <reference types="../../../../../ws-do/src/env" />
+import { resetCommunityWsHarness, cleanupCommunityWsHarness, mountHook, seedCanonicalThread, capturedOnMessage,
+ canonicalRegistry, canonicalMessage, hasCanonicalChannelNotify } from "./test-harness"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_DELIVERY_OPERATION_ID_HEADER, createLogger, decodeCommunityBrowserEvent, encodeCommunityBrowserEvent,
+ deriveCommunityDeliveryOperationId, encodePreparedCommunityBrowserEventBatch, serializeMessageDeliveryBatch, type MessageDeliveryBatch } from "@alook/shared"
+import { handleMessageDelivery } from "../../../../../ws-do/src/routes/message-delivery"
+import { readCommunityBrowserEventBundleRequest } from "../../../../../ws-do/src/community-browser-event-ingress"
+import { createCommunityDeliveryReceipt } from "../../../../../ws-do/src/community-delivery-receipt"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
+import { act } from "@/test/react-dom-harness"
+import * as registry from "./registry"
+
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+const batch = (): MessageDeliveryBatch => ({ communityContract: BUSINESS_SCHEMA_VERSION, messageId: "message-current-join",
+ messageEvent: { profiles: messageProfilesFixture([{ ...messageResourceFixture({ id: "message-current-join", channelId: "thread-current", authorId: "author-current" }), authorName: "Author", authorAvatarVersion: 1 }]), type: "community:message.create", channelId: "thread-current", serverId: "server-current", parentChannelId: "parent-current",
+ message: { ...messageResourceFixture({ id: "message-current-join", channelId: "thread-current", authorId: "author-current" }), authorName: "Author", authorAvatarVersion: 1 } },
+ contentUserIds: ["u_me"], unreadPlainUserIds: [], unreadMentionUserIds: [], mentionUserIds: [],
+ joinedParticipantUserIds: ["u_me"], rosterRefreshUserId: "u_me",
+})
+
+async function deliver(value: unknown, apply = true) {
+ const calls: unknown[] = []
+ const fetch = vi.fn(async (request: Request) => {
+ const ingress = await readCommunityBrowserEventBundleRequest(request)
+ if (!ingress.ok) throw new Error("Current target ingress rejected")
+ calls.push(...ingress.prepared.events)
+ const encoded = encodePreparedCommunityBrowserEventBatch({ operationId: ingress.operationId, operationDigest: ingress.operationDigest, prepared: ingress.prepared })
+ if (!encoded.ok) throw new Error("Current browser batch rejected")
+ if (apply) await capturedOnMessage!(encoded.batch)
+ return Response.json(createCommunityDeliveryReceipt({ status: "complete", operationId: ingress.operationId,
+ operationDigest: ingress.operationDigest, eventCount: ingress.eventCount,
+ results: [{ socketIndex: 0, outcome: "enqueued", frameCount: 1, persistedNextFrameIndex: 1, ambiguousClosed: false }] }))
+ })
+ const request = new Request("https://ws.test/broadcast/community/message-delivery", { method: "POST",
+ headers: { "content-type": "application/json", [COMMUNITY_DELIVERY_OPERATION_ID_HEADER]: await deriveCommunityDeliveryOperationId(batch().messageId) },
+ body: JSON.stringify(value) })
+ const context = { request, url: new URL(request.url), traceId: undefined, log: createLogger({ service: "current-membership-test" }),
+ env: { WS_DO: { idFromName: (name: string) => name, get: () => ({ fetch }) } } } as unknown as Parameters<typeof handleMessageDelivery>[0]
+ const response = await handleMessageDelivery(context)
+ return { response, calls, fetch }
+}
+
+describe("current membership producer to consumer", () => {
+ it("delivers committed participant notify membership through actual route, ingress and hook", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ seedCanonicalThread("server-current", "parent-current", "text", "thread-current")
+ const value = JSON.parse(serializeMessageDeliveryBatch(batch()))
+ const result = await act(() => deliver(value))
+ expect(result.response?.status).toBe(200)
+ expect(result.calls).toContainEqual({ type: "community:channel.membership.change", channelId: "thread-current", serverId: "server-current", userId: "u_me", relation: "notify", present: true })
+ expect(hasCanonicalChannelNotify("thread-current", "u_me")).toBe(true)
+ expect(canonicalMessage(batch().messageId)?.content).toBe("Body")
+ })
+
+ it("calibrates the actual singular dispatch on a normal current single relationship frame", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ seedCanonicalThread("server-current", "parent-current", "text", "thread-current")
+ const encoded = encodeCommunityBrowserEvent({ type: "community:channel.membership.change", serverId: "server-current", channelId: "thread-current", userId: "u_me", relation: "notify", present: true })
+ if (!encoded.ok) throw new Error("Current relationship fixture rejected")
+ const dispatch = vi.spyOn(registry, "dispatchCommunityWsEvent")
+ await act(async () => { await capturedOnMessage!(encoded.envelope) })
+ expect(dispatch).toHaveBeenCalledTimes(1)
+ expect(hasCanonicalChannelNotify("thread-current", "u_me")).toBe(true)
+ })
+
+ it.each(["community:channel.member_add", "community:channel.member_remove"])("rejects obsolete %s even inside the current wire version before dispatch", async type => {
+ await mountHook({ viewerUserId: "u_me" })
+ const frame = { type, schemaVersion: BUSINESS_SCHEMA_VERSION, channelId: "thread-current", serverId: "server-current", userId: "peer" }
+ const dispatch = vi.spyOn(registry, "dispatchCommunityWsEvent")
+ const counts = () => [canonicalRegistry!.collections.channels.size, canonicalRegistry!.collections.channelMemberships.size, canonicalRegistry!.collections.messages.size]
+ const before = counts()
+ const decoded = decodeCommunityBrowserEvent(frame)
+ await act(async () => { await capturedOnMessage!(frame) })
+ expect({ admitted: decoded.ok, dispatched: dispatch.mock.calls.length }).toEqual({ admitted: false, dispatched: 0 })
+ expect(counts()).toEqual(before)
+ })
+
+ it("rejects obsolete memberAdded before any target delivery", async () => {
+ const result = await deliver({ ...batch(), memberAdded: { userId: "u_me", channelId: "thread-current", serverId: "server-current" } }, false)
+ expect(result.response?.status).toBe(400)
+ expect(result.fetch).not.toHaveBeenCalled()
+ })
+})
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 44c0fb359..890d0840c 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
@@ -14,6 +14,8 @@ async function harness() {
const registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
registerCommunityDbRegistry(registry)
+ registry.collections.profiles.utils.writeUpsert({ id: "u1", name: "User", discriminator: "0001", avatar: "/avatar?v=1", avatarVersion: 1 })
+ registry.collections.profiles.utils.writeUpsert({ id: "bot-1", name: "Before", discriminator: "0002", avatar: null, avatarVersion: 0 })
return { queryClient }
}
@@ -98,4 +100,10 @@ describe("profile identity events", () => {
ownerUserId: "owner-1",
})
})
+ it("does not invent a full profile from an avatar-only event for an unknown user", async () => {
+ const { queryClient } = await harness()
+ projectCommunityWsEventToDb(queryClient, { type: "community:identity.update", userId: "unknown", avatar: null, avatarVersion: 4 })
+ expect(profile(queryClient, "unknown")).toBeUndefined()
+ })
+
})
diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
index 3005cf488..2a910f512 100644
--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts
+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
@@ -43,19 +43,6 @@ export function invalidateChannelMembers(
})
}
-export function invalidateChannelRoster(
- projection: CommunityWsProjectionTransaction,
- channelId: string,
-) {
- invalidateChannelMembers(projection, channelId)
- projection.invalidate("channel-addable-members", {
- queryKey: communityKeys.channelAddableMembers(channelId),
- })
- projection.invalidate("thread-participants", {
- queryKey: communityKeys.threadParticipants(channelId),
- })
-}
-
export function invalidateThreads(
projection: CommunityWsProjectionTransaction,
channelId: string,
diff --git a/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts b/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts
index a5a0bf450..5c8baa1d8 100644
--- a/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/live-forum-window.dom.test.ts
@@ -1,8 +1,9 @@
+import { forumSidebarEnvelopeFixture, channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { canonicalRegistry, capturedOnMessage, capturedQueryClient, cleanupCommunityWsHarness, getCommunityApiFetchMock, hasCanonicalChannelNotify,
mountCanonicalHook, mountHook, resetCommunityWsHarness, seedCanonicalForumSidebar } from "./test-harness"
import { act } from "@/test/react-dom-harness"
import { afterEach, beforeEach, describe, expect, it } from "vitest"
-import { deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatchForContract, prepareCommunityDeliveryEvents, type CommunityWsEvent } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, communityBrowserEventBatchType, deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatchForContract, prepareCommunityDeliveryEvents, type CommunityWsEvent } from "@alook/shared"
import { captureCommunityLiveSnapshotToken, getCanonicalCommunityChannels, getCanonicalCommunityMessages, publishCommunityChannelMetadata } from "@/lib/community-db/sync"
import { useForumSidebarThreads, type SidebarThreadEnvelope } from "../use-forum-sidebar-threads"
import { communityKeys } from "@/lib/query-keys"
@@ -11,19 +12,15 @@ beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
const serverId = "live-server"
function envelope(ids: string[]): SidebarThreadEnvelope {
- const now = new Date().toISOString()
- return { serverNow: now, channels: ids.map(id => ({ id, name: id, serverId, type: "thread", creatorId: "u_me", archived: false,
- parentChannelId: "forum_1", parentMessageId: `opener-${id}`, lastMessageAt: now, activityAt: now,
- expiresAt: new Date(Date.parse(now) + 72 * 60 * 60 * 1000).toISOString(), unread: false })),
- included: { parentMessages: ids.map(id => ({ id: `opener-${id}`, channelId: "forum_1", type: "chat", content: `Title ${id}`, seq: 1 })) } }
+ return forumSidebarEnvelopeFixture(serverId, ids, "u_me")
}
async function frame(events: CommunityWsEvent[], id: string) {
const prepared = await prepareCommunityDeliveryEvents(events)
if (!prepared.ok) throw new Error("invalid live window fixture")
- const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId(id), prepared: prepared.prepared, contract: 2 })
+ const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId(id), prepared: prepared.prepared, contract: BUSINESS_SCHEMA_VERSION })
if (!encoded.ok) throw new Error("invalid live window wire")
- expect(encoded.batch.type).toBe("community:events.batch.v2")
+ expect(encoded.batch.type).toBe(communityBrowserEventBatchType())
return encoded.batch
}
@@ -50,16 +47,16 @@ describe("live forum window participation convergence", () => {
const sidebar = await mountCanonicalHook(() => useForumSidebarThreads(serverId, null))
await expect.poll(() => sidebar.result.current.error?.message ?? sidebar.result.current.sidebar.status).toBe("ready")
expect(reads).toBe(1)
- act(() => { publishCommunityChannelMetadata(capturedQueryClient, { metadata: {
+ act(() => { publishCommunityChannelMetadata(capturedQueryClient, { metadata: channelResourceFixture({
id: "post_live", serverId, name: "New live post", type: "thread", parentChannelId: "forum_1", parentMessageId: "opener-post_live",
creatorId: "u_me", archived: false, lastMessageAt: new Date().toISOString(),
- }, proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined } }) })
+ }), proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined } }) })
expect(hasCanonicalChannelNotify("post_live", "u_me")).toBe(false)
const now = new Date().toISOString()
- const message: CommunityWsEvent = { type: "community:message.create", serverId, channelId: "post_live", parentChannelId: "forum_1",
- message: { id: "live-reply", type: "chat", authorId: "u_me", authorName: "Me", authorAvatarVersion: 0, content: "First reply", seq: 1, createdAt: now } }
+ const message: CommunityWsEvent = { profiles: [{ id: "u_me", name: "Me", discriminator: "0042", avatar: null, avatarVersion: 0 }], type: "community:message.create", serverId, channelId: "post_live", parentChannelId: "forum_1",
+ message: messageResourceFixture({ id: "live-reply", channelId: "post_live", type: "chat", authorId: "u_me", authorName: "Me", authorAvatarVersion: 0, content: "First reply", seq: 1, createdAt: now }) }
const create: CommunityWsEvent = { type: "community:channel.child_create", parentChannelId: "forum_1", parentMessageId: "opener-post_live",
- channel: { id: "post_live", name: "New live post", type: "thread", creatorId: "u_me", createdAt: now } }
+ channel: channelResourceFixture({ id: "post_live", serverId, parentChannelId: "forum_1", parentMessageId: "opener-post_live", name: "New live post", type: "thread", creatorId: "u_me", createdAt: now }) }
const activity: CommunityWsEvent = { type: "community:channel.child_update", parentChannelId: "forum_1", channelId: "post_live", changes: { lastMessageAt: now, messageCount: 1 } }
const membership: CommunityWsEvent = { type: "community:channel.membership.change", relation: "notify", present: true,
serverId, channelId: "post_live", userId: "u_me" }
diff --git a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
index 06e44ccd5..aaf86cf9e 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
@@ -1,3 +1,6 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { channelResourceFixture, messageResourceFixture, currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { conversationEntryFixture, conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
@@ -80,11 +83,11 @@ describe("useCommunityWs — member events", () => {
} },
)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.leave",
serverId: "srv_1",
userId: "u_me",
- } satisfies CommunityMemberLeave)
+ } satisfies CommunityMemberLeave))
expect(getCapturedRuntime().ui.get()).toMatchObject({
currentServerId: null,
@@ -106,11 +109,11 @@ describe("useCommunityWs — member events", () => {
}).catch(() => undefined)
expect(capturedQueryClient.getQueryState(key)).toBeDefined()
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.leave",
serverId: "srv_1",
userId: "u_me",
- } satisfies CommunityMemberLeave)
+ } satisfies CommunityMemberLeave))
expect(capturedQueryClient.getQueryState(key)).toBeUndefined()
})
@@ -129,11 +132,11 @@ describe("useCommunityWs — member events", () => {
scope: { kind: "server", serverId: "srv_2", channelId: "channel_2" },
actors: [],
})
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.leave",
serverId: "srv_1",
userId: "u_other",
- } satisfies CommunityMemberLeave)
+ } satisfies CommunityMemberLeave))
expect(capturedQueryClient.getQueryState(matching)?.isInvalidated).toBe(true)
expect(capturedQueryClient.getQueryState(other)?.isInvalidated).toBe(false)
})
@@ -149,11 +152,11 @@ describe("useCommunityWs — member events", () => {
const unsubscribe = observer.subscribe(() => undefined)
expect(queryFn).toHaveBeenCalledOnce()
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.leave",
serverId: "srv_1",
userId: "u_other",
- } satisfies CommunityMemberLeave)
+ } satisfies CommunityMemberLeave))
await vi.waitFor(() => expect(queryFn).toHaveBeenCalledTimes(2))
expect(capturedQueryClient.getQueryState(key)?.data).toBeUndefined()
@@ -170,7 +173,7 @@ describe("useCommunityWs — member events", () => {
const event: CommunityMemberJoin = {
type: "community:member.join",
serverId: "srv_1",
- member: {
+ member: { avatar: null,
id: "mem_1",
userId: "u_1",
name: "n",
@@ -180,7 +183,7 @@ describe("useCommunityWs — member events", () => {
joinedAt: "2026-07-03T00:00:00.000Z",
},
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const cache = capturedQueryClient.getQueryData<{
pages: { members: { userId: string }[]; total: number }[]
}>(communityKeys.members("srv_1"))
@@ -219,10 +222,10 @@ describe("useCommunityWs — member events", () => {
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
online = ["u_online"]
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.join",
serverId: "srv_1",
- member: {
+ member: { avatar: null,
id: "mem_online",
userId: "u_online",
name: "Online member",
@@ -231,7 +234,7 @@ describe("useCommunityWs — member events", () => {
role: "member",
joinedAt: "2026-08-17T00:00:00.000Z",
},
- } satisfies CommunityMemberJoin)
+ } satisfies CommunityMemberJoin))
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: affectedKey,
@@ -247,10 +250,10 @@ describe("useCommunityWs — member events", () => {
})
})
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.join",
serverId: "srv_1",
- member: {
+ member: { avatar: null,
id: "mem_offline",
userId: "u_offline",
name: "Offline member",
@@ -259,7 +262,7 @@ describe("useCommunityWs — member events", () => {
role: "member",
joinedAt: "2026-08-17T00:01:00.000Z",
},
- } satisfies CommunityMemberJoin)
+ } satisfies CommunityMemberJoin))
await vi.waitFor(() => {
expect(affectedQuery).toHaveBeenCalledTimes(3)
@@ -279,7 +282,7 @@ describe("useCommunityWs — member events", () => {
const event = {
type: "community:member.join",
serverId: "srv_new",
- member: {
+ member: { avatar: null,
id: "mem_me",
userId: "u_me",
name: "Me",
@@ -290,24 +293,24 @@ describe("useCommunityWs — member events", () => {
},
} satisfies CommunityMemberJoin
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.servers(), exact: true })
expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.server("srv_new"), exact: true })
spy.mockClear()
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
...event,
- member: { ...event.member, id: "mem_peer", userId: "u_peer" },
- })
+ member: { avatar: null, ...event.member, id: "mem_peer", userId: "u_peer" },
+ }))
expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.servers(), exact: true })
})
it("forwards WS membership changes onto the server-scoped search overlay bus", async () => {
await mountHook()
const server = (id: string) => {
- capturedOnMessage!({ type: "community:member.join", serverId: id, member: { id: `${id}-gone`, userId: "u_gone", name: "Gone", discriminator: "0001", avatarVersion: 0, role: "member", joinedAt: "2026-07-03T00:00:00.000Z" } })
- capturedOnMessage!({ type: "community:member.join", serverId: id, member: { id: `${id}-remaining`, userId: "u_remaining", name: "Remaining", discriminator: "0002", avatarVersion: 0, role: "member", joinedAt: "2026-07-03T00:00:00.000Z" } })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:member.join", serverId: id, member: { avatar: null, id: `${id}-gone`, userId: "u_gone", name: "Gone", discriminator: "0001", avatarVersion: 0, role: "member", joinedAt: "2026-07-03T00:00:00.000Z" } }))
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:member.join", serverId: id, member: { avatar: null, id: `${id}-remaining`, userId: "u_remaining", name: "Remaining", discriminator: "0002", avatarVersion: 0, role: "member", joinedAt: "2026-07-03T00:00:00.000Z" } }))
const key = [...communityKeys.members(id), "search", "g"]
capturedQueryClient.setQueryData(key, { pages: [{ members: [{ id: `${id}-gone`, userId: "u_gone" }, { id: `${id}-remaining`, userId: "u_remaining" }], hasMore: false, limit: 50 }], pageParams: [null] })
return key
@@ -315,17 +318,17 @@ describe("useCommunityWs — member events", () => {
const current = server("srv_1"), other = server("srv_2")
const otherBefore = capturedQueryClient.getQueryData(other)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.leave",
serverId: "srv_1",
userId: "u_gone",
- } satisfies CommunityMemberLeave)
- capturedOnMessage!({
+ } satisfies CommunityMemberLeave))
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:member.update",
serverId: "srv_1",
memberId: "srv_1-remaining",
changes: { role: "admin" },
- } satisfies CommunityMemberUpdate)
+ } satisfies CommunityMemberUpdate))
expect(capturedQueryClient.getQueryData<{ pages: Array<{ members: Array<{ userId: string }> }> }>(current)?.pages[0]?.members.map((member) => member.userId)).toEqual(["u_remaining"])
expect(capturedQueryClient.getQueryData(other)).toBe(otherBefore)
const registry = (await import("./test-harness")).canonicalRegistry!
@@ -377,7 +380,7 @@ describe("useCommunityWs — member events", () => {
userId: "u_renamed",
changes: { nickname: "NewName" },
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const channelCache = capturedQueryClient.getQueryData<{
pages: { messages: { id: string; authorName: string }[] }[]
@@ -415,7 +418,7 @@ describe("useCommunityWs — member events", () => {
memberId: "mem_1",
changes: { role: "admin" },
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const cache = capturedQueryClient.getQueryData<{
pages: { messages: { id: string; authorName: string }[] }[]
@@ -432,7 +435,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
seedCanonicalThread("srv_1", "private_parent", "forum", "private")
seedCommunityAttentionScope(capturedQueryClient, { channelId: "private", serverId: "srv_1", seq: 1 })
- capturedOnMessage!({ type: "community:channel.membership.change", relation: "notify", present: false, serverId: "srv_1", channelId: "private", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", relation: "notify", present: false, serverId: "srv_1", channelId: "private", userId: "u_me" }))
expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("private")?.ordinaryUnread)).toBe(false)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("private")).toBe(false)
seedCommunityAttentionScope(capturedQueryClient, { channelId: "private", serverId: "srv_1", seq: 2 })
@@ -443,27 +446,27 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
it("member_add invalidates channelMembers AND threadParticipants for a child thread", async () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!({
- type: "community:channel.member_add",
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "notify", present: true,
+ type: "community:channel.membership.change",
serverId: "srv_1",
channelId: "ch_1",
userId: "u_new",
- })
+ }))
const invalidated = (key: unknown) =>
spy.mock.calls.some((c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(key))
- expect(invalidated(communityKeys.channelMembers("ch_1"))).toBe(true)
+ await vi.waitFor(() => expect(invalidated(communityKeys.channelMembers("ch_1", "notify"))).toBe(true))
expect(invalidated(communityKeys.threadParticipants("ch_1"))).toBe(true)
})
it("member_remove invalidates threadParticipants too", async () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!({
- type: "community:channel.member_remove",
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "notify", present: false,
+ type: "community:channel.membership.change",
serverId: "srv_1",
channelId: "ch_1",
userId: "u_gone",
- })
+ }))
expect(
spy.mock.calls.some(
(c) => JSON.stringify(c[0]?.queryKey) === JSON.stringify(communityKeys.threadParticipants("ch_1")),
@@ -485,12 +488,12 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
categories: [{ id: "cat_1", channels: [{ id: "ch_1", type: "text" }] }],
})
- capturedOnMessage!({
- type: "community:channel.member_remove",
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: false,
+ type: "community:channel.membership.change",
serverId: "srv_1",
channelId: "ch_1",
userId: "u_other",
- })
+ }))
expect(capturedQueryClient.getQueryState(messagesKey)).toBeDefined()
expect(capturedQueryClient.getQueryState(pinsKey)).toBeDefined()
@@ -508,12 +511,12 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
id: "srv_1",
categories: [{ id: "cat_1", channels: [{ id: "ch_1", type: "text" }] }],
})
- capturedOnMessage!({
- type: "community:channel.member_remove",
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: false,
+ type: "community:channel.membership.change",
serverId: "srv_1",
channelId: "ch_1",
userId: "u_me",
- })
+ }))
expect(hasCanonicalChannel("ch_1")).toBe(false)
})
@@ -523,11 +526,10 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
const { useCommunityStore } = await import("@/stores/community")
const key = communityKeys.forumSidebarThreads("srv_1")
await act(async () => { seedCanonicalForumSidebar("srv_1", ["post_1", "post_2"]) })
- await act(async () => { patchCanonicalCommunityChannel(capturedQueryClient, "forum_1", row => ({ ...row, type: parentType })) })
- await act(async () => { patchCanonicalCommunityChannel(capturedQueryClient, "post_1", (row) => ({
- ...row,
- unread: true,
- })) })
+ await act(async () => {
+ patchCanonicalCommunityChannel(capturedQueryClient, "forum_1", row => ({ ...row, type: parentType }))
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "post_1", serverId: "srv_1", parentChannelId: "forum_1", seq: 1 })
+ })
await act(async () => { getCapturedRuntime().ui.actions.setCurrentChannelId("post_1") })
await act(async () => { seedCanonicalFocusedChannel({
name: "Private forum title",
@@ -536,24 +538,24 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
}) })
const { useCommunityWsStore } = await import("@/stores/community/ws")
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.membership.change", relation: "notify", present: false,
serverId: "srv_1",
channelId: "post_1",
userId: "u_me",
- }) })
+ })) })
expect(hasCanonicalChannelAccess("post_1", "u_me")).toBe(true)
expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(false)
expect(getCanonicalCommunityChannels(capturedQueryClient)
.find(({ id }) => id === "post_1")).not.toHaveProperty("unread")
expect(readCurrentCommunityChannelMeta(capturedQueryClient)?.name).toBe("Private forum title")
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.membership.change", relation: "notify", present: true,
serverId: "srv_1",
channelId: "post_2",
userId: "u_me",
- }) })
+ })) })
expect(hasCanonicalChannelAccess("post_2", "u_me")).toBe(true)
expect(hasCanonicalChannelNotify("post_2", "u_me")).toBe(true)
})
@@ -583,12 +585,12 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
hint: capturedQueryClient.getQueryData(hintKey),
}
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.membership.change", relation: "notify", present: true,
serverId: "srv_1",
channelId: "text_thread",
userId: "u_me",
- })
+ }))
expect(capturedQueryClient.getQueryData(baseKey)).toBe(before.base)
expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
@@ -601,12 +603,12 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
name: "Private title",
parentChannelId: "text_parent",
})
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.membership.change", relation: "notify", present: false,
serverId: "srv_1",
channelId: "text_thread",
userId: "u_me",
- })
+ }))
expect(capturedQueryClient.getQueryData(baseKey)).toBe(before.base)
expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
@@ -628,7 +630,7 @@ describe("membership metadata and access lifetime", () => {
capturedQueryClient.setQueryData(key, content)
const api = getCommunityApiFetchMock()
api.mockResolvedValue(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, creatorId: null, createdAt: "2026-10-01T00:00:00Z", lastMessageAt: null, id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", name: "Child", archived: false }, "u_me"))
- capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present }))
if (!present) expect(capturedQueryClient.getQueryData(key)).toBeUndefined()
else expect(capturedQueryClient.getQueryData(key)).toEqual(content)
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).toMatchObject({ channelId: "child", proof: expect.any(Object) }))
@@ -648,7 +650,7 @@ describe("membership metadata and access lifetime", () => {
seedCommunityAttentionScope(capturedQueryClient, { channelId: "dm-private", serverId: null, seq: 2 })
const api = getCommunityApiFetchMock()
api.mockRejectedValue(new ApiError("DM blocked", 403))
- capturedOnMessage!({ type: "community:channel.membership.change", channelId: "dm-private", serverId: null, userId: "u_me", relation: "access", present: false })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "dm-private", serverId: null, userId: "u_me", relation: "access", present: false }))
expect(capturedQueryClient.getQueryData(key)).toBeUndefined()
expect(capturedQueryClient.getQueryData(otherKey)).toBeDefined()
expect(getCapturedRuntime().ui.get()).toMatchObject({ currentChannelId: null, subscription: { channelId: "other-channel" } })
@@ -670,7 +672,7 @@ describe("membership metadata and access lifetime", () => {
const error = new ApiError("metadata lookup failed", status)
api.mockImplementation((...args) => args[0] === "/api/community/channels/child/messages?entry=1" ? Promise.reject(error) : fallback(...args))
const query = vi.spyOn(capturedQueryClient, "query")
- capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true }))
await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything()))
await expect(query.mock.results[0]!.value).rejects.toBe(error)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(status !== 500)
@@ -691,7 +693,7 @@ describe("membership metadata and access lifetime", () => {
capturedQueryClient.setQueryData(key, { pages: [{ messages: [{ id: "private" }] }] })
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)
const query = vi.spyOn(capturedQueryClient, "query")
- capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true }))
await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything()))
await expect(query.mock.results[0]!.value).rejects.toBe(archived)
await vi.waitFor(() => expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(true))
@@ -704,11 +706,12 @@ describe("membership metadata and access lifetime", () => {
seedCanonicalThread("server", "parent", "forum", "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
creatorId: "u_me", name: "Child", archived: false, lastMessageAt: null, createdAt: "2026-08-01T00:00:00.000Z",
- readContractVersion: 2, accessDecision: { channelId: "child", canRead: true, canSend: true, canCreateDiscussion: false } }, "u_me")
- const member = { id: "member", userId: "u_me", role: "member", name: "Viewer", discriminator: "0001",
- avatar: "", avatarVersion: 0, source: "explicit", isCreator: true }
+ }, "u_me")
+ const member = { channelId: "child", userId: "u_me", relation: "notify" as const, role: "member", memberId: "member", source: "explicit", isCreator: true }
+ const memberResponse = (members: typeof member[]) => ({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "child", relation: "notify", members,
+ profiles: [{ id: "u_me", name: "Viewer", discriminator: "0001", avatar: null, avatarVersion: 0 }] })
const api = getCommunityApiFetchMock()
- api.mockImplementation(async (path: string) => path.endsWith("/members?relation=notify") ? { members: [member] } : payload)
+ api.mockImplementation(async (path: string) => path.endsWith("/members?relation=notify") ? memberResponse([member]) : payload)
const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))
const roster = await mountCanonicalHook(() => useChannelMembers("child", true, "server", "notify"))
await vi.waitFor(() => {
@@ -730,15 +733,15 @@ describe("membership metadata and access lifetime", () => {
let pending!: ReturnType<typeof roster.result.current.refetch>
act(() => { pending = roster.result.current.refetch() })
await vi.waitFor(() => expect(reads).toHaveLength(1))
- await act(async () => capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "notify", present: false }))
+ await act(async () => capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "notify", present: false })))
await vi.waitFor(() => expect(reads).toHaveLength(2))
expect(reads[0]!.signal.aborted).toBe(true)
- await act(async () => reads[1]!.resolve({ members: [] }))
+ await act(async () => reads[1]!.resolve(memberResponse([])))
await vi.waitFor(() => {
expect(roster.result.current.members).toHaveLength(0)
expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)
})
- await act(async () => { reads[0]!.resolve({ members: [member] }); await pending })
+ await act(async () => { reads[0]!.resolve(memberResponse([member])); await pending })
expect(roster.result.current.members).toHaveLength(0)
expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)
expect(metadata.result.current.data!.readProof).toBe(proof)
@@ -760,14 +763,14 @@ describe("membership metadata and access lifetime", () => {
capturedQueryClient.setQueryData(communityKeys.channelMessages("child"), content)
const bodyQuery = capturedQueryClient.getQueryCache().find({ queryKey: communityKeys.channelMessages("child"), exact: true })
const generation = getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation
- await act(async () => capturedOnMessage!({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "notify", present }))
+ await act(async () => capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "notify", present })))
expect(metadata.result.current.isVerified).toBe(true)
expect(metadata.result.current.data!.identityProof).toBe(proof)
expect(getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation).toBe(generation)
expect(capturedQueryClient.getQueryCache().find({ queryKey: communityKeys.channelMessages("child"), exact: true })).toBe(bodyQuery)
expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("child"))).toEqual(content)
})
- it.each(["text", "forum"] as const)("replaces an in-flight %s child metadata read when participation changes again", async (parentType) => {
+ it.each(["text", "forum"] as const)("replaces an in-flight %s child metadata read when explicit access refresh changes again", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("server", "parent", parentType, "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
@@ -778,6 +781,7 @@ describe("membership metadata and access lifetime", () => {
const currentBody = { ...conversationEntryFixture().messages[0]!, id: "m_current", channelId: "child", seq: 2, content: "Current body" }
const historyBody = { ...currentBody, id: "m_history", seq: 1, content: "History body", createdAt: "2026-09-30T00:00:01.000Z" }
payload.messages = [historyBody, currentBody]
+ payload.profiles = messageProfilesFixture(payload.messages)
payload.page = { olderCursor: `${historyBody.createdAt}|${historyBody.id}`, newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 2 }
const api = getCommunityApiFetchMock()
api.mockResolvedValue(payload)
@@ -802,9 +806,9 @@ describe("membership metadata and access lifetime", () => {
reads.push({ signal: (args[1] as { signal: AbortSignal }).signal, resolve, reject })
})
})
- capturedOnMessage!({ type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(reads).toHaveLength(1))
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(reads).toHaveLength(2))
expect(reads[0]!.signal.aborted).toBe(true)
expect(reads[1]!.signal.aborted).toBe(false)
@@ -814,7 +818,7 @@ describe("membership metadata and access lifetime", () => {
else reads[0]!.reject(new ApiError("Old denial", 403))
})
expect(metadata.result.current.data?.name).not.toBe("Old archived child")
- expect(metadata.result.current.isVerified).toBe(true)
+ expect(metadata.result.current.isVerified).toBe(false)
expect(getCapturedRuntime().ws.get().channelAccessScopes.get("child")?.generation).toBe(generation)
expect(canonicalMessage(currentBody.id)?.content).toBe("Current body")
expect(canonicalMessage("m_late_only")).toBeUndefined()
@@ -836,7 +840,7 @@ describe("membership metadata and access lifetime", () => {
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(false)
})
- it("hands one batched add/remove to the latest participation generation", async () => {
+ it("hands batched explicit access refreshes to the latest access generation", async () => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("server", "parent", "text", "child")
const payload = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
@@ -849,8 +853,8 @@ describe("membership metadata and access lifetime", () => {
await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))
const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1").length
const events = [
- { type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" },
- { type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" },
+ { relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" },
+ { relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" },
] as const
const prepared = await prepareCommunityDeliveryEvents(events)
if (!prepared.ok) throw new Error("Participant events must prepare")
@@ -877,13 +881,13 @@ describe("membership metadata and access lifetime", () => {
const api = getCommunityApiFetchMock()
api.mockResolvedValue(payload)
const metaKey = entryKey("server", "child")
- capturedQueryClient.setQueryDefaults(metaKey, { retryDelay: 0 })
+ capturedQueryClient.setQueryDefaults(communityKeys.conversationEntries("child"), { retryDelay: 0 })
const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))
await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))
const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1").length
api.mockRejectedValue(new ApiError("temporary", 503))
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
- await vi.waitFor(() => expect(metadata.result.current).toMatchObject({ isError: true, fetchStatus: "idle", isVerified: true }))
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
+ await vi.waitFor(() => expect(metadata.result.current).toMatchObject({ isError: true, fetchStatus: "idle", isVerified: false }))
expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1")).toHaveLength(before + 2)
await act(async () => { await new Promise<void>((resolve) => setTimeout(resolve, 20)) })
expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1")).toHaveLength(before + 2)
@@ -916,9 +920,9 @@ describe("membership metadata and access lifetime", () => {
vi.spyOn(capturedQueryClient, "cancelQueries").mockImplementation(async (...args) => { await cancel(...args); await gate })
const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1").length
await act(async () => {
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
- if (race === "parent") capturedOnMessage!({ type: "community:channel.member_remove", channelId: "parent", serverId: "server", userId: "u_me" })
- else if (race === "server") capturedOnMessage!({ type: "community:member.leave", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "notify", present: false, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
+ if (race === "parent") capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: false, type: "community:channel.membership.change", channelId: "parent", serverId: "server", userId: "u_me" }))
+ else if (race === "server") capturedOnMessage!(currentCommunityEventFixture({ type: "community:member.leave", serverId: "server", userId: "u_me" }))
else if (race === "account") getCapturedRuntime().ws.actions.activateProfileAccount("other")
else metadata.unmount()
})
@@ -950,7 +954,7 @@ describe("membership metadata and access lifetime", () => {
expect(capturedQueryClient.getQueryData(metaKey)).not.toHaveProperty("type")
const content = { pages: [{ messages: [{ id: "m1" }] }] }
act(() => { capturedQueryClient.setQueryData(key, content) })
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "notify", present: false, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))
expect(metadata.result.current.data).toMatchObject({ id: "child", type: "thread" })
expect(hasCanonicalChannelAccess("child", "u_me")).toBe(true)
@@ -960,14 +964,14 @@ describe("membership metadata and access lifetime", () => {
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(false)
})
- it("retires unqualified legacy content before a cold relationship recheck", async () => {
+ it("replaces unqualified transport content after a cold explicit access recheck", async () => {
await mountHook({ viewerUserId: "u_me" })
const api = getCommunityApiFetchMock()
- api.mockResolvedValue(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, creatorId: null, createdAt: "2026-10-01T00:00:00Z", lastMessageAt: null, id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", name: "Child", archived: false }, "u_me"))
+ api.mockResolvedValue({ ...conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, creatorId: null, createdAt: "2026-10-01T00:00:00Z", lastMessageAt: null, id: "child", serverId: "server", type: "thread", parentChannelId: "parent", parentMessageId: "opener", name: "Child", archived: false }, "u_me"), parent: channelResourceFixture({ id: "parent", serverId: "server", type: "text" }) })
const key = communityKeys.channelMessages("child")
const content = { pages: [{ messages: [{ id: "m1", content: "readable" }] }] }
capturedQueryClient.setQueryData(key, content)
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).toMatchObject({ channelId: "child", proof: expect.any(Object) }))
expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).not.toHaveProperty("type")
const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))
@@ -976,34 +980,35 @@ describe("membership metadata and access lifetime", () => {
expect(capturedQueryClient.getQueryData(key)).toMatchObject({ pages: [{ messages: [] }] })
})
- it("restores a newly mentioned forum participant and refreshes the mounted sidebar after legacy metadata recovery", async () => {
+ it("restores a newly mentioned forum participant and refreshes the mounted sidebar after complete metadata recovery", async () => {
await mountHook({ viewerUserId: "u_me" })
const api = getCommunityApiFetchMock()
const base = communityKeys.forumSidebarThreads("server")
capturedQueryClient.setQueryData(base, { threads: [], serverNow: "2026-10-01T00:00:00Z", verifiedEpoch: 0, serverClockOffsetMs: 0 })
seedCommunityAttentionScope(capturedQueryClient, { channelId: "child", serverId: "server", parentChannelId: "forum", seq: 1, attentionCount: 1 })
- api.mockResolvedValue(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 1, creatorId: "peer", createdAt: "2026-10-01T00:00:00Z", lastMessageAt: "2026-10-01T00:00:01Z", id: "child", serverId: "server", type: "thread", parentChannelId: "forum", parentMessageId: "opener", name: "New post", archived: false }, "u_me"))
- capturedOnMessage!({ type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" })
+ api.mockResolvedValue({ ...conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 1, creatorId: "peer", createdAt: "2026-10-01T00:00:00Z", lastMessageAt: "2026-10-01T00:00:01Z", id: "child", serverId: "server", type: "thread", parentChannelId: "forum", parentMessageId: "opener", name: "New post", archived: false }, "u_me"), parent: channelResourceFixture({ id: "forum", serverId: "server", type: "forum" }) })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).toMatchObject({ channelId: "child", proof: expect.any(Object) }))
+ await act(async () => capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", relation: "notify", present: true, channelId: "child", serverId: "server", userId: "u_me" })))
await vi.waitFor(() => expect(hasCanonicalChannelNotify("child", "u_me")).toBe(true))
await vi.waitFor(() => expect(capturedQueryClient.getQueryState(base)?.isInvalidated).toBe(true))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)
expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("child")?.ordinaryUnread)).toBe(true)
})
- it.each([403, 404, 500].flatMap((status) => (["community:channel.member_add", "community:channel.member_remove"] as const).map((type) => ({ status, type }))))("keeps unknown legacy content retired after $type when the access recheck returns $status", async ({ status, type }) => {
+ it.each([403, 404, 500].flatMap((status) => ([true, false] as const).map((present) => ({ status, present }))))("keeps denied access retired and transient access unqualified for present=$present and status=$status", async ({ status, present }) => {
await mountHook({ viewerUserId: "u_me" })
const { ApiError } = await import("@/lib/errors")
const { useCommunityWsStore } = await import("@/stores/community/ws")
getCommunityApiFetchMock().mockRejectedValue(new ApiError("lookup failed", status))
const key = communityKeys.channelMessages("child")
capturedQueryClient.setQueryData(key, { pages: [] })
- capturedOnMessage!({ type, channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", relation: "access", present, channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything()))
await vi.waitFor(() => expect(capturedQueryClient.getQueryState(entryKey("server", "child"))?.fetchStatus ?? "idle").toBe("idle"))
- expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(true)
- expect(capturedQueryClient.getQueryData(key) === undefined).toBe(true)
+ expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(!present || status !== 500)
+ expect(capturedQueryClient.getQueryData(key) === undefined).toBe(!present || status !== 500)
expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)
})
@@ -1013,15 +1018,15 @@ describe("membership metadata and access lifetime", () => {
let release!: (value: unknown) => void
const api = getCommunityApiFetchMock()
api.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: false, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(release).toBeTypeOf("function"))
- const meta = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
+ const meta = { ...conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "child", serverId: "server", name: "Child", type: "thread",
parentChannelId: "parent", parentMessageId: "opener", creatorId: null,
archived: false, lastMessageAt: null,
- }, "u_me")
+ }, "u_me"), parent: channelResourceFixture({ id: "parent", serverId: "server", type: "text" }) }
api.mockResolvedValue(meta)
- capturedOnMessage!({ type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).toMatchObject({ channelId: "child", proof: expect.any(Object) }))
release({ ...meta, channel: { ...meta.channel, type: "text", parentChannelId: null, parentMessageId: null } })
await Promise.resolve()
@@ -1030,9 +1035,9 @@ describe("membership metadata and access lifetime", () => {
let releaseAfterLeave!: (value: unknown) => void
api.mockImplementationOnce(() => new Promise((resolve) => { releaseAfterLeave = resolve }))
- capturedOnMessage!({ type: "community:channel.member_add", channelId: "other", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "other", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(releaseAfterLeave).toBeTypeOf("function"))
- capturedOnMessage!({ type: "community:member.leave", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:member.leave", serverId: "server", userId: "u_me" }))
releaseAfterLeave(conversationEntryFromChannel({ ...meta.channel, id: "other" }, "u_me"))
await Promise.resolve()
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("other", "server")).toBe(true)
@@ -1050,12 +1055,14 @@ describe("membership metadata and access lifetime", () => {
getCapturedRuntime().ui.actions.setCurrentServerId("server")
getCapturedRuntime().ui.actions.setCurrentChannelId("child")
getCapturedRuntime().ui.actions.subscribe({ channelId: "child" })
- capturedOnMessage!({ type: "community:channel.member_remove", channelId: "parent", serverId: "server", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: false, type: "community:channel.membership.change", channelId: "parent", serverId: "server", userId: "u_me" }))
expect(capturedQueryClient.getQueryData(communityKeys.pins("child"))).toBeUndefined()
expect(getCapturedRuntime().ui.get().currentChannelId).toBeNull()
- capturedOnMessage!({ type: "community:message.create", channelId: "child", parentChannelId: "parent", serverId: "server", message: {
+ capturedOnMessage!(currentCommunityEventFixture({ profiles: messageProfilesFixture([messageResourceFixture({ channelId: "child",
+ id: "late", seq: 2, authorId: "author", authorName: "Author", authorAvatarVersion: 0, content: "late", type: "chat", createdAt: "2026-09-06T00:00:00.000Z",
+ })]), type: "community:message.create", channelId: "child", parentChannelId: "parent", serverId: "server", message: messageResourceFixture({ channelId: "child",
id: "late", seq: 2, authorId: "author", authorName: "Author", authorAvatarVersion: 0, content: "late", type: "chat", createdAt: "2026-09-06T00:00:00.000Z",
- } })
+ }) }))
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "child", serverId: "server" }).liveIds.length).toBe(0)
})
})
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 06b813a04..05d0f2a73 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -8,7 +8,6 @@ import type {
CommunityMemberJoin,
CommunityMemberLeave,
CommunityMemberUpdate,
- CommunityWsEvent,
} from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
@@ -17,23 +16,13 @@ import {
isKnownNonForumSidebarChannel,
} from "@/hooks/community/use-forum-sidebar-threads"
-import { getQualifiedConversationEntry } from "@/lib/community/conversation-entry"
import { channelMetadataOptions, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"
import { runCommunityWsProjectionTransaction } from "./projection-transaction"
import type { MembershipEventContext } from "@/hooks/community/community-ws/handler-context"
import { evictServerChannelScopes } from "./scope-eviction"
-import {
- invalidateChannelRefDirectory,
- invalidateForumSidebar,
- invalidateInbox,
- invalidateChannelRoster,
- invalidateInvitableFriends,
- invalidatePresence,
- invalidateServerDetail,
- invalidateServersList,
-} from "./invalidation-projections"
+import { invalidateChannelRefDirectory, invalidateForumSidebar, invalidateInbox, invalidateInvitableFriends, invalidatePresence, invalidateServerDetail, invalidateServersList } from "./invalidation-projections"
import {
refreshServerReactionDetails,
removeServerReactionDetails,
@@ -44,17 +33,12 @@ import {
setCanonicalCommunityChannelMember,
} from "@/lib/community-db/sync"
-type ChannelMemberEvent = Extract<
- CommunityWsEvent,
- { type: "community:channel.member_add" | "community:channel.member_remove" }
->
-
function retireChannelAccess(event: { serverId: string | null; channelId: string }, context: MembershipEventContext) {
const registry = getCommunityDbRegistry(context.queryClient)
if (registry) retireCommunityChannelReading(registry, event.channelId, { reason: "read-denied", serverId: event.serverId })
}
-function refreshChannelAccess(event: { serverId: string | null; channelId: string }, context: MembershipEventContext, legacyEvent?: ChannelMemberEvent) {
+function refreshChannelAccess(event: { serverId: string | null; channelId: string }, context: MembershipEventContext) {
const { queryClient } = context
const token = captureChannelMetadataToken(queryClient, event.channelId)
const options = channelMetadataOptions(queryClient, event.serverId, event.channelId)
@@ -67,14 +51,8 @@ function refreshChannelAccess(event: { serverId: string | null; channelId: strin
if (!isChannelMetadataTokenCurrent(token)) return
const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === event.channelId && row.serverId === event.serverId)
if (channel?.archived) runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection }))
- else if (channel) {
- if (legacyEvent && channel.type === "thread") runCommunityWsProjectionTransaction(queryClient, (projection) => {
- handleChannelMembershipChange({ ...legacyEvent, type: "community:channel.membership.change", relation: "notify", present: legacyEvent.type === "community:channel.member_add" }, { ...context, projection })
- })
- }
- } catch {
- if (legacyEvent?.type === "community:channel.member_add" && isChannelMetadataTokenCurrent(token)) runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection }))
- }
+ } catch {}
+
})()
}
@@ -100,28 +78,6 @@ export function handleChannelMembershipChange(event: CommunityChannelMembershipC
refreshChannelAccess(event, context)
}
-export function handleChannelMemberEvent(event: ChannelMemberEvent, context: MembershipEventContext) {
- const { queryClient } = context
- const proof = getQualifiedConversationEntry(queryClient, event.channelId)?.proof
- const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === event.channelId && row.serverId === event.serverId)
- const verified = !!proof && isChannelMetadataTokenCurrent(proof) && !channel?.pending && !channel?.archived
- && !getCommunityRuntime(queryClient).ws.actions.isChannelAccessRevoked(event.channelId, event.serverId)
- const relation = verified && channel?.type === "thread" ? "notify"
- : verified && (channel?.type === "text" || channel?.type === "forum") ? "access" : undefined
- if (relation) {
- handleChannelMembershipChange({ ...event, type: "community:channel.membership.change", relation, present: event.type === "community:channel.member_add" }, context)
- if (relation === "notify" && event.userId === context.viewerUserIdRef.current) {
- const token = captureChannelMetadataToken(queryClient, event.channelId)
- context.projection.fence("channel-metadata", { queryKey: channelMetadataOptions(queryClient, event.serverId, event.channelId).queryKey, exact: true }, () => isChannelMetadataTokenCurrent(token))
- }
- return
- }
- if (event.userId === context.viewerUserIdRef.current) {
- if (event.type === "community:channel.member_remove") retireChannelAccess(event, context)
- refreshChannelAccess(event, context, event)
- } else invalidateChannelRoster(context.projection, event.channelId)
-}
-
function finishMemberEvent(
event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate,
{ projection }: MembershipEventContext,
diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
index 51e989993..9ba8a69fb 100644
--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
@@ -1,3 +1,6 @@
+import { messageProfilesFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { messageResourceFixture, currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { botCreationFixture } from "@/test/bot-creation-fixtures"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { seedCanonicalFocusedChannel } from "./test-harness"
@@ -10,7 +13,7 @@ import type {
CommunityReactionAdd,
} from "@alook/shared"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
-import { writeCommunityProfilePatches, beginCommunityProfileSeed } from "@/lib/community/profile-seed"
+import { writeCommunityProfilePatches, beginCommunityProfileSeed, communityUserProfilePatch } from "@/lib/community/profile-seed"
import { getMessageStreamState } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"
@@ -62,17 +65,17 @@ function seedParent(serverId: string, parentId: string, type: "forum" | "text")
}
describe("useCommunityWs — message.create", () => {
- it("publishes confirmed message and author once before the ID view consumes it", async () => {
+ it("publishes the supplied complete author profile before its confirmed message", async () => {
getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_once" })
resetHookMemoization()
await mountHook()
const registry = getCommunityDbRegistry(capturedQueryClient)!
const revision = beginCommunityProfileSeed(registry).revision
const event = messageCreate("ch_once")
- capturedOnMessage!(event)
- expect(beginCommunityProfileSeed(registry).revision).toBe(revision + 1)
+ capturedOnMessage!(currentCommunityEventFixture(event))
+ expect(beginCommunityProfileSeed(registry).revision).toBe(revision)
expect(registry.collections.messages.get(event.message.id)).toMatchObject({ content: event.message.content })
- expect(registry.collections.profiles.get(event.message.authorId)).toMatchObject({ name: event.message.authorName })
+ expect(registry.collections.profiles.get(event.message.authorId)).toMatchObject(event.profiles[0])
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_once", serverId: "s1" }).liveIds).toContain(event.message.id)
expect(canonicalMessage(event.message.id)).toMatchObject({ content: event.message.content })
})
@@ -89,7 +92,7 @@ describe("useCommunityWs — message.create", () => {
const event = messageCreate("ch_gap")
event.message.seq = 5
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(scheduleGapRepairMock).toHaveBeenCalledWith(
capturedQueryClient,
@@ -106,8 +109,8 @@ describe("useCommunityWs — message.create", () => {
const event = messageCreate("dm_gap")
event.message.seq = 8
- capturedOnMessage!(event)
- capturedOnMessage!(messageCreate("other"))
+ capturedOnMessage!(currentCommunityEventFixture(event))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("other")))
expect(scheduleGapRepairMock).toHaveBeenCalledTimes(1)
expect(scheduleGapRepairMock).toHaveBeenCalledWith(
@@ -128,7 +131,7 @@ describe("useCommunityWs — message.create", () => {
parentChannelId: "forum_1",
} satisfies CommunityMessageCreate
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const data = canonicalForumSidebar("srv_1")
expect(data?.threads[0]).toMatchObject({
@@ -145,11 +148,11 @@ describe("useCommunityWs — message.create", () => {
const key = communityKeys.forumSidebarThreads("srv_1")
capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
...messageCreate("post_missing"),
serverId: "srv_1",
parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate)
+ } satisfies CommunityMessageCreate))
await vi.waitFor(() => {
expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(false)
@@ -181,11 +184,11 @@ describe("useCommunityWs — message.create", () => {
throw new Error(`unexpected API fetch: ${url}`)
})
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
...messageCreate("post_live"),
serverId: "srv_1",
parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate)
+ } satisfies CommunityMessageCreate))
await vi.waitFor(() => expect(hasCanonicalChannel("post_live")).toBe(true))
expect(getCanonicalCommunityChannels(capturedQueryClient)
@@ -197,11 +200,11 @@ describe("useCommunityWs — message.create", () => {
)
getCommunityApiFetchMock().mockRejectedValueOnce(new Error("metadata unavailable"))
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
...messageCreate("post_unavailable"),
serverId: "srv_1",
parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate)
+ } satisfies CommunityMessageCreate))
await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
"/api/community/channels/post_unavailable/messages?entry=1",
expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function), authenticationAccount: "u_me" }),
@@ -220,11 +223,11 @@ describe("useCommunityWs — message.create", () => {
seedCanonicalForumSidebar("srv_1", ["post_retained"])
const key = communityKeys.forumSidebarThreads("srv_1")
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
...messageCreate("post_retained"),
serverId: "srv_1",
parentChannelId: "forum_1",
- } satisfies CommunityMessageCreate)
+ } satisfies CommunityMessageCreate))
expect(canonicalForumSidebar("srv_1").threads[0]).toMatchObject({
activityAt: "2026-07-03T00:00:00.000Z",
@@ -260,11 +263,11 @@ describe("useCommunityWs — message.create", () => {
capturedQueryClient.getQueryData(hintKey),
]
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
...messageCreate("text_thread"),
serverId: "s1",
parentChannelId: "text_parent",
- } satisfies CommunityMessageCreate)
+ } satisfies CommunityMessageCreate))
expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
@@ -291,7 +294,7 @@ describe("useCommunityWs — message.create", () => {
pageParams: [null],
})
- capturedOnMessage!(messageCreate("ch_1"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1")))
const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(
communityKeys.channelMessages("ch_1"),
@@ -309,8 +312,8 @@ describe("useCommunityWs — message.create", () => {
resetHookMemoization()
await mountHook()
- capturedOnMessage!(messageCreate("parent_1", "parent_message"))
- capturedOnMessage!(messageCreate("thread_1", "thread_message"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("parent_1", "parent_message")))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("thread_1", "thread_message")))
expect([
...getMessageStreamState(capturedQueryClient, { kind: "channel", id: "parent_1", serverId: "s1" }).liveIds,
@@ -330,8 +333,8 @@ describe("useCommunityWs — message.create", () => {
await mountHook()
getCapturedRuntime().ui.actions.releaseSecondaryChannel(owner)
- capturedOnMessage!(messageCreate("parent_hidden", "hidden_parent_message"))
- capturedOnMessage!(messageCreate("thread_1", "visible_thread_message"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("parent_hidden", "hidden_parent_message")))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("thread_1", "visible_thread_message")))
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "parent_hidden", serverId: "s1" }).liveIds)
.toHaveLength(0)
@@ -349,11 +352,11 @@ describe("useCommunityWs — message.create", () => {
await mountHook()
const event = messageCreate("ch_1")
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds).toHaveLength(0)
getCapturedRuntime().ui.actions.setCurrentServerId("s1")
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds).toHaveLength(1)
})
@@ -369,7 +372,7 @@ describe("useCommunityWs — message.create", () => {
capturedQueryClient.setQueryData(allKey, empty)
capturedQueryClient.setQueryData(bugKey, empty)
- capturedOnMessage!(messageCreate("forum_1"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("forum_1")))
expect(capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(allKey)?.pages[0].messages).toHaveLength(0)
expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(0)
@@ -382,7 +385,7 @@ describe("useCommunityWs — message.create", () => {
pages: [{ messages: [], hasMore: false }],
pageParams: [null],
})
- capturedOnMessage!(messageCreate("ch_other"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_other")))
const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
communityKeys.channelMessages("ch_other"),
)
@@ -400,7 +403,7 @@ describe("useCommunityWs — message.create", () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_1"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1")))
expect(spy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })
expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })
@@ -416,7 +419,7 @@ describe("useCommunityWs — message.create", () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_1"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1")))
expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_1") })
expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_1") })
@@ -433,7 +436,7 @@ describe("useCommunityWs — message.create", () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_other"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_other")))
expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.channelMembers("ch_other") })
expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.threadParticipants("ch_other") })
@@ -450,9 +453,9 @@ describe("useCommunityWs — message.create", () => {
pages: [{ messages: [], hasMore: false }],
pageParams: [null],
})
- capturedOnMessage!(messageCreate("ch_1"))
- capturedOnMessage!(messageCreate("ch_1"))
- capturedOnMessage!(messageCreate("ch_1"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1")))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1")))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1")))
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_1", serverId: "s1" }).liveIds.length).toBe(1)
})
@@ -474,7 +477,7 @@ describe("useCommunityWs — message.create", () => {
pageParams: [null],
})
- capturedOnMessage!(messageCreate("ch_1", "new_message"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1", "new_message")))
const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
communityKeys.channelMessages("ch_1"),
@@ -505,7 +508,7 @@ describe("useCommunityWs — message.create", () => {
pageParams: [null],
})
- capturedOnMessage!(messageCreate("ch_1", "new_message"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1", "new_message")))
const cache = capturedQueryClient.getQueryData<{
pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean }[]
@@ -536,7 +539,7 @@ describe("useCommunityWs — message.create", () => {
pageParams: [{ mode: "anchor", anchor: "seed_0" }],
})
- capturedOnMessage!(messageCreate("ch_1", "new_message"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1", "new_message")))
const cache = capturedQueryClient.getQueryData<{
pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]
@@ -567,7 +570,7 @@ describe("useCommunityWs — message.create", () => {
],
pageParams: [null],
})
- capturedOnMessage!(messageCreate("ch_1", "m_new"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1", "m_new")))
const cache = capturedQueryClient.getQueryData<{
pages: { hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]
}>(communityKeys.channelMessages("ch_1"))
@@ -586,7 +589,7 @@ describe("useCommunityWs — message.create", () => {
pages: [{ messages: [{ id: "seed_0", content: "x", createdAt: "t" }], hasMore: false }],
pageParams: [null],
})
- capturedOnMessage!(messageCreate("ch_1", "m_new"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_1", "m_new")))
const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
communityKeys.channelMessages("ch_1"),
)
@@ -599,7 +602,7 @@ describe("useCommunityWs — message.create", () => {
try {
await mountHook({ viewerUserId: "u_author" })
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_random"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_random")))
vi.advanceTimersByTime(1_000)
expect(invalidateSpy).not.toHaveBeenCalled()
} finally {
@@ -613,11 +616,11 @@ describe("useCommunityWs — message.create", () => {
await mountHook({ viewerUserId: "u_me" })
const fetchAttention = vi.spyOn(capturedQueryClient, "query")
for (let i = 0; i < 10; i++) {
- capturedOnMessage!(messageCreate("ch_x", `m_${i}`))
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_x", `m_${i}`)))
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:unread.bump", userId: "u_me", channelId: "ch_x",
serverId: "s1", isMention: false,
- })
+ }))
}
expect(fetchAttention).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(500)
@@ -653,12 +656,12 @@ describe("useCommunityWs — message.create", () => {
)
const event = messageCreate("ch_focused", "m_focused")
- capturedOnMessage!(event)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture(event))
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:unread.bump", userId: "u_me", channelId: event.channelId,
serverId: "s1", isMention: false,
- })
- capturedOnMessage!(event)
+ }))
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(order).toEqual(["candidate"])
await vi.advanceTimersByTimeAsync(500)
@@ -684,7 +687,7 @@ describe("useCommunityWs — message.create", () => {
)
const event = messageCreate("ch_focused", "m_committed")
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(promoteInboxReadReservation(lease, 20)).toBe(true)
await settleInboxReadReservationGeneration(
capturedQueryClient,
@@ -694,7 +697,7 @@ describe("useCommunityWs — message.create", () => {
)
seen.mockClear()
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(seen).not.toHaveBeenCalled()
await expect(reserveInboxUnreadsResponse(capturedQueryClient, {
@@ -724,10 +727,11 @@ describe("useCommunityWs — message.create", () => {
},
)
- capturedOnMessage!(messageCreate("ch_focused", "m_self"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_focused", "m_self")))
const background = messageCreate("ch_background", "m_background")
background.message.authorId = "u_other"
- capturedOnMessage!(background)
+ background.profiles = messageProfilesFixture([background.message])
+ capturedOnMessage!(currentCommunityEventFixture(background))
expect(seen).toEqual([])
releaseInboxReadReservationSurface(lease)
@@ -776,11 +780,11 @@ describe("useCommunityWs — message.create", () => {
)
const event = messageCreate("ch_focused", "m_visible")
- capturedOnMessage!(event)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture(event))
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:unread.bump", userId: "u_me", channelId: event.channelId,
serverId: "s1", isMention: false,
- })
+ }))
expect(submitReadIntent(lease, {
kind: "timeline",
channelId: "ch_focused",
@@ -818,8 +822,8 @@ describe("useCommunityWs — reactions", () => {
emoji: "👍",
}
- capturedOnMessage!(event)
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(canonicalMessage("m_opener")?.reactions).toEqual([
{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] },
@@ -847,7 +851,7 @@ describe("useCommunityWs — reactions", () => {
userId: "u_other",
emoji: "👍",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const cache = capturedQueryClient.getQueryData<{
pages: { messages: { id: string; reactions: { emoji: string; count: number; me: boolean }[] }[] }[]
}>(communityKeys.channelMessages("ch_1"))
@@ -862,13 +866,13 @@ describe("useCommunityWs — reactions", () => {
getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_empty" })
await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:reaction.add",
channelId: "ch_empty",
messageId: "m_missing",
userId: "u_other",
emoji: "👍",
- })
+ }))
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch_empty", serverId: "s1" }).liveIds.length)
.toBe(0)
@@ -890,13 +894,13 @@ describe("useCommunityWs — reactions", () => {
communityKeys.messageContext("dm", "ch_1", 8),
unresolvedContext,
)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:reaction.add",
channelId: "ch_1",
messageId: "m_1",
userId: "u_other",
emoji: "🔥",
- })
+ }))
expect(canonicalMessage("m_1")?.reactions).toEqual([
{ emoji: "🔥", count: 1, me: false, userIds: ["u_other"] },
])
@@ -927,13 +931,13 @@ describe("useCommunityWs — reactions", () => {
},
)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:reaction.add",
channelId: "dm_1",
messageId: "m_dm",
userId: "u_me",
emoji: "👍",
- })
+ }))
expect(getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveIds).toContain("m_dm")
expect(canonicalMessage("m_dm")?.reactions).toEqual([
@@ -959,13 +963,13 @@ describe("useCommunityWs — reactions", () => {
},
})
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:reaction.add",
channelId: "ch_1",
messageId: "m_channel",
userId: "u_me",
emoji: "👍",
- })
+ }))
expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain("m_channel")
expect(canonicalMessage("m_channel")?.reactions).toEqual([
@@ -975,6 +979,31 @@ describe("useCommunityWs — reactions", () => {
})
describe("useCommunityWs — message.updated", () => {
+ it.each([1, 3])("keeps real renamed approval identities when an old message.updated arrives with avatar v2 over v%s", async currentVersion => {
+ getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm_1" })
+ await mountHook()
+ const registry = getCommunityDbRegistry(capturedQueryClient)!
+ const identities = [
+ { id: "friend", name: "Old Friend", discriminator: "0001", image: "/api/community/users/friend/avatar", avatarVersion: 1 },
+ { id: "bot", name: "Old Bot", discriminator: "0002", image: "/api/community/bots/bot/avatar", avatarVersion: 1 },
+ ]
+ writeCommunityProfilePatches(identities.map(profile => communityUserProfilePatch(profile.id, profileResourceFixture({ id: profile.id, name: profile.name, discriminator: profile.discriminator, avatar: `/known-${profile.id}.png`, avatarVersion: currentVersion }))), registry, { command: true })
+ const approval = { friendshipId: "friendship", status: "pending" as const, waitingOn: "you" as const, otherProfile: identities[0]!, botProfile: identities[1]!, waitingOnProfile: null }
+ seedCanonicalStream({ kind: "dm", id: "dm_1" }, { type: "wsMessage", message: { id: "delayed-approval", seq: 4, type: "chat", content: "", approval } })
+ const delayed = currentCommunityEventFixture({ type: "community:message.updated", channelId: "dm_1", messageId: "delayed-approval", approval: { ...approval, status: "denied", waitingOn: null,
+ otherProfile: { ...identities[0]!, avatarVersion: 2 }, botProfile: { ...identities[1]!, avatarVersion: 2 } } })
+ for (const [index, profile] of identities.entries()) capturedOnMessage!(currentCommunityEventFixture({ type: "community:profile.update", userId: profile.id,
+ name: `Renamed ${profile.id}`, discriminator: `009${index + 1}`, aboutMe: "Current bio", bannerColor: null, kind: index === 0 ? "human" : "bot", ownerUserId: index === 0 ? null : "owner" }))
+ const revision = beginCommunityProfileSeed(registry).revision
+ capturedOnMessage!(delayed)
+ expect(canonicalMessage("delayed-approval")?.approval).toMatchObject({ status: "denied", waitingOn: null })
+ for (const [index, profile] of identities.entries()) expect(registry.collections.profiles.get(profile.id)).toMatchObject({
+ name: `Renamed ${profile.id}`, discriminator: `009${index + 1}`, aboutMe: "Current bio",
+ avatar: currentVersion === 1 ? `${profile.image}?v=2` : `/known-${profile.id}.png`, avatarVersion: currentVersion === 1 ? 2 : 3,
+ })
+ expect(beginCommunityProfileSeed(registry).revision).toBe(revision)
+ })
+
it("projects gallery resolution without erasing friendship approval or overwriting a renamed identity", async () => {
getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm_1" })
await mountHook()
@@ -984,12 +1013,12 @@ describe("useCommunityWs — message.updated", () => {
capturedQueryClient.setQueryData(communityKeys.bots(), { bots: [] })
const request = botCreationFixture({ status: "approved" })
request.bots[0]!.createdBot = { id: "new-bot", name: "Researcher", discriminator: "0042", image: null, avatarVersion: 0 }
- writeCommunityProfilePatches([{ id: "new-bot", identityAbout: { name: "Renamed Bot", discriminator: "0042" } }], getCommunityDbRegistry(capturedQueryClient), { command: true })
- capturedOnMessage!({ type: "community:message.updated", channelId: "dm_1", messageId: "gallery-message", botCreation: request })
+ writeCommunityProfilePatches([{ id: "new-bot", avatar: { avatar: null, avatarVersion: 0 }, identityAbout: { discriminator: "0042", name: "Renamed Bot" } }], getCommunityDbRegistry(capturedQueryClient), { command: true })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:message.updated", channelId: "dm_1", messageId: "gallery-message", botCreation: request }))
expect(canonicalMessage("gallery-message")).toMatchObject({ approval, botCreation: request })
expect(getCommunityDbRegistry(capturedQueryClient)!.collections.profiles.get("new-bot")).toMatchObject({ name: "Renamed Bot", discriminator: "0042" })
expect(capturedQueryClient.getQueryState(communityKeys.bots())?.isInvalidated).toBe(true)
- capturedOnMessage!({ type: "community:message.updated", channelId: "dm_1", messageId: "gallery-message", approval: { ...approval, status: "denied", waitingOn: null } })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:message.updated", channelId: "dm_1", messageId: "gallery-message", approval: { ...approval, status: "denied", waitingOn: null } }))
expect(canonicalMessage("gallery-message")?.botCreation).toEqual(request)
})
@@ -1027,12 +1056,12 @@ describe("useCommunityWs — message.updated", () => {
waitingOnProfile: { ...profile, id: "waiting_1", name: "Waiting" },
}
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:message.updated",
channelId: "dm_1",
messageId: "m_dm",
approval,
- })
+ }))
expect(getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveIds).toContain("m_dm")
expect(canonicalMessage("m_dm")?.approval).toEqual(approval)
@@ -1066,12 +1095,12 @@ describe("useCommunityWs — message.updated", () => {
botProfile: { ...profile, id: "bot_1", name: "Bot" },
}
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:message.updated",
channelId: "ch_1",
messageId: "m_channel",
approval,
- })
+ }))
expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain("m_channel")
expect(canonicalMessage("m_channel")?.approval).toEqual(approval)
@@ -1095,12 +1124,12 @@ describe("useCommunityWs — message.updated", () => {
botProfile: { ...profile, id: "bot_1", name: "Bot" },
}
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:message.updated",
channelId: "ch_parent",
messageId: "m_parent",
approval,
- })
+ }))
expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain("m_parent")
expect(canonicalMessage("m_parent")?.approval).toEqual(approval)
@@ -1116,7 +1145,7 @@ describe("useCommunityWs — pin.add", () => {
channelId: "ch_1",
messageId: "m_1",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const pinsCalls = spy.mock.calls.filter((c) =>
JSON.stringify(c[0]?.queryKey ?? []).includes(`"pins"`) ||
// pins() nests under channel + channelId + pins
@@ -1149,10 +1178,20 @@ describe("useCommunityWs — DM message.create", () => {
const fetchAttention = vi.spyOn(capturedQueryClient, "query")
// A DM is a channel now — its message arrives as `message.create` keyed by
// the DM's channel id (which the subscription tracks in `dmConversationId`).
- const event: CommunityMessageCreate = {
+ const event: CommunityMessageCreate = { profiles: messageProfilesFixture([messageResourceFixture({ authorAvatarVersion: 0, channelId: "dm_1", ...{
+ id: "dm_m_1",
+ seq: 1,
+ authorId: "u_a",
+ authorName: "a",
+ authorAvatarVersion: 0,
+ content: "hi",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ } })]),
type: "community:message.create",
channelId: "dm_1",
- message: {
+ message: messageResourceFixture({ authorAvatarVersion: 0, channelId: "dm_1", ...{
id: "dm_m_1",
seq: 1,
authorId: "u_a",
@@ -1162,13 +1201,13 @@ describe("useCommunityWs — DM message.create", () => {
type: "chat",
seq: 1,
createdAt: "2026-07-03T00:00:00.000Z",
- },
+ } }),
}
- capturedOnMessage!(event)
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture(event))
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:unread.bump", userId: "u_me", channelId: event.channelId,
isMention: false,
- })
+ }))
const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string; seq?: number }[] }[] }>(
communityKeys.dmMessages("dm_1"),
)
@@ -1195,10 +1234,19 @@ describe("useCommunityWs — DM message.create", () => {
getCapturedRuntime().ws.actions.markSeenMessage("dm_replay")
await mountHook()
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({ profiles: messageProfilesFixture([messageResourceFixture({ authorAvatarVersion: 0, channelId: "dm_1", ...{
+ id: "dm_replay",
+ seq: 12,
+ authorId: "u_a",
+ authorName: "a",
+ authorAvatarVersion: 0,
+ content: "replay",
+ type: "chat",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ } })]),
type: "community:message.create",
channelId: "dm_1",
- message: {
+ message: messageResourceFixture({ authorAvatarVersion: 0, channelId: "dm_1", ...{
id: "dm_replay",
seq: 12,
authorId: "u_a",
@@ -1207,8 +1255,8 @@ describe("useCommunityWs — DM message.create", () => {
content: "replay",
type: "chat",
createdAt: "2026-07-03T00:00:00.000Z",
- },
- })
+ } }),
+ }))
expect(getMessageStreamState(capturedQueryClient, { kind: "dm", id: "dm_1" }).liveIds.includes("dm_replay")).toBe(true)
})
@@ -1223,7 +1271,7 @@ describe("canonical message refresh ownership", () => {
await act(async () => {
for (let seq = 1; seq <= 502; seq++) {
const event = messageCreate(scope.id, `tail_${seq}`)
- capturedOnMessage!({ ...event, message: { ...event.message, seq } })
+ capturedOnMessage!(currentCommunityEventFixture({ ...event, message: { ...event.message, seq } }))
}
})
const live = getMessageStreamState(capturedQueryClient, scope).liveIds
@@ -1240,26 +1288,27 @@ describe("canonical message refresh ownership", () => {
await mountHook()
const event = messageCreate(scope.id)
seedCanonicalMessages(scope.id, [{ ...event.message,
- attachments: [{ name: "settled.txt", url: "/media/settled", sizeBytes: 1024 }],
+ attachments: [{ id: "settled", name: "settled.txt", url: "/media/settled", thumbnailUrl: null, contentType: "text/plain", sizeBytes: 1024, width: null, height: null }],
embeds: [{ title: "Prior" }],
}])
- await act(async () => { capturedOnMessage!({ ...event, message: { ...event.message, attachments: [], embeds: [] } }) })
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({ ...event, message: { ...event.message, attachments: [], embeds: [] } })) })
expect(getCommunityDbRegistry(capturedQueryClient)!.collections.messages.get(event.message.id)).toMatchObject({ attachments: [], embeds: [] })
expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain(event.message.id)
expect(canonicalMessage(event.message.id)).toMatchObject({ attachments: [], embeds: [] })
})
- it("preserves canonical attachments when a duplicate WS row omits them", async () => {
+ it("rejects a duplicate WS row missing required attachments without changing canonical bytes", async () => {
const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
getCapturedRuntime().ui.actions.setCurrentServerId(scope.serverId)
getCapturedRuntime().ui.actions.subscribe({ channelId: scope.id })
await mountHook()
- const attachments = [{ name: "settled.txt", url: "/media/settled", sizeBytes: 1024 }]
+ const attachments = [{ id: "settled", name: "settled.txt", url: "/media/settled", thumbnailUrl: null, contentType: "text/plain", sizeBytes: 1024, width: null, height: null }]
const event = messageCreate(scope.id)
seedCanonicalMessages(scope.id, [{ ...event.message, attachments }])
- await act(async () => { capturedOnMessage!(event) })
+ const { attachments: _attachments, ...incomplete } = event.message
+ await act(async () => { capturedOnMessage!({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION, message: incomplete }) })
expect(getCommunityDbRegistry(capturedQueryClient)!.collections.messages.get(event.message.id)?.attachments).toEqual(attachments)
- expect(getMessageStreamState(capturedQueryClient, scope).liveIds).toContain(event.message.id)
- expect(canonicalMessage(event.message.id)?.attachments).toEqual([{ ...attachments[0], kind: "file", size: "1.0 KB" }])
+ expect(getMessageStreamState(capturedQueryClient, scope).liveIds).not.toContain(event.message.id)
+ expect(canonicalMessage(event.message.id)?.attachments).toEqual([{ name: "settled.txt", url: "/media/settled", contentType: "text/plain", sizeBytes: 1024, kind: "file", size: "1.0 KB" }])
})
})
@@ -1276,19 +1325,26 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =
pageParams: [null],
})
- const event: CommunityMessageCreate = {
+ const event: CommunityMessageCreate = { profiles: messageProfilesFixture([messageResourceFixture({ authorAvatarVersion: 0, channelId: "ch_focused", ...{
+ id: "m_1",
+ authorId: "u_someone_else",
+ authorName: "them",
+ content: "hi",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ } })]),
type: "community:message.create",
channelId: "ch_focused",
- message: {
+ message: messageResourceFixture({ authorAvatarVersion: 0, channelId: "ch_focused", ...{
id: "m_1",
authorId: "u_someone_else",
authorName: "them",
content: "hi",
seq: 1,
createdAt: "2026-07-03T00:00:00.000Z",
- },
+ } }),
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(markReadMutate).not.toHaveBeenCalled()
})
@@ -1300,19 +1356,26 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =
resetHookMemoization()
await mountHook({ viewerUserId: "u_me" })
- const event: CommunityMessageCreate = {
+ const event: CommunityMessageCreate = { profiles: messageProfilesFixture([messageResourceFixture({ authorAvatarVersion: 0, channelId: "ch_focused", ...{
+ id: "m_1",
+ authorId: "u_me",
+ authorName: "me",
+ content: "hi",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ } })]),
type: "community:message.create",
channelId: "ch_focused",
- message: {
+ message: messageResourceFixture({ authorAvatarVersion: 0, channelId: "ch_focused", ...{
id: "m_1",
authorId: "u_me",
authorName: "me",
content: "hi",
seq: 1,
createdAt: "2026-07-03T00:00:00.000Z",
- },
+ } }),
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(markReadMutate).not.toHaveBeenCalled()
})
@@ -1324,10 +1387,18 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =
resetHookMemoization()
await mountHook({ viewerUserId: "u_me" })
- const event: CommunityMessageCreate = {
+ const event: CommunityMessageCreate = { profiles: messageProfilesFixture([messageResourceFixture({ authorAvatarVersion: 0, channelId: "dm_1", ...{
+ id: "dm_m_1",
+ authorId: "u_a",
+ authorName: "a",
+ content: "hi",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ } })]),
type: "community:message.create",
channelId: "dm_1",
- message: {
+ message: messageResourceFixture({ authorAvatarVersion: 0, channelId: "dm_1", ...{
id: "dm_m_1",
authorId: "u_a",
authorName: "a",
@@ -1335,9 +1406,9 @@ describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () =
type: "chat",
seq: 1,
createdAt: "2026-07-03T00:00:00.000Z",
- },
+ } }),
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(markReadMutate).not.toHaveBeenCalled()
})
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 522d0c319..78d9e4bec 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -172,7 +172,7 @@ export function handleMessageUpdated(
event: CommunityMessageUpdated,
context: CommunityWsHandlerContext,
) {
- writeCommunityProfilePatches(approvalProfilePatches(event.approval), getCommunityDbRegistry(context.queryClient), { event: true })
+ writeCommunityProfilePatches(approvalProfilePatches(event.approval), getCommunityDbRegistry(context.queryClient), { event: true, resourceSeed: true })
if (event.botCreation?.status === "approved") invalidateBotSurfaces(context.queryClient)
// 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.dom.test.ts b/src/web/src/hooks/community/community-ws/presence-machine-events.dom.test.ts
index f4a2b2ee1..23416235b 100644
--- a/src/web/src/hooks/community/community-ws/presence-machine-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/presence-machine-events.dom.test.ts
@@ -1,3 +1,4 @@
+import { currentCommunityEventFixture, dmListRowFixture } from "@/test/community-resource-fixtures"
import { act } from "react"
import { getCapturedRuntime } from "./test-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -36,14 +37,14 @@ describe("useCommunityWs — presence", () => {
userId: "u_pres",
online: true,
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const { useCommunityWsStore } = await import("@/stores/community/ws")
expect(getCapturedRuntime().ws.get().presenceByUserId.get("u_pres")).toBe("online")
expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toEqual({
online: ["friend_existing"],
})
const patchedSnapshot = capturedQueryClient.getQueryData(communityKeys.friendsPresence())
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toBe(patchedSnapshot)
expect(spy).not.toHaveBeenCalled()
})
@@ -63,7 +64,7 @@ describe("useCommunityWs — presence", () => {
userId: "friend_non_member",
online: false,
}
- capturedOnMessage!(offline)
+ capturedOnMessage!(currentCommunityEventFixture(offline))
expect(getCapturedRuntime().ws.get().presenceByUserId.get("friend_non_member"))
.toBe("offline")
expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence()))
@@ -72,11 +73,11 @@ describe("useCommunityWs — presence", () => {
it("does not create a friends presence cache from a live delta alone", async () => {
await mountHook()
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:presence.update",
userId: "u_pres",
online: true,
- } satisfies CommunityPresenceUpdate)
+ } satisfies CommunityPresenceUpdate))
expect(capturedQueryClient.getQueryData(communityKeys.friendsPresence())).toBeUndefined()
})
@@ -92,7 +93,7 @@ describe("useCommunityWs — status.update", () => {
statusEmoji: "🎧",
statusText: "Vibing",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const { useCommunityWsStore } = await import("@/stores/community/ws")
expect(getCapturedRuntime().ws.get()).not.toHaveProperty("profilesByUserId")
expect(getCapturedRuntime().ws.get().presenceByUserId.has("u_status")).toBe(false)
@@ -114,7 +115,7 @@ describe("useCommunityWs — bot audit events", () => {
createdAt: "2026-09-01T15:00:00.000Z",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const { useCommunityWsStore } = await import("@/stores/community/ws")
expect(capturedQueryClient.getQueryData<{ pages: { events: unknown[] }[] }>(communityKeys.botAuditLog("bot_stop"))?.pages[0].events).toEqual([{
@@ -129,7 +130,7 @@ describe("useCommunityWs — bot audit events", () => {
})
describe("useCommunityWs — machines", () => {
- const dispatchMachine = async (event: unknown) => { await act(async () => { await capturedOnMessage!(event) }) }
+ const dispatchMachine = async (event: unknown) => { await act(async () => { await capturedOnMessage!(currentCommunityEventFixture(event)) }) }
const machine = (id: string, status: "online" | "offline" = "offline"): CommunityMachineSummary => ({
id, hostname: id, displayName: id, platform: "darwin", arch: "arm64",
osRelease: "24", daemonVersion: "0.1", lastSeenAt: null, status,
diff --git a/src/web/src/hooks/community/community-ws/read-state-events.test.ts b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
index 360c22f8c..0255fd5b3 100644
--- a/src/web/src/hooks/community/community-ws/read-state-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
@@ -1,3 +1,4 @@
+import { resourceBundleFixture } from "@/test/community-resource-fixtures"
import { afterEach, beforeEach, expect, it, vi } from "vitest"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { currentConversationReadState } from "@/lib/community/conversation-entry"
@@ -11,7 +12,7 @@ import { disposeAccountReadStateReconciliation } from "./read-state-reconciliati
const apiFetch = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
-const emptyAttention = { scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+const emptyAttention = { resources: resourceBundleFixture({ viewerId: "u1" }), scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
function context(): CommunityWsDispatchContext { return { deliveryMode: "single", queryClient: owner.client, communityStore: owner.runtime.ui, wsStore: owner.runtime.ws, sub: {}, viewerUserIdRef: { current: "u1" }, matchesFocus: () => false } }
beforeEach(async () => { owner = await createCommunityQueryOwner("u1"); apiFetch.mockReset() })
afterEach(async () => { disposeAccountReadStateReconciliation(owner.client); await owner.registry.cleanup(); owner.client.clear() })
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 b9cca7b1f..3dc388122 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
@@ -1,3 +1,4 @@
+import { attentionSnapshotScenarioFixture, resourceBundleFixture } from "@/test/community-resource-fixtures"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
@@ -10,7 +11,7 @@ vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(
let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
const row = (seq: number) => ({ channelId: "c1", lastReadMessageId: `m${seq}`, lastReadAt: `2026-10-27T00:00:0${seq}.000Z`, lastReadSeq: seq })
const snapshot = (revision: number, seq = revision) => ({ revision, readStates: [row(seq)] })
-const attention = { scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+const attention = { resources: resourceBundleFixture(), scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done }); return { promise, resolve } }
beforeEach(async () => { apiFetch.mockReset(); owner = await createCommunityQueryOwner(); apiFetch.mockImplementation(async (path: string) => path.endsWith("/attention") ? attention : snapshot(1)) })
afterEach(async () => { await owner.client.cancelQueries(); await owner.registry.cleanup(); owner.client.clear(); vi.useRealTimers() })
@@ -35,11 +36,11 @@ describe("native account read-state reconciliation", () => {
it("rechecks an early attention count only after a held read-state advances its confirmed revision", async () => {
const gate = deferred<ReturnType<typeof snapshot>>()
let attentionReads = 0
- apiFetch.mockImplementation(async (path: string) => path.endsWith("/read-state") ? gate.promise : {
+ apiFetch.mockImplementation(async (path: string) => path.endsWith("/read-state") ? gate.promise : attentionSnapshotScenarioFixture({
...attention,
scopes: [{ scopeId: "c1", channelId: "c1", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 5, unreadCount: ++attentionReads === 1 ? 5 : 3, attentionCount: 0, lastAttentionSeq: null }],
included: { ...attention.included, dms: [{ id: "c1", userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0, lastMessageAt: "2026-10-27T00:00:05.000Z", lastUnreadSeq: 5 }], profiles: [{ userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0 }] },
- })
+ }))
const outcome = reconcileAccountReadState(owner.client).then(() => null, error => error)
try {
await vi.waitFor(() => expect(owner.registry.collections.attentionScopes.get("c1")?.unreadCount).toBe(5))
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
index 7374f9d02..1a125232a 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
@@ -1,3 +1,4 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryObserver } from "@tanstack/react-query"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
@@ -17,11 +18,11 @@ function row(seq: number) {
return { ...fixture().messages[0], id: `m${seq}`, seq,
createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, seq)).toISOString(),
authorName: "Peer", authorAvatar: "", authorAvatarVersion: 0,
- content: `Body ${seq}`, resourceComplete: true as const, embeds: [], reactions: [],
+ content: `Body ${seq}`, embeds: [], reactions: [],
}
}
function page(messages: ReturnType<typeof row>[], latestSeq: number): MessagesPage {
- return { messages, latestSeq, hasMoreOlder: true, hasMoreNewer: false, olderCursor: "older" }
+ return messageReadPageFixture({ messages, latestSeq, hasMoreOlder: true, hasMoreNewer: false, olderCursor: "older" })
}
function suffix(cursor: number) { return `since=${encodeURIComponent(`${row(cursor).createdAt}|m${cursor}`)}` }
@@ -70,10 +71,10 @@ describe("complete canonical coverage at the existing repair owner", () => {
it.each(["exact-ID", "latest"] as const)("reuses a real %s prefetch without giving prefetch a window writer", async hint => {
const h = await setup()
- load.mockResolvedValueOnce(hint === "exact-ID" ? row(101) : page([row(101)], 101))
+ load.mockResolvedValueOnce(hint === "exact-ID" ? { message: row(101), profiles: fixture().profiles } : page([row(101)], 101))
if (hint === "exact-ID") await prefetchCommunityMessage(h.client, "m101", { channelId: "c1", serverId: "s1" })
else await prefetchCommunityLatestMessage(h.client, "c1")
- expect(h.registry.collections.messages.get("m101")?.resourceComplete).toBe(true)
+ expect(h.registry.collections.messages.get("m101")).toMatchObject(row(101))
expect(h.ids()).toEqual(["m98", "m99", "m100"])
load.mockReset().mockResolvedValue(page([{ ...row(100), content: "corrected" }], 101))
try {
@@ -109,7 +110,7 @@ describe("complete canonical coverage at the existing repair owner", () => {
it("retains current-window correction of a deleted reply target even when creations are cached", async () => {
const h = await setup()
- ingestMessages(h.registry, "c1", [{ ...row(100), replyTo: { id: "gone", authorName: "Peer", text: "old reply" } }, row(101)])
+ ingestMessages(h.registry, "c1", [{ ...row(100), replyTo: { id: "gone", authorId: "peer", authorName: "Peer", text: "old reply" } }, row(101)])
load.mockResolvedValueOnce(page([{ ...row(100), replyTo: { id: "gone", authorName: "Deleted user", text: "", deleted: true } }], 101))
try {
await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
@@ -193,7 +194,7 @@ describe("complete canonical coverage at the existing repair owner", () => {
it.each(["missing", "partial", "other-channel", "duplicate-seq", "cursor-order", "invalid-time", "cursor-separator"] as const)("does not let %s evidence or a maximum seq hide a missing resource", async kind => {
const h = await setup()
ingestMessages(h.registry, "c1", [row(103)])
- if (kind === "partial") ingestMessages(h.registry, "c1", [{ id: "m101", seq: 101, createdAt: row(101).createdAt, content: "partial" }])
+ if (kind === "partial") expect(() => ingestMessages(h.registry, "c1", [{ id: "m101", seq: 101, createdAt: row(101).createdAt, content: "partial" }])).toThrow()
if (kind === "other-channel") ingestMessages(h.registry, "c2", [{ ...row(101), channelId: "c2" }])
if (kind === "duplicate-seq") ingestMessages(h.registry, "c1", [row(101), { ...row(101), id: "other101" }])
if (kind === "cursor-order") ingestMessages(h.registry, "c1", [{ ...row(101), createdAt: row(99).createdAt }])
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 8579520f0..ae35be056 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
@@ -1,3 +1,5 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
+import { dmListRowFixture, messageSeedFixture, serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { COMMUNITY_CONVERSATION_ANCHOR_MISSING } from "@alook/shared"
import { ingestDms, ingestMessages, ingestServerDetail, retireCommunityChannelReading } from "@/lib/community-db/sync"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
@@ -152,7 +154,7 @@ describe("focused message reconnect catch-up", () => {
controller.abort()
stopParent()
expect(signal?.aborted).toBe(false)
- release({ messages: [{ id: "m_2", seq: 2, content: "owned by window" }], latestSeq: 2 })
+ release(messageReadPageFixture({ messages: messageSeedFixture("handoff", [{ id: "m_2", seq: 2, content: "owned by window" }]), latestSeq: 2 }))
await repair
expect(registry.collections.messages.get("m_2")?.content).toBe("owned by window")
stopWindow()
@@ -163,7 +165,7 @@ describe("focused message reconnect catch-up", () => {
const key = communityKeys.channelMessages("retry")
const { unsubscribe } = seedActiveQuery(client, key)
apiFetchMock.mockRejectedValueOnce(failure === "deadline" ? new ConversationReadTimeoutError() : new ApiError("temporary", failure))
- .mockResolvedValueOnce({ messages: [{ id: "m_2", seq: 2, content: "refreshed" }], latestSeq: 2 })
+ .mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("retry", [{ id: "m_2", seq: 2, content: "refreshed" }]), latestSeq: 2 }))
await client.query({ ...messageReconcileOptions(client, { kind: "channel", scopeId: "retry" }, key), retryDelay: 0 })
expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(registry.collections.messages.get("m_2")?.content).toBe("refreshed")
@@ -181,7 +183,7 @@ describe("focused message reconnect catch-up", () => {
expect(client.getQueryData(key)).toBe(before)
const repair = client.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })!
expect(isFailedMessageRepair(client, repair)).toBe(true)
- apiFetchMock.mockResolvedValue({ messages: [{ id: "m_2", seq: 2, content: "recovered" }], latestSeq: 2 })
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({ messages: messageSeedFixture("exhausted", [{ id: "m_2", seq: 2, content: "recovered" }]), latestSeq: 2 }))
await retryFailedMessageRepairs(client)
expect(apiFetchMock).toHaveBeenCalledTimes(4)
expect(registry.collections.messages.get("m_2")?.content).toBe("recovered")
@@ -193,9 +195,9 @@ describe("focused message reconnect catch-up", () => {
const { client, registry } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("scroll-newer")
const { unsubscribe } = seedActiveQuery(client, key)
- apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_2", seq: 2 }], latestSeq: 100 })
- .mockResolvedValueOnce({ messages: [{ id: "m_3", seq: 3, createdAt: "2026-08-15T00:00:03.000Z" }], latestSeq: 100, hasMoreNewer: true, newerCursor: "next-page" })
- .mockResolvedValueOnce({ messages: [{ id: "m_4", seq: 4, content: "from scroll" }], latestSeq: 100, hasMoreNewer: true, newerCursor: "later-page" })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("scroll-newer", [{ id: "m_2", seq: 2 }]), latestSeq: 100 }))
+ .mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("scroll-newer", [{ id: "m_3", seq: 3, createdAt: "2026-08-15T00:00:03.000Z" }]), latestSeq: 100, hasMoreNewer: true, newerCursor: "next-page" }))
+ .mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("scroll-newer", [{ id: "m_4", seq: 4, content: "from scroll" }]), latestSeq: 100, hasMoreNewer: true, newerCursor: "later-page" }))
await reconcileFocusedMessageQueries(client, "channel", "scroll-newer")
expect(apiFetchMock).toHaveBeenCalledTimes(2)
const observer = new InfiniteQueryObserver(client, {
@@ -260,7 +262,7 @@ describe("focused message reconnect catch-up", () => {
await vi.advanceTimersByTimeAsync(10_000)
expect(apiFetchMock).toHaveBeenCalledOnce()
const next = reason === "window" ? seedActiveQuery(client, key) : first
- apiFetchMock.mockResolvedValue({ messages: [], latestSeq: 2 })
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({ messages: messageSeedFixture("cancelled", []), latestSeq: 2 }))
await reconcileFocusedMessageQueries(client, "channel", "cancelled")
expect(apiFetchMock).toHaveBeenCalledTimes(2)
next.unsubscribe()
@@ -285,7 +287,7 @@ describe("focused message reconnect catch-up", () => {
queryClient.setQueryData(key, { pages: [{ messages: [{ id: "new-account-message" }] }], pageParams: [] })
}
const expected = queryClient.getQueryData(key)
- release({ messages: [{ id: "old-reconnect-message" }], latestSeq: 2, hasMore: false })
+ release(messageReadPageFixture({ messages: messageSeedFixture("child", [{ id: "old-reconnect-message" }]), latestSeq: 2, hasMore: false }))
await result
expect(queryClient.getQueryData(key)).toBe(expected)
unsubscribe()
@@ -306,12 +308,12 @@ describe("focused message reconnect catch-up", () => {
expect(client.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })?.state.fetchStatus).toBe("fetching")
expect(cancel).toHaveBeenCalledOnce()
expect(apiFetchMock).toHaveBeenCalledOnce()
- apiFetchMock.mockResolvedValueOnce({ messages: [3, 4, 5].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` })), latestSeq: 5, hasMoreNewer: false })
- release({ messages: [], latestSeq: 2, hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("shared", [3, 4, 5].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` }))), latestSeq: 5, hasMoreNewer: false }))
+ release(messageReadPageFixture({ messages: messageSeedFixture("shared", []), latestSeq: 2, hasMore: false }))
await Promise.all([first, reconnect, gap])
expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(key)?.pages.flatMap((page) => page.messages.map((message) => message.id))).toEqual(["m_2", "m_3", "m_4", "m_5", "m_1"])
- apiFetchMock.mockResolvedValueOnce({ messages: [], latestSeq: 5, hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("shared", []), latestSeq: 5, hasMore: false }))
await reconcileFocusedMessageQueries(client, kind, "shared")
expect(apiFetchMock).toHaveBeenCalledTimes(3)
unsubscribe()
@@ -339,7 +341,7 @@ describe("focused message reconnect catch-up", () => {
expect(client.getQueryData(key)).toBe(before)
const repair = client.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })!
expect(isFailedMessageRepair(client, repair)).toBe(true)
- apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_2", seq: 2, content: "retry recovered" }], latestSeq: 2 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("shared-failure", [{ id: "m_2", seq: 2, content: "retry recovered" }]), latestSeq: 2 }))
await retryFailedMessageRepairs(client)
expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(registry.collections.messages.get("m_2")?.content).toBe("retry recovered")
@@ -354,17 +356,17 @@ describe("focused message reconnect catch-up", () => {
const subscriptions = [seedActiveQuery(client, key), seedActiveQuery(client, taggedKey)]
let releaseTagged!: (page: unknown) => void
const tagged = new Promise((resolve) => { releaseTagged = resolve })
- const fresh = { messages: [3, 4, 5].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` })), latestSeq: 5, hasMoreNewer: false }
+ const fresh = messageReadPageFixture({ messages: messageSeedFixture("variants", [3, 4, 5].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` }))), latestSeq: 5, hasMoreNewer: false })
apiFetchMock.mockImplementation((url: string) => {
if (url.includes("since=")) return Promise.resolve(fresh)
if (url.includes("tag=")) return tagged
- return Promise.resolve({ messages: [], latestSeq: apiFetchMock.mock.calls.length > 2 ? 5 : 2, hasMore: false })
+ return Promise.resolve(messageReadPageFixture({ messages: messageSeedFixture("variants", []), latestSeq: apiFetchMock.mock.calls.length > 2 ? 5 : 2, hasMore: false }))
})
const first = reconcileFocusedMessageQueries(client, "channel", "variants")
await vi.waitFor(() => expect(publishCommunityMessagesMock).toHaveBeenCalledOnce())
const gap = scheduleFocusedMessageGapRepair(client, { kind: "channel", scopeId: "variants" }, 5)
await vi.waitFor(() => expect(publishCommunityMessagesMock).toHaveBeenCalledTimes(2))
- releaseTagged({ messages: [], latestSeq: 2, hasMore: false })
+ releaseTagged(messageReadPageFixture({ messages: messageSeedFixture("variants", []), latestSeq: 2, hasMore: false }))
await Promise.all([first, gap])
for (const queryKey of [key, taggedKey]) {
expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(queryKey)?.pages.flatMap((page) => page.messages.map((message) => message.id))).toEqual(["m_2", "m_3", "m_4", "m_5", "m_1"])
@@ -402,8 +404,8 @@ describe("focused message reconnect catch-up", () => {
const shared = reconcileFocusedMessageQueries(client, "channel", "changed")
expect(scheduleFocusedMessageGapRepair(client, { kind: "channel", scopeId: "changed" }, 5)).not.toBeNull()
expect(apiFetchMock).toHaveBeenCalledTimes(2)
- apiFetchMock.mockResolvedValueOnce({ messages: [], latestSeq: 5, hasMoreNewer: false })
- releaseNew({ messages: [{ id: "m_2", content: "current", seq: 2, createdAt: "2026-08-15T00:00:02.000Z" }], latestSeq: 2, hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture("changed", []), latestSeq: 5, hasMoreNewer: false }))
+ releaseNew(messageReadPageFixture({ messages: messageSeedFixture("changed", [{ id: "m_2", content: "current", seq: 2, createdAt: "2026-08-15T00:00:02.000Z" }]), latestSeq: 2, hasMore: false }))
await Promise.all([second, shared])
expect(publishCommunityMessagesMock).toHaveBeenCalledOnce()
expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(key)?.pages[0].messages[0].id).toBe("m_2")
@@ -442,26 +444,26 @@ describe("focused message reconnect catch-up", () => {
const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
const setQueryDataSpy = vi.spyOn(queryClient, "setQueryData")
apiFetchMock
- .mockResolvedValueOnce({
- messages: [{
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_gap", [{
id: "m_2",
type: "chat",
seq: 2,
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
latestSeq: 6,
hasMore: false,
- })
- .mockResolvedValueOnce({
- messages: [3, 4, 5, 6].map((seq) => ({
+ }))
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_gap", [3, 4, 5, 6].map((seq) => ({
id: `m_${seq}`,
type: "chat",
seq,
createdAt: `2026-08-15T00:00:0${seq}.000Z`,
- })),
+ }))),
latestSeq: 6,
hasMoreNewer: false,
- })
+ }))
const first = scheduleFocusedMessageGapRepair(
queryClient,
@@ -479,6 +481,7 @@ describe("focused message reconnect catch-up", () => {
expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(captureCommunityLiveSnapshotTokenMock).toHaveBeenCalledWith(queryClient, "ch_gap")
expect(publishCommunityMessagesMock).toHaveBeenCalledWith(queryClient, {
+ profiles: expect.arrayContaining([expect.objectContaining({ id: "viewer", discriminator: "0042", avatar: null, avatarVersion: 0 })]),
channelId: "ch_gap",
messages: expect.arrayContaining([
expect.objectContaining({ id: "m_2" }),
@@ -502,11 +505,11 @@ describe("focused message reconnect catch-up", () => {
...current,
pages: current.pages.map((page: any) => ({ ...page, latestSeq: 99 })),
}))
- apiFetchMock.mockResolvedValue({
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({
messages: [],
latestSeq: 2,
hasMore: false,
- })
+ }))
const repair = scheduleFocusedMessageGapRepair(
queryClient,
@@ -547,17 +550,17 @@ describe("focused message reconnect catch-up", () => {
"m_1",
])
- resolveRefresh({
- messages: [{
+ resolveRefresh(messageReadPageFixture({
+ messages: messageSeedFixture("ch_visible", [{
id: "m_2",
type: "chat",
seq: 2,
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 2,
- })
+ }))
await reconciliation
unsubscribe()
})
@@ -576,9 +579,9 @@ describe("focused message reconnect catch-up", () => {
it.each([403, 404])("retires a denied DM through its real scope and keeps the DM shell for status %s", async (status) => {
const { client, registry, runtime } = await createCommunityQueryOwner("a")
- ingestDms(registry, { conversations: ["denied", "sibling"].map((id) => ({ id, userId: id + "-peer", name: id, discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "old" })) })
- ingestMessages(registry, "denied", [{ id: "private", type: "chat", content: "remove" }])
- ingestMessages(registry, "sibling", [{ id: "sibling-message", type: "chat", content: "keep" }])
+ ingestDms(registry, { conversations: ["denied", "sibling"].map((id) => dmListRowFixture({ id, userId: id + "-peer", name: id, discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "old" }, registry.accountId!)) })
+ ingestMessages(registry, "denied", messageSeedFixture("denied", [{ id: "private", type: "chat", content: "remove" }]))
+ ingestMessages(registry, "sibling", messageSeedFixture("sibling", [{ id: "sibling-message", type: "chat", content: "keep" }]))
const scope = { kind: "dm" as const, id: "denied" }
runtime.messageStream.actions.accept(scope, { nonce: "pending", tempId: "temp", message: { type: "chat", content: "pending", authorId: "a" }, localUploads: [] })
const key = communityKeys.dmMessages(scope.id), sibling = communityKeys.dmMessages("sibling")
@@ -598,10 +601,10 @@ describe("focused message reconnect catch-up", () => {
it("retires a denied channel using its captured server and leaves the sibling readable", async () => {
const { client, registry, runtime } = await createCommunityQueryOwner("a")
- ingestServerDetail(registry, { id: "server", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "a",
- categories: [{ id: "category", name: "Chats", channels: ["denied-channel", "sibling-channel"].map((id) => ({ id, name: id, active: false, unread: false })) }] })
- ingestMessages(registry, "denied-channel", [{ id: "private", type: "chat", content: "remove" }])
- ingestMessages(registry, "sibling-channel", [{ id: "public", type: "chat", content: "keep" }])
+ ingestServerDetail(registry, serverDirectoryFixture({ id: "server", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "a",
+ categories: [{ id: "category", name: "Chats", channels: ["denied-channel", "sibling-channel"].map((id) => ({ id, name: id, active: false, unread: false })) }] }))
+ ingestMessages(registry, "denied-channel", messageSeedFixture("denied-channel", [{ id: "private", type: "chat", content: "remove" }]))
+ ingestMessages(registry, "sibling-channel", messageSeedFixture("sibling-channel", [{ id: "public", type: "chat", content: "keep" }]))
const key = communityKeys.channelMessages("denied-channel"), sibling = communityKeys.channelMessages("sibling-channel")
const subscriptions = [seedActiveQuery(client, key), seedActiveQuery(client, sibling)]
apiFetchMock.mockRejectedValueOnce(new ApiError("forbidden", 403))
@@ -621,7 +624,7 @@ describe("focused message reconnect catch-up", () => {
const { client, registry, runtime } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("late-denial")
const subscriptions = [seedActiveQuery(client, key)]
- ingestMessages(registry, "late-denial", [{ id: "keep", type: "chat", content: "current" }])
+ ingestMessages(registry, "late-denial", messageSeedFixture("late-denial", [{ id: "keep", type: "chat", content: "current" }]))
let reject!: (error: Error) => void
apiFetchMock.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail }))
const repair = reconcileFocusedMessageQueries(client, "channel", "late-denial", "server")
@@ -642,7 +645,7 @@ describe("focused message reconnect catch-up", () => {
const scope = { kind: "channel" as const, id: "anchor-scope", serverId: "server" }
const key = communityKeys.channelMessagesWindow(scope.id, { mode: "anchor", anchor: "gone" })
const { unsubscribe } = seedActiveQuery(client, key)
- ingestMessages(registry, scope.id, [{ id: "readable", type: "chat", content: "keep" }])
+ ingestMessages(registry, scope.id, messageSeedFixture(scope.id, [{ id: "readable", type: "chat", content: "keep" }]))
runtime.messageStream.actions.accept(scope, { nonce: "pending", tempId: "temp", message: { type: "chat", content: "pending", authorId: "a" }, localUploads: [] })
const missing = new ApiError("anchor not found", 404, [COMMUNITY_CONVERSATION_ANCHOR_MISSING])
apiFetchMock.mockRejectedValueOnce(missing)
@@ -657,7 +660,7 @@ describe("focused message reconnect catch-up", () => {
it("does not turn a late denial after explicit DM deletion into read-denied retirement or restore its shell", async () => {
const { client, registry } = await createCommunityQueryOwner("a")
- ingestDms(registry, { conversations: [{ id: "deleted", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "" }] })
+ ingestDms(registry, { conversations: [dmListRowFixture({ id: "deleted", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "" }, registry.accountId!)] })
const key = communityKeys.dmMessages("deleted"), { unsubscribe } = seedActiveQuery(client, key)
let reject!: (error: Error) => void
apiFetchMock.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail }))
@@ -711,12 +714,12 @@ describe("focused message reconnect catch-up", () => {
}) => {
if (pageParam.mode === "newest") {
return {
- messages: [{
+ messages: messageSeedFixture("ch_race", [{
id: "m_2",
type: "chat",
seq: 2,
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 2,
@@ -726,12 +729,12 @@ describe("focused message reconnect catch-up", () => {
olderSignals.push(signal)
if (olderCallCount === 1) return staleOlder
return {
- messages: [{
+ messages: messageSeedFixture("ch_race", [{
id: "m_1",
type: "chat",
seq: 1,
createdAt: "2026-08-15T00:00:01.000Z",
- }],
+ }]),
hasMore: false,
latestSeq: 3,
}
@@ -753,8 +756,8 @@ describe("focused message reconnect catch-up", () => {
expect(olderCallCount).toBe(1)
})
apiFetchMock
- .mockResolvedValueOnce({
- messages: [{
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_race", [{
id: "m_2",
type: "chat",
seq: 2,
@@ -764,21 +767,21 @@ describe("focused message reconnect catch-up", () => {
type: "chat",
seq: 3,
createdAt: "2026-08-15T00:00:03.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 3,
- })
- .mockResolvedValueOnce({
- messages: [{
+ }))
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_race", [{
id: "m_3",
type: "chat",
seq: 3,
createdAt: "2026-08-15T00:00:03.000Z",
- }],
+ }]),
hasMoreNewer: false,
latestSeq: 3,
- })
+ }))
const cancel = vi.spyOn(queryClient, "cancelQueries")
const foreground = reconcileFocusedMessageQueries(queryClient, "channel", "ch_race")
@@ -786,11 +789,11 @@ describe("focused message reconnect catch-up", () => {
expect(queryClient.getQueryCache().find({ queryKey: [...queryKey, "reconcile"], exact: true })?.state.fetchStatus).toBe("fetching")
await Promise.all([foreground, reconnect])
expect(cancel).toHaveBeenCalledOnce()
- resolveStaleOlder({
- messages: [{ id: "stale_m_1" }],
+ resolveStaleOlder(messageReadPageFixture({
+ messages: messageSeedFixture("ch_race", [{ id: "stale_m_1" }]),
hasMore: false,
latestSeq: 2,
- })
+ }))
await pendingOlder
expect(olderSignals[0]?.aborted).toBe(true)
@@ -809,8 +812,8 @@ describe("focused message reconnect catch-up", () => {
const { client: client } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("late-replay")
let olderCalls = 0
- const newest = { messages: [{ id: "m_2", seq: 2, createdAt: "2026-08-15T00:00:02.000Z" }], latestSeq: 2, hasMore: true, cursor: "older" }
- const older = { messages: [{ id: "m_1", seq: 1, createdAt: "2026-08-15T00:00:01.000Z" }], latestSeq: 2, hasMore: false }
+ const newest = messageReadPageFixture({ messages: messageSeedFixture("late-replay", [{ id: "m_2", seq: 2, createdAt: "2026-08-15T00:00:02.000Z" }]), latestSeq: 2, hasMore: true, cursor: "older" })
+ const older = messageReadPageFixture({ messages: messageSeedFixture("late-replay", [{ id: "m_1", seq: 1, createdAt: "2026-08-15T00:00:01.000Z" }]), latestSeq: 2, hasMore: false })
let releaseStale!: (value: typeof older) => void
let releaseReplay!: (value: typeof older) => void
const observer = new InfiniteQueryObserver(client, {
@@ -830,9 +833,9 @@ describe("focused message reconnect catch-up", () => {
await vi.waitFor(() => expect(observer.getCurrentResult().isSuccess).toBe(true))
const pagination = observer.fetchNextPage()
await vi.waitFor(() => expect(olderCalls).toBe(1))
- apiFetchMock.mockResolvedValueOnce(newest).mockResolvedValueOnce({
- messages: [3, 4, 5].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` })), latestSeq: 5, hasMoreNewer: false,
- })
+ apiFetchMock.mockResolvedValueOnce(newest).mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("late-replay", [3, 4, 5].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` }))), latestSeq: 5, hasMoreNewer: false,
+ }))
const cancel = vi.spyOn(client, "cancelQueries")
const foreground = reconcileFocusedMessageQueries(client, "channel", "late-replay")
await vi.waitFor(() => expect(olderCalls).toBe(2))
@@ -853,13 +856,13 @@ describe("focused message reconnect catch-up", () => {
const { client: client } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("idle-pagination")
let olderCalls = 0
- const newest = { messages: [{ id: "m_2", seq: 2, createdAt: "2026-08-15T00:00:02.000Z" }], latestSeq: 2, hasMore: true, cursor: "older-2" }
+ const newest = messageReadPageFixture({ messages: messageSeedFixture("idle-pagination", [{ id: "m_2", seq: 2, createdAt: "2026-08-15T00:00:02.000Z" }]), latestSeq: 2, hasMore: true, cursor: "older-2" })
const observer = new InfiniteQueryObserver(client, {
queryKey: key,
queryFn: async ({ pageParam }) => {
if (pageParam.mode === "newest") return newest
olderCalls += 1
- return { messages: [{ id: "m_1", seq: 1 }], latestSeq: 2, hasMore: true, cursor: "older-1" }
+ return { messages: messageSeedFixture("idle-pagination", [{ id: "m_1", seq: 1 }]), latestSeq: 2, hasMore: true, cursor: "older-1" }
},
initialPageParam: { mode: "newest", cursor: "" },
getNextPageParam: (last) => last.hasMore ? { mode: "older", cursor: last.cursor } : undefined,
@@ -884,16 +887,16 @@ describe("focused message reconnect catch-up", () => {
async (kind, queryKey, scopeId) => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const { queryFn, unsubscribe } = seedEmptyActiveQuery(queryClient, queryKey)
- apiFetchMock.mockResolvedValue({
- messages: [{
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({
+ messages: messageSeedFixture(scopeId, [{
id: "m_first",
type: "chat",
seq: 1,
createdAt: "2026-08-15T00:00:01.000Z",
- }],
+ }]),
hasMore: false,
latestSeq: 1,
- })
+ }))
await reconcileFocusedMessageQueries(queryClient, kind, scopeId)
@@ -921,12 +924,12 @@ describe("focused message reconnect catch-up", () => {
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
const gap = scheduleFocusedMessageGapRepair(client, { kind, scopeId }, 2)
expect(gap).not.toBeNull()
- apiFetchMock.mockResolvedValueOnce({
- messages: [1, 2].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` })),
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture(scopeId, [1, 2].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` }))),
latestSeq: 2,
hasMore: false,
- })
- release({ messages: [], latestSeq: 0, hasMore: false })
+ }))
+ release(messageReadPageFixture({ messages: messageSeedFixture(scopeId, []), latestSeq: 0, hasMore: false }))
await Promise.all([repair, gap])
expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([
@@ -944,13 +947,13 @@ describe("focused message reconnect catch-up", () => {
const scopeId = "bounded-empty"
const key = kind === "channel" ? communityKeys.channelMessages(scopeId) : communityKeys.dmMessages(scopeId)
const { queryFn, unsubscribe } = seedEmptyActiveQuery(client, key)
- apiFetchMock.mockResolvedValue({ messages: [], latestSeq: 0, hasMore: false })
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({ messages: messageSeedFixture(scopeId, []), latestSeq: 0, hasMore: false }))
await scheduleFocusedMessageGapRepair(client, { kind, scopeId }, 2)
expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(client.getQueryData<{ pages: Array<{ messages: unknown[] }> }>(key)?.pages[0].messages).toEqual([])
const repair = client.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })!
expect(isFailedMessageRepair(client, repair)).toBe(true)
- apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_later", seq: 2 }], latestSeq: 2, hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture(scopeId, [{ id: "m_later", seq: 2 }]), latestSeq: 2, hasMore: false }))
await reconcileFocusedMessageQueries(client, kind, scopeId)
expect(apiFetchMock).toHaveBeenCalledTimes(3)
expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(key)?.pages[0].messages.map((message) => message.id)).toEqual(["m_later"])
@@ -965,7 +968,7 @@ describe("focused message reconnect catch-up", () => {
const key = communityKeys.channelMessages(scopeId)
const subscriptions = [seedEmptyActiveQuery(client, key).unsubscribe]
let release!: (page: unknown) => void
- apiFetchMock.mockResolvedValueOnce({ messages: [], latestSeq: 0, hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: messageSeedFixture(scopeId, []), latestSeq: 0, hasMore: false }))
apiFetchMock.mockReturnValueOnce(new Promise((resolve) => { release = resolve }))
const gap = scheduleFocusedMessageGapRepair(client, { kind: "channel", scopeId }, 2)
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
@@ -976,7 +979,7 @@ describe("focused message reconnect catch-up", () => {
subscriptions.push(seedActiveQuery(client, key).unsubscribe)
}
const current = client.getQueryData(key)
- release({ messages: [{ id: "m_obsolete", seq: 2 }], latestSeq: 2, hasMore: false })
+ release(messageReadPageFixture({ messages: messageSeedFixture(scopeId, [{ id: "m_obsolete", seq: 2 }]), latestSeq: 2, hasMore: false }))
await gap
expect(client.getQueryData(key)).toBe(current)
expect(publishCommunityMessagesMock).toHaveBeenCalledTimes(publicationsBeforeRetirement)
@@ -989,7 +992,7 @@ describe("focused message reconnect catch-up", () => {
it("preserves a same-query cold reset until its canonical read completes instead of rebuilding pages from old HTTP", async () => {
const { client: client } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("reset-pending")
- const oldPage = { messages: [{ id: "m_old", seq: 2 }], latestSeq: 2, hasMore: false }
+ const oldPage = { messages: messageSeedFixture("reset-pending", [{ id: "m_old", seq: 2 }]), latestSeq: 2, hasMore: false }
client.setQueryData(key, { pages: [oldPage], pageParams: [{ mode: "newest" }] })
let releaseCanonical!: (page: typeof oldPage) => void
const queryFn = vi.fn(() => new Promise<typeof oldPage>((resolve) => { releaseCanonical = resolve }))
@@ -1013,7 +1016,7 @@ describe("focused message reconnect catch-up", () => {
releaseOld(oldPage)
await repair
expect(client.getQueryData(key)).toBeUndefined()
- releaseCanonical({ messages: [{ id: "m_current", seq: 3 }], latestSeq: 3, hasMore: false })
+ releaseCanonical(messageReadPageFixture({ messages: messageSeedFixture("reset-pending", [{ id: "m_current", seq: 3 }]), latestSeq: 3, hasMore: false }))
await reset
expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(key)?.pages[0].messages.map((message) => message.id)).toEqual(["m_current"])
expect(queryFn).toHaveBeenCalledOnce()
@@ -1031,16 +1034,16 @@ describe("focused message reconnect catch-up", () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryFn = vi.fn()
.mockRejectedValueOnce(new Error("offline"))
- .mockResolvedValueOnce({
- messages: [{
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture(scopeId, [{
id: "m_after_reconnect",
type: "chat",
seq: 1,
createdAt: "2026-08-15T00:00:01.000Z",
- }],
+ }]),
hasMore: false,
latestSeq: 1,
- })
+ }))
const observer = new InfiniteQueryObserver(queryClient, {
queryKey,
queryFn,
@@ -1094,29 +1097,29 @@ describe("focused message reconnect catch-up", () => {
})
const unsubscribe = observer.subscribe(() => undefined)
apiFetchMock
- .mockResolvedValueOnce({
- messages: [{
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_anchor", [{
id: "m_10",
type: "chat",
seq: 10,
createdAt: "2026-08-15T00:00:10.000Z",
- }],
+ }]),
hasMoreOlder: true,
olderCursor: "older-10",
hasMoreNewer: true,
newerCursor: "newer-10",
latestSeq: 11,
- })
- .mockResolvedValueOnce({
- messages: [{
+ }))
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_anchor", [{
id: "m_11",
type: "chat",
seq: 11,
createdAt: "2026-08-15T00:00:11.000Z",
- }],
+ }]),
hasMoreNewer: false,
latestSeq: 11,
- })
+ }))
await reconcileFocusedMessageQueries(queryClient, "channel", "ch_anchor")
@@ -1139,38 +1142,38 @@ describe("focused message reconnect catch-up", () => {
const queryKey = communityKeys.channelMessages("ch_1")
const { queryFn, unsubscribe } = seedActiveQuery(queryClient, queryKey)
apiFetchMock
- .mockResolvedValueOnce({
- messages: [{
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_1", [{
id: "m_2",
type: "chat",
seq: 2,
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 4,
- })
- .mockResolvedValueOnce({
- messages: [{
+ }))
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_1", [{
id: "m_3",
type: "chat",
seq: 3,
createdAt: "2026-08-15T00:00:03.000Z",
- }],
+ }]),
hasMoreNewer: true,
newerCursor: "2026-08-15T00:00:03.000Z|m_3",
latestSeq: 4,
- })
- .mockResolvedValueOnce({
- messages: [{
+ }))
+ .mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_1", [{
id: "m_4",
type: "chat",
seq: 4,
createdAt: "2026-08-15T00:00:04.000Z",
- }],
+ }]),
hasMoreNewer: false,
latestSeq: 4,
- })
+ }))
await reconcileFocusedMessageQueries(queryClient, "channel", "ch_1")
@@ -1212,29 +1215,29 @@ describe("focused message reconnect catch-up", () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.channelMessages("ch_bounded")
const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
- apiFetchMock.mockResolvedValueOnce({
- messages: [{
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_bounded", [{
id: "m_2",
type: "chat",
seq: 2,
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 100,
- })
+ }))
for (let seq = 3; seq <= 10; seq += 1) {
- apiFetchMock.mockResolvedValueOnce({
- messages: [{
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({
+ messages: messageSeedFixture("ch_bounded", [{
id: `m_${seq}`,
type: "chat",
seq,
createdAt: `2026-08-15T00:00:${String(seq).padStart(2, "0")}.000Z`,
- }],
+ }]),
hasMoreNewer: true,
newerCursor: `2026-08-15T00:00:${String(seq).padStart(2, "0")}.000Z|m_${seq}`,
latestSeq: 100,
- })
+ }))
}
await reconcileFocusedMessageQueries(queryClient, "channel", "ch_bounded")
@@ -1261,18 +1264,18 @@ describe("focused message reconnect catch-up", () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.channelMessages("ch_1")
const { queryFn, unsubscribe } = seedActiveQuery(queryClient, queryKey)
- apiFetchMock.mockResolvedValue({
- messages: [{
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({
+ messages: messageSeedFixture("ch_1", [{
id: "m_2",
type: "chat",
seq: 2,
content: "edited while disconnected",
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 2,
- })
+ }))
await reconcileFocusedMessageQueries(queryClient, "channel", "ch_1")
@@ -1312,18 +1315,18 @@ describe("focused message reconnect catch-up", () => {
}, ...current.pages.slice(1)],
}
: current)
- return {
- messages: [{
+ return messageReadPageFixture({
+ messages: messageSeedFixture("ch_1", [{
id: "m_2",
type: "chat",
seq: 2,
content: "refreshed",
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 2,
- }
+ })
})
await reconcileFocusedMessageQueries(queryClient, "channel", "ch_1")
@@ -1342,17 +1345,17 @@ describe("focused message reconnect catch-up", () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.dmMessages("dm_1")
const { queryFn, unsubscribe } = seedActiveQuery(queryClient, queryKey)
- apiFetchMock.mockResolvedValue({
- messages: [{
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({
+ messages: messageSeedFixture("dm_1", [{
id: "m_2",
type: "chat",
seq: 2,
createdAt: "2026-08-15T00:00:02.000Z",
- }],
+ }]),
hasMore: true,
cursor: "older-2",
latestSeq: 2,
- })
+ }))
await reconcileFocusedMessageQueries(queryClient, "dm", "dm_1")
@@ -1381,7 +1384,7 @@ describe("focused message reconnect catch-up", () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.channelMessagesWindow("forum_1", { mode: "newest" }, "bug")
const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
- apiFetchMock.mockResolvedValue({ messages: [], hasMoreNewer: false, latestSeq: 2 })
+ apiFetchMock.mockResolvedValue(messageReadPageFixture({ messages: messageSeedFixture("forum_1", []), hasMoreNewer: false, latestSeq: 2 }))
await reconcileFocusedMessageQueries(queryClient, "channel", "forum_1")
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 b70a5aea1..deaf930f2 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -1,4 +1,5 @@
-import { CommunityMessageResourceSchema } from "@alook/shared"
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, CommunityMessageResourceSchema } from "@alook/shared"
import { CancelledError, hashKey, queryOptions, type InfiniteData, type Query, type QueryClient, type QueryKey } from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
@@ -12,7 +13,7 @@ import type { ApiRequestOptions } from "@/lib/api/client"
import { actionAttributes, currentPageObservation } from "@/lib/observability/context"
import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "@/lib/observability/telemetry"
import { channelHref } from "@/lib/community/community-route"
-import { messageWindowPage, type MessageInput, type MessagesPage, type MessagesPageParam, type MessagesWindowPage } from "@/lib/community/models/message"
+import { messageWindowPage, type MessageInput, type MessagesPage, type MessagesReadPage, type MessagesPageParam, type MessagesWindowPage } from "@/lib/community/models/message"
import { buildMessagesUrl, messageWindowIdentity } from "@/lib/community/message-window"
type MessageCache = InfiniteData<MessagesWindowPage, MessagesPageParam>
@@ -40,7 +41,7 @@ function mergeWindow(cache: MessageCache, refreshed: MessagesPage, catchUp: Mess
function cachedCoverage(queryClient: QueryClient, scopeId: string, cache: MessageCache, refreshed: MessagesPage, target: number, tag: string | null) {
if (tag !== null || !Number.isSafeInteger(target)) return
const byId = new Map<string, MessageInput>(getCanonicalCommunityMessages(queryClient)
- .filter(row => row.channelId === scopeId && row.resourceComplete === true).map(row => [row.id, row]))
+ .filter(row => row.channelId === scopeId).map(row => [row.id, row]))
for (const message of refreshed.messages) {
const parsed = CommunityMessageResourceSchema.strip().safeParse(message)
if (parsed.success && parsed.data.channelId === scopeId) byId.set(message.id, parsed.data)
@@ -133,7 +134,7 @@ export function retryFailedMessageRepairs(queryClient: QueryClient) {
}))
}
-export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, landing?: { page: MessagesPage; param: MessagesPageParam }, owner?: MessageRepairOwner) {
+export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, landing?: { page: MessagesReadPage; param: MessagesPageParam }, owner?: MessageRepairOwner) {
const scopeId = scope.scopeId
const token = captureCommunityLiveSnapshotToken(queryClient, scopeId), registry = getCommunityDbRegistry(queryClient)
const channel = registry?.collections.channels.get(scopeId)
@@ -143,7 +144,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
const pendingDirection = originalQuery?.state.fetchStatus === "fetching" ? originalQuery.state.fetchMeta?.fetchMore?.direction : undefined
let paginationReplayed = false
let landingPage = landing
- let prefetched: { param: MessagesPageParam; page: MessagesPage } | undefined
+ let prefetched: { param: MessagesPageParam; page: MessagesReadPage } | undefined
const repairKey: QueryKey = [...key, "reconcile"]
return queryOptions({
queryKey: repairKey, staleTime: 0,
@@ -175,8 +176,8 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
const tag = messageWindowIdentity(key)?.tag ?? null
const load = async (param: MessagesPageParam) => {
assert()
- const page = await withConversationReadDeadline(signal, (readSignal) => apiFetchCommunity<MessagesPage>(
- url(scopeId, param, tag), { signal: readSignal, assertActive: assert,
+ const page = await withConversationReadDeadline(signal, (readSignal) => apiFetchCommunity<MessagesReadPage>(
+ url(scopeId, param, tag), { signal: readSignal, assertActive: assert, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) },
observation: { ...observation, reason: "background", role: "reconcile", windowMode: param.mode } }, token,
))
assert()
@@ -185,8 +186,8 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
const target = () => queryClient.getQueryData<number>(targetKey(key)) ?? 0
let cached: MessagesPage | undefined
let cachedCovered = 0
- const published = new Set<MessagesPage>()
- const prefetch = async (current: MessageCache, refreshed: MessagesPage) => {
+ const published = new Set<MessagesReadPage>()
+ const prefetch = async (current: MessageCache, refreshed: MessagesReadPage) => {
if (prefetched) return
const required = Math.max(refreshed.latestSeq ?? 0, target())
const coverage = cachedCoverage(queryClient, scopeId, current, refreshed, required, tag)
@@ -206,14 +207,14 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
if (remaining) { cached = remaining.page; cachedCovered = remaining.covered }
}
}
- const publish = (refreshed: MessagesPage) => {
+ const publish = (refreshed: MessagesReadPage) => {
assert()
const fetchedEnd = Math.max(0, ...(prefetched?.page.messages.map(message => message.seq ?? 0) ?? []))
const catchUp = cached && prefetched && cachedCovered >= fetchedEnd
? [prefetched.page, cached] : [...(cached ? [cached] : []), ...(prefetched ? [prefetched.page] : [])]
const pending = [refreshed, ...(prefetched ? [prefetched.page] : [])].filter(page => !published.has(page))
if (pending.length) {
- publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), proof: { token, signal } })
+ publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), profiles: [...new Map(pending.flatMap(page => page.profiles).map(profile => [profile.id, profile])).values()], proof: { token, signal } })
for (const page of pending) published.add(page)
}
queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)
@@ -258,7 +259,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
})
}
-export function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, target = 0, landing?: { page: MessagesPage; param: MessagesPageParam }, owner?: MessageRepairOwner) {
+export function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, target = 0, landing?: { page: MessagesReadPage; param: MessagesPageParam }, owner?: MessageRepairOwner) {
const query = queryClient.getQueryCache().find({ queryKey: key, exact: true })
if (!query) return Promise.resolve()
queryClient.setQueryData<number>(targetKey(key), (current) => Math.max(current ?? 0, target))
@@ -299,7 +300,7 @@ export function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope,
})
}
-export function reconcileConversationLanding(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, page: MessagesPage, param: MessagesPageParam, owner: MessageRepairOwner) {
+export function reconcileConversationLanding(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, page: MessagesReadPage, param: MessagesPageParam, owner: MessageRepairOwner) {
const data = queryClient.getQueryData(key)
const highWater = page.latestSeq ?? 0
if (!isMessageCache(data)) return Promise.resolve()
diff --git a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
index 333ef1025..8464ba3ed 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
@@ -1,3 +1,4 @@
+import { currentCommunityEventFixture, messageResourceFixture, forumSidebarEnvelopeFixture, serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { seedCanonicalFocusedChannel } from "./test-harness"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { ingestMessages, ingestServerDetail } from "@/lib/community-db/sync"
@@ -51,9 +52,9 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const subscriptions: Array<() => void> = []
for (const serverId of ["server-A", "server-B"]) {
const id = serverId === "server-A" ? "channel-A" : "channel-B"
- ingestServerDetail(registry, { id: serverId, name: serverId, discriminator: "0001", description: "", icon: null, ownerId: "scope-viewer",
- categories: [{ id: "category-" + serverId, name: "Chats", channels: [{ id, name: id, active: false, unread: false }] }] })
- ingestMessages(registry, id, [{ id: "message-" + id, seq: 1, type: "chat", content: id }])
+ ingestServerDetail(registry, serverDirectoryFixture({ id: serverId, name: serverId, discriminator: "0001", description: "", icon: null, ownerId: "scope-viewer",
+ categories: [{ id: "category-" + serverId, name: "Chats", channels: [{ id, name: id, active: false, unread: false }] }] }))
+ ingestMessages(registry, id, [messageResourceFixture({ id: "message-" + id, channelId: id, content: id })])
const queryKey = communityKeys.channelMessages(id)
client.setQueryData(queryKey, { pages: [{ messages: [{ id: "message-" + id, seq: 1 }], latestSeq: 1, hasMore: false }], pageParams: [{ mode: "newest" }] })
subscriptions.push(new QueryObserver(client, { queryKey, queryFn: async () => null, staleTime: Infinity }).subscribe(() => {}))
@@ -164,7 +165,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
resetHookMemoization()
await mountHook({ viewerUserId: "u_me" })
flushEffects()
- capturedOnMessage?.({ type: "community:unread.bump", channelId: "dm_effect_replay", userId: "u_me", isMention: false })
+ await capturedOnMessage?.(currentCommunityEventFixture({ type: "community:unread.bump", channelId: "dm_effect_replay", userId: "u_me", isMention: false }))
await vi.advanceTimersByTimeAsync(500)
expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (
@@ -827,7 +828,10 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
if (url === "/api/community/users/me/read-state") {
return { revision: 0, readStates: [] }
}
- if (String(url).includes("/channels?")) return forumSidebarFixture([])
+ if (String(url).includes("/channels?")) {
+ const serverId = new URL(String(url), "https://alook.test").pathname.split("/")[4]!
+ return { ...forumSidebarEnvelopeFixture(serverId, [], "u_me"), serverNow: "2026-08-01T00:00:00.000Z" }
+ }
throw new Error(`unexpected API fetch: ${String(url)}`)
})
const queryClient = new QueryClient({
diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.ts
index 9187a78a9..c5e7691fa 100644
--- a/src/web/src/hooks/community/community-ws/registry.test.ts
+++ b/src/web/src/hooks/community/community-ws/registry.test.ts
@@ -91,7 +91,9 @@ describe("community WebSocket registry", () => {
it("has exactly one entry for each runtime event type", () => {
const eventTypes = Object.values(WS_EVENTS).sort()
const registryTypes = Object.keys(communityWsRegistry).sort()
- expect(eventTypes).toHaveLength(48)
+ expect(eventTypes).toHaveLength(46)
+ expect(eventTypes).not.toContain("community:channel.member_add")
+ expect(eventTypes).not.toContain("community:channel.member_remove")
expect(registryTypes).toEqual(eventTypes)
})
@@ -111,7 +113,7 @@ describe("community WebSocket registry", () => {
"community:server.update",
"community:category.update",
"community:channel.update",
- "community:channel.member_add",
+ "community:channel.membership.change",
"community:member.update",
"community:unread.bump",
"community:presence.update",
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index 8e19e9c80..c5f216c61 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -29,7 +29,6 @@ import {
handleServerUpdate,
} from "@/hooks/community/community-ws/structure-tree-events"
import {
- handleChannelMemberEvent,
handleChannelMembershipChange,
handleMemberJoin,
handleMemberLeave,
@@ -86,8 +85,6 @@ export const communityWsRegistry = {
"community:channel.delete": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers", "focused-messages"] },
"community:channel.reorder": { handler: handleChannelEvent, reconnectPolicies: ["all-cached-servers"] },
"community:channel.membership.change": { handler: handleChannelMembershipChange, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },
- "community:channel.member_add": { handler: handleChannelMemberEvent, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },
- "community:channel.member_remove": { handler: handleChannelMemberEvent, reconnectPolicies: ["focused-channel-roster", "all-cached-servers"] },
"community:category.create": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },
"community:category.update": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },
"community:category.delete": { handler: handleCategoryEvent, reconnectPolicies: ["all-cached-servers"] },
@@ -187,7 +184,7 @@ export function dispatchCommunityWsEvents(
const serverId = "serverId" in event ? event.serverId : undefined
const parentChannelId = "parentChannelId" in event ? event.parentChannelId : undefined
if (channelId
- && !["community:channel.membership.change", "community:channel.member_add", "community:channel.member_remove", "community:channel.delete"].includes(event.type)
+ && !["community:channel.membership.change", "community:channel.delete"].includes(event.type)
&& getCommunityRuntime(context.queryClient).ws.actions.isChannelAccessRevoked(channelId, serverId, parentChannelId ?? undefined)) continue
if (channelId && serverId) getCommunityRuntime(context.queryClient).ws.actions.observeChannelScope(serverId, channelId, parentChannelId)
const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>
@@ -199,7 +196,6 @@ export function dispatchCommunityWsEvents(
if ([
"community:server.delete",
"community:channel.delete",
- "community:channel.member_remove",
"community:member.leave",
].includes(event.type) || event.type === "community:channel.membership.change" && !event.present) {
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 f274e3772..7c3909f90 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,3 +1,4 @@
+import { serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { QueryClient } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { communityKeys } from "@/lib/query-keys"
@@ -30,10 +31,10 @@ describe("owner-delete scope eviction", () => {
const registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestServerDetail(registry, {
+ ingestServerDetail(registry, serverDirectoryFixture({
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()
diff --git a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts b/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
index 0f5e59656..81d3169b6 100644
--- a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
@@ -1,3 +1,4 @@
+import { currentCommunityEventFixture, dmListRowFixture } from "@/test/community-resource-fixtures"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { getCapturedRuntime } from "./test-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -115,7 +116,7 @@ describe("useCommunityWs — account unread projection", () => {
it("does not notify for an orphan unread.bump", async () => {
await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!(unreadBump("dm_1", "u_me"))
+ capturedOnMessage!(currentCommunityEventFixture(unreadBump("dm_1", "u_me")))
expect(notificationMocks.show).not.toHaveBeenCalled()
})
@@ -154,7 +155,7 @@ describe("useCommunityWs — account unread projection", () => {
await mountHook({ viewerUserId: "u_me" })
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(messageCreate("ch_focused"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_focused")))
await vi.advanceTimersByTimeAsync(500)
expect(getMessageStreamState(capturedQueryClient, {
@@ -190,7 +191,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
])("$type invalidates Friends and reconciles canonical attention once", async (event) => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
"/api/community/users/me/attention",
expect.objectContaining({ signal: expect.anything() }),
@@ -216,25 +217,24 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
scope: { kind: "server", serverId: "server_1", channelId: "channel_1" },
actors: [],
})
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:friend.block",
userId: "blocked_1",
- } satisfies CommunityFriendBlock)
+ } satisfies CommunityFriendBlock))
expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("dm_message"))).toBeUndefined()
expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("server_message"))).toBeDefined()
})
it.each([false, true])("retires a visible DM and late reads with viewer-owned Block=%s, preserving siblings", async (blockedByViewer) => {
const registry = getCommunityDbRegistry(capturedQueryClient)!
- ingestDms(registry, { conversations: ["u_a", "u_other"].map((userId) => ({
+ ingestDms(registry, { conversations: ["u_a", "u_other"].map((userId) => dmListRowFixture({
id: `dm_${userId}`, userId, name: userId, discriminator: "0001", avatar: "A", avatarVersion: 0,
status: "offline" as const, preview: "old private preview",
- })) })
+ }, "u_me")) })
seedCanonicalMessages("dm_u_a", [{ id: "private", content: "private body" }])
seedCanonicalMessages("dm_u_other", [{ id: "other", content: "other body" }])
const baseMetadata = conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, id: "dm_u_a", serverId: null, name: null, type: "dm", parentChannelId: null,
- parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null, createdAt: "2026-10-08T00:00:00Z",
- readContractVersion: 2, accessDecision: { channelId: "dm_u_a", canRead: true, canSend: true, canCreateDiscussion: false } }, "u_me")
+ parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null, createdAt: "2026-10-08T00:00:00Z" }, "u_me")
const metadata = { ...baseMetadata, peer: { ...baseMetadata.peer!, id: "u_a" } }
const api = getCommunityApiFetchMock()
const original = api.getMockImplementation()!
@@ -254,7 +254,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
getCapturedRuntime().ui.setState((state) => ({ ...state, subscription: { dmConversationId: "dm_u_a" } }))
})
await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!({ type: "community:friend.block", userId: "u_a", ...(blockedByViewer ? { blockedByViewer: true } : {}) })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:friend.block", userId: "u_a", ...(blockedByViewer ? { blockedByViewer: true } : {}) }))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_u_a", null)).toBe(true)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_u_other", null)).toBe(false)
expect(isChannelMetadataTokenCurrent(oldMetadata)).toBe(false)
@@ -265,7 +265,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
expect(registry.collections.friendships.has("blocked:u_a")).toBe(blockedByViewer)
expect(getCapturedRuntime().ui.get().subscription.dmConversationId).toBeUndefined()
expect(() => publishCommunityMessages(capturedQueryClient, { channelId: "dm_u_a", messages: [{ id: "late", content: "late body", type: "chat", seq: 2 }], proof: { token: proof } })).toThrow("Stale community live snapshot")
- capturedOnMessage!(messageCreate("dm_u_a", "late-ws"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("dm_u_a", "late-ws")))
expect(registry.collections.messages.has("late-ws")).toBe(false)
await act(async () => { release(metadata); await pending })
expect(capturedQueryClient.getQueryData(communityKeys.channelMeta(null, "dm_u_a"))).toBeUndefined()
@@ -274,14 +274,14 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
it("does not retire the focused DM for an unrelated block or a retired provider", async () => {
const registry = getCommunityDbRegistry(capturedQueryClient)!
- ingestDms(registry, { conversations: [{ id: "dm_keep", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "keep" }] })
+ ingestDms(registry, { conversations: [dmListRowFixture({ id: "dm_keep", userId: "peer", name: "Peer", discriminator: "0001", avatar: "P", avatarVersion: 0, status: "offline", preview: "keep" }, "u_me")] })
seedCanonicalMessages("dm_keep", [{ id: "keep", content: "keep body" }])
await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!({ type: "community:friend.block", userId: "unrelated" })
- capturedOnMessage!({ type: "community:friend.block", userId: "u_me" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:friend.block", userId: "unrelated" }))
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:friend.block", userId: "u_me" }))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_keep", null)).toBe(false)
act(() => getCapturedRuntime().lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 })))
- capturedOnMessage!({ type: "community:friend.block", userId: "peer" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:friend.block", userId: "peer" }))
expect(registry.collections.messages.get("keep")?.content).toBe("keep body")
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_keep", null)).toBe(false)
})
@@ -295,10 +295,10 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
}).catch(() => undefined)
expect(capturedQueryClient.getQueryState(key)).toBeDefined()
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:friend.block",
userId: "blocked_1",
- } satisfies CommunityFriendBlock)
+ } satisfies CommunityFriendBlock))
expect(capturedQueryClient.getQueryState(key)).toBeUndefined()
})
@@ -313,7 +313,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
messageId: "m_1",
authorName: "A",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
await vi.advanceTimersByTimeAsync(500)
expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (
path === "/api/community/users/me/attention"
@@ -332,7 +332,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
messageId: "m_1",
authorName: "A",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(spy.mock.calls.filter((call) => {
const key = call[0]?.queryKey as unknown[] | undefined
return key?.length === 2 && key[0] === "community" && key[1] === "servers"
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
index 577b60bf4..f6da2654e 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { currentCommunityEventFixture, forumFeedScenarioFixture, channelResourceFixture, categoryResourceFixture } from "@/test/community-resource-fixtures"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { act } from "@/test/react-dom-harness"
@@ -7,7 +9,7 @@ import { getCapturedRuntime, seedCanonicalStream, seedCanonicalMessages, canonic
import { useServerRailProjection, useServerTreeProjection } from "@/lib/community-db/projections"
import { mapForumFeedPages } from "@/hooks/community/use-forum-feed"
import { normalizeThreadResources, forumFeedWindow } from "@/hooks/community/forum-feed-window"
-import { publishCommunityForumFeed, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { publishCommunityChannelMetadata, publishCommunityForumFeed, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { QueryObserver } from "@tanstack/react-query"
import type {
@@ -43,9 +45,9 @@ import {
} from "./test-harness"
import { getCanonicalCommunityChannels } from "@/lib/community-db/sync"
-function forumFeedFixture(rows: Array<{ id: string; opener: string; tags: string[] }>) {
+function forumFeedTransportFixture(rows: Array<{ id: string; opener: string; tags: string[] }>) {
return {
- pages: [{
+ pages: [forumFeedScenarioFixture("forum_1", {
serverId: "s1",
parentType: "forum",
threads: rows.map((row) => ({
@@ -86,23 +88,34 @@ function forumFeedFixture(rows: Array<{ id: string; opener: string; tags: string
})),
},
hasMore: false,
- }],
+ })],
pageParams: [null],
}
}
+function forumFeedFixture(rows: Parameters<typeof forumFeedTransportFixture>[0]) {
+ const transport = forumFeedTransportFixture(rows)
+ return { ...transport, pages: transport.pages.map(page => forumFeedWindow(normalizeThreadResources("forum_1", page))) }
+}
+
+function seedKnownThread(serverId: string, parentId: string, parentType: "text" | "forum", childId: string, openerId: string) {
+ seedCanonicalServer({ id: serverId, channels: [{ id: parentId, type: parentType, name: "Parent" }] })
+ publishCommunityChannelMetadata(capturedQueryClient, { metadata: channelResourceFixture({ id: childId, serverId, type: "thread", parentChannelId: parentId, parentMessageId: openerId }),
+ proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient, childId) } })
+}
+
function forumFeedIds(filter: string | null) {
const pages = capturedQueryClient.getQueryData<ReturnType<typeof forumFeedFixture>>(
communityKeys.forumFeed("forum_1", filter),
)?.pages ?? []
const messages = new Map([...canonicalRegistry!.collections.messages.values()].map((message) => [message.id, message]))
const channels = new Map([...canonicalRegistry!.collections.channels.values()].map((channel) => [channel.id, channel]))
- return mapForumFeedPages(pages.map((page) => forumFeedWindow(normalizeThreadResources("forum_1", page))), messages, channels, new Map(), filter).map((thread) => thread.id)
+ return mapForumFeedPages(pages, messages, channels, new Map(), filter).map((thread) => thread.id)
}
function seedForumFeed(rows: Parameters<typeof forumFeedFixture>[0]) {
seedCanonicalServer({ id: "s1", categories: [{ id: "cat1", name: "Forum", channels: [{ id: "forum_1", name: "Forum", type: "forum", active: false, unread: false }] }] })
- const page = forumFeedFixture(rows).pages[0]!
+ const page = forumFeedTransportFixture(rows).pages[0]!
act(() => { publishCommunityForumFeed(capturedQueryClient, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined }) })
}
@@ -114,33 +127,12 @@ describe("useCommunityWs — server.update patches server + list caches", () =>
await mountHook()
seedCanonicalServer({ id: "srv_1", name: "old", description: "old description", ownerId: "u_1" })
const view = await mountCanonicalHook(() => ({ rail: useServerRailProjection(), detail: useServerTreeProjection("srv_1") }))
- act(() => { capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
- id: "srv_1",
- name: "old",
- description: "d",
- icon: null,
- ownerId: "u_1",
- categories: [],
- }) })
- act(() => { capturedQueryClient.setQueryData(communityKeys.servers(), {
- servers: [
- {
- id: "srv_1",
- name: "old",
- description: "old description",
- initial: "O",
- active: false,
- unread: false,
- mentions: 0,
- },
- ],
- }) })
const event: CommunityServerUpdate = {
type: "community:server.update",
serverId: "srv_1",
changes: { name: "new", description: "new description" },
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(view.result.current.detail).toMatchObject({
name: "new",
description: "new description",
@@ -151,7 +143,7 @@ describe("useCommunityWs — server.update patches server + list caches", () =>
})
})
describe("useCommunityWs — child channel events", () => {
- it("child_create without a parentMessageId only invalidates threads", async () => {
+ it("rejects child_create without a parentMessageId before invalidations", async () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event: CommunityChildChannelCreate = {
@@ -164,9 +156,9 @@ describe("useCommunityWs — child channel events", () => {
createdAt: "2026-07-03T00:00:00.000Z",
},
}
- await act(async () => { capturedOnMessage!(event) })
+ await act(async () => { capturedOnMessage!({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }) })
const keys = spy.mock.calls.map((c) => c[0]?.queryKey as unknown[])
- expect(keys.some((k) => k?.includes("threads"))).toBe(true)
+ expect(keys.some((k) => k?.includes("threads"))).toBe(false)
expect(keys.some((k) => k?.includes("forum-threads"))).toBe(false)
expect(keys).not.toContainEqual(communityKeys.channelMessages("ch_1"))
})
@@ -180,15 +172,15 @@ describe("useCommunityWs — channel.* invalidates server(id)", () => {
const event: CommunityChannelCreate = {
type: "community:channel.create",
serverId: "srv_1",
- channel: {
+ channel: channelResourceFixture({ serverId: "srv_1", ...{
id: "ch_new",
name: "n",
type: "text",
position: 0,
createdAt: "2026-07-03T00:00:00.000Z",
- },
+ } }),
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(
spy.mock.calls.some((c) => {
const key = c[0]?.queryKey as unknown[] | undefined
@@ -203,16 +195,10 @@ describe("useCommunityWs — category.* invalidates tree projections", () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!({
- type: "community:category.create",
- serverId: "srv_1",
- category: {
- id: "cat_new",
- name: "Category",
- position: 0,
- private: false,
- },
- } satisfies CommunityCategoryCreate)
+ capturedOnMessage!(currentCommunityEventFixture({
+ type: "community:category.create", serverId: "srv_1",
+ category: categoryResourceFixture({ id: "cat_new", name: "Category", position: 0, private: false, serverId: "srv_1" }),
+ } satisfies CommunityCategoryCreate))
expect(spy).toHaveBeenCalledWith({
queryKey: communityKeys.channelRefDirectory(),
@@ -234,7 +220,7 @@ describe("useCommunityWs — invite.create", () => {
act(() => { capturedQueryClient.setQueryData(matchingKey, { invites: [] }) })
act(() => { capturedQueryClient.setQueryData(otherKey, { invites: [] }) })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:invite.create",
serverId: "srv_1",
invite: {
@@ -242,7 +228,7 @@ describe("useCommunityWs — invite.create", () => {
token: "token_1",
createdAt: "2026-08-08T00:00:00.000Z",
},
- })
+ }))
expect(capturedQueryClient.getQueryState(matchingKey)?.isInvalidated).toBe(true)
expect(capturedQueryClient.getQueryState(otherKey)?.isInvalidated).toBe(false)
@@ -256,11 +242,11 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
act(() => { getCapturedRuntime().ui.setState((state) => ({ ...state, ...{
typingByScope: new Map([["ch:ch_old", new Map([["u_typing", "Typer"]])]]),
} })) })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.delete",
serverId: "srv_1",
channelId: "ch_old",
- } satisfies CommunityChannelDelete)
+ } satisfies CommunityChannelDelete))
expect(getCapturedRuntime().ui.get().typingByScope.has("ch:ch_old")).toBe(false)
})
@@ -270,11 +256,11 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
seedCommunityAttentionScope(capturedQueryClient, { channelId: "ch_dead", serverId: "srv_1", seq: 1 })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.delete",
serverId: "srv_1",
channelId: "ch_dead",
- } satisfies CommunityChannelDelete)
+ } satisfies CommunityChannelDelete))
expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("ch_dead")?.ordinaryUnread)).toBe(false)
})
@@ -296,7 +282,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
serverId: "srv_1",
channelId: "ch_dead",
}
- await act(async () => { capturedOnMessage!(event) })
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture(event)) })
expect(capturedQueryClient.getQueryData(communityKeys.channelMessages("ch_dead"))).toBeUndefined()
expect(capturedQueryClient.getQueryData(communityKeys.pins("ch_dead"))).toBeUndefined()
@@ -321,7 +307,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
description: "",
icon: null,
ownerId: "u_owner",
- categories: [{ id: "cat_1", name: "Category", private: 0, channels: [] }],
+ categories: [{ id: "cat_1", name: "Category", private: false, channels: [] }],
}
seedCanonicalServer({ ...freshServer, categories: [{ ...freshServer.categories[0], channels: [{ ...deletedChannel, active: false, unread: false }] }] })
act(() => { capturedQueryClient.setQueryData(serverKey, {
@@ -343,11 +329,11 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
const unsubscribe = observer.subscribe(() => {})
try {
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.delete",
serverId: "srv_1",
channelId: "ch_dead",
- } satisfies CommunityChannelDelete)
+ } satisfies CommunityChannelDelete))
expect(fetchServer).toHaveBeenCalledTimes(1)
expect(canonicalRegistry!.collections.channels.has("ch_dead")).toBe(false)
@@ -374,7 +360,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
pages: [{
messages: [
{ id: "opener-post_1", thread: { id: "post_1" } },
- { id: "opener-keep", thread: { id: "post_keep" } },
+ { id: "opener-post_keep", thread: { id: "post_keep" } },
],
hasMore: false,
}],
@@ -382,22 +368,9 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
}
await act(async () => { capturedQueryClient.setQueryData(communityKeys.channelMessages("forum_1"), feed) })
const forumFeed = {
- pages: [{
- serverId: "srv_1",
- parentType: "forum",
- threads: [
- { id: "post_1", parentMessageId: "opener-post_1" },
- { id: "post_keep", parentMessageId: "opener-keep" },
- ],
- included: {
- parentMessages: [{ id: "opener-post_1" }, { id: "opener-keep" }],
- firstMessages: [{ channelId: "post_1" }, { channelId: "post_keep" }],
- tags: [{ messageId: "opener-post_1" }, { messageId: "opener-keep" }],
- participants: [{ channelId: "post_1" }, { channelId: "post_keep" }],
- },
- hasMore: false,
- }],
- pageParams: [null],
+ pages: [{ serverId: "srv_1", parentType: "forum", hasMore: false,
+ threads: [{ id: "post_1", openerMessageId: "opener-post_1", participantIds: [] }, { id: "post_keep", openerMessageId: "opener-post_keep", participantIds: [] }],
+ }], pageParams: [null],
}
await act(async () => { capturedQueryClient.setQueryData(communityKeys.forumFeed("forum_1", "bug"), forumFeed) })
await act(async () => { capturedQueryClient.setQueryData(communityKeys.forumTags("forum_1"), { tags: ["bug"] }) })
@@ -424,16 +397,16 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
},
}) })
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.delete",
serverId: "srv_1",
channelId: "post_1",
parentChannelId: "forum_1",
parentMessageId: "opener-post_1",
- } satisfies CommunityChannelDelete) })
+ } satisfies CommunityChannelDelete)) })
expect(capturedQueryClient.getQueryData<typeof feed>(communityKeys.channelMessages("forum_1"))
- ?.pages[0].messages.map((message) => message.id)).toEqual(["opener-keep"])
+ ?.pages[0].messages.map((message) => message.id)).toEqual(["opener-post_keep"])
expect(capturedQueryClient.getQueryData<typeof forumFeed>(communityKeys.forumFeed("forum_1", "bug"))
?.pages[0].threads.map((thread) => thread.id)).toEqual(["post_keep"])
expect(canonicalForumSidebar("srv_1").threads.map((thread) => thread.id))
@@ -458,20 +431,20 @@ describe("useCommunityWs — child_create patches parent thread badge with count
pages: [{ messages: [], hasMore: false }],
pageParams: [null],
}) })
- capturedOnMessage!(messageCreate("ch_parent", "m_parent"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_parent", "m_parent")))
const event: CommunityChildChannelCreate = {
type: "community:channel.child_create",
parentChannelId: "ch_parent",
parentMessageId: "m_parent",
- channel: {
+ channel: channelResourceFixture({ serverId: canonicalRegistry?.collections.channels.get("ch_parent")?.serverId ?? "s1", parentChannelId: "ch_parent", parentMessageId: "m_parent", ...{
id: "ch_thread",
name: "New thread",
type: "thread",
createdAt: "2026-07-03T00:00:00.000Z",
- },
+ } }),
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const cache = capturedQueryClient.getQueryData<{
pages: { messages: { id: string; thread?: { id: string; name: string; messageCount: number } }[] }[]
@@ -502,15 +475,15 @@ describe("useCommunityWs — child_create patches parent thread badge with count
type: "community:channel.child_create",
parentChannelId: "ch_parent",
parentMessageId: "m_parent",
- channel: {
+ channel: channelResourceFixture({ serverId: canonicalRegistry?.collections.channels.get("ch_parent")?.serverId ?? "s1", parentChannelId: "ch_parent", parentMessageId: "m_parent", ...{
id: "ch_thread",
name: "New thread",
type: "thread",
createdAt: "2026-07-03T00:00:00.000Z",
- },
+ } }),
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: parentMessagesKey })
act(() => { capturedQueryClient.setQueryData(parentMessagesKey, {
@@ -524,7 +497,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
}],
pageParams: [null],
}) })
- capturedOnMessage!(messageCreate("ch_parent", "m_parent"))
+ capturedOnMessage!(currentCommunityEventFixture(messageCreate("ch_parent", "m_parent")))
const cache = capturedQueryClient.getQueryData<{
pages: { messages: { id: string; thread?: { id: string } }[] }[]
@@ -535,6 +508,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("child_update still applies the reported messageCount unchanged", async () => {
await mountHook()
+ seedKnownThread("s1", "ch_parent", "text", "ch_thread", "m_parent")
seedCanonicalMessages("ch_parent", [{ id: "m_parent", content: "hello", thread: { id: "ch_thread", name: "old", messageCount: 0 } }])
act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {
pages: [
@@ -558,7 +532,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
channelId: "ch_thread",
changes: { messageCount: 5 },
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const cache = capturedQueryClient.getQueryData<{
pages: { messages: { thread?: { messageCount: number } }[] }[]
@@ -577,12 +551,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
act(() => { capturedQueryClient.setQueryData(key, { value: "stale" }) })
}
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: ["archived"] },
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
await vi.waitFor(() => {
for (const key of [allFeed, archivedFeed, tags, messages]) {
@@ -604,12 +578,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
const unsubscribe = observer.subscribe(() => {})
try {
await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(1))
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: [...tags] },
- } satisfies CommunityChildChannelUpdate) })
+ } satisfies CommunityChildChannelUpdate)) })
await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(2))
await act(async () => { release({ tags: [...staleTags] }); await oldRead })
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(key)).toEqual({ tags: [...tags] }))
@@ -632,12 +606,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
forumFeedFixture([]),
) })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: ["bug", "archived"] },
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
expect(forumFeedIds(null)).toEqual([])
expect(forumFeedIds("bug")).toEqual([])
@@ -660,12 +634,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
forumFeedFixture([]),
) })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: ["bug"] },
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
expect(forumFeedIds("archived")).toEqual([])
expect(forumFeedIds(null)).toEqual([])
@@ -683,18 +657,18 @@ describe("useCommunityWs — child_create patches parent thread badge with count
forumFeedFixture([{ id: "post_1", opener: "opener_two", tags: ["bug"] }]),
) })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: ["bug", "archived"] },
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
expect(forumFeedIds(null)).toEqual([])
expect(forumFeedIds("bug")).toEqual([])
expect(canonicalRegistry!.collections.channels.get("post_1")).toMatchObject({ parentMessageId: "opener_one", tags: ["bug", "archived"] })
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumFeedFixture>>(communityKeys.forumFeed("forum_1", null))?.pages[0].threads[0].parentMessageId).toBe("opener_one")
- expect(capturedQueryClient.getQueryData<ReturnType<typeof forumFeedFixture>>(communityKeys.forumFeed("forum_1", "bug"))?.pages[0].threads[0].parentMessageId).toBe("opener_two")
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumFeedFixture>>(communityKeys.forumFeed("forum_1", null))?.pages[0].threads[0].openerMessageId).toBe("opener_one")
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumFeedFixture>>(communityKeys.forumFeed("forum_1", "bug"))?.pages[0].threads[0].openerMessageId).toBe("opener_two")
})
it("archive-tag updates evict only the sidebar projection and keep the active route", async () => {
@@ -709,12 +683,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
parentMessageId: "opener-post_1",
}) })
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags: ["bug", "archived"] },
- } satisfies CommunityChildChannelUpdate) })
+ } satisfies CommunityChildChannelUpdate)) })
expect(canonicalForumSidebar("s1").threads.map(({ id }) => id)).toEqual(["post_2"])
expect(getCanonicalCommunityChannels(capturedQueryClient)
@@ -743,12 +717,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
parentMessageId: "opener-post_1",
}) })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "post_1",
changes: { tags },
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
expect(canonicalForumSidebar("s1").threads).toEqual(before)
expect(getCapturedRuntime().ui.get().currentChannelId).toBe("post_1")
@@ -772,12 +746,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
parentChannelId: "ch_parent",
}) })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "ch_parent",
channelId: "ch_thread",
changes: { name: "new" },
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
expect(readCurrentCommunityChannelMeta(capturedQueryClient)?.name).toBe("new")
expect(capturedQueryClient.getQueryData<{ name: string }>(
@@ -797,21 +771,21 @@ describe("useCommunityWs — child_create patches parent thread badge with count
parentMessageId: "opener-ch_thread",
}) })
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "ch_thread",
changes: { archived: true, tags: ["bug"] },
- } satisfies CommunityChildChannelUpdate) })
+ } satisfies CommunityChildChannelUpdate)) })
expect(canonicalForumSidebar("s1").threads).toEqual([])
expect(readCurrentCommunityChannelMeta(capturedQueryClient)).toMatchObject({ id: "ch_thread", archived: true })
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "ch_thread",
changes: { archived: false },
- } satisfies CommunityChildChannelUpdate) })
+ } satisfies CommunityChildChannelUpdate)) })
expect(canonicalForumSidebar("s1").threads.map(({ id }) => id)).toEqual(["ch_thread"])
})
@@ -820,12 +794,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
seedCanonicalForumSidebar("s1", [])
getCommunityApiFetchMock().mockRejectedValueOnce(new Error("offline"))
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "forum_1",
channelId: "missing-post",
changes: { archived: false },
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
expect.stringContaining("retainId=missing-post"),
@@ -843,12 +817,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
parentChannelId: "forum_1",
})
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.delete",
serverId: "srv_1",
channelId: "ch_dead",
parentChannelId: "forum_1",
- } satisfies CommunityChannelDelete)
+ } satisfies CommunityChannelDelete))
expect(readCurrentCommunityChannelMeta(capturedQueryClient)).toBeNull()
})
@@ -879,12 +853,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
{ archived: false },
{ lastMessageAt: "2026-08-09T00:00:00.000Z" },
]) {
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "text_parent",
channelId: "text_thread",
changes,
- } satisfies CommunityChildChannelUpdate)
+ } satisfies CommunityChildChannelUpdate))
}
expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
@@ -898,6 +872,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("child_update keeps newer thread fields from the current base row when refreshing fallback", async () => {
await mountHook()
+ seedKnownThread("s1", "ch_parent", "text", "ch_thread", "m_parent")
const { useCommunityStore } = await import("@/stores/community")
await act(async () => { getCapturedRuntime().ui.actions.setCurrentServerId("s1") })
const scope = { kind: "channel" as const, id: "ch_parent", serverId: "s1" }
@@ -943,12 +918,12 @@ describe("useCommunityWs — child_create patches parent thread badge with count
await act(async () => { seedCanonicalMessages("ch_parent", [{ id: "m_parent", content: "hello", seq: 1, thread: { id: "ch_thread", name: "base", messageCount: 2, lastReplyAt: "2026-08-06T00:00:02.000Z" } }]) })
- await act(async () => { capturedOnMessage!({
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture({
type: "community:channel.child_update",
parentChannelId: "ch_parent",
channelId: "ch_thread",
changes: { messageCount: 5 },
- } satisfies CommunityChildChannelUpdate) })
+ } satisfies CommunityChildChannelUpdate)) })
expect(canonicalMessage("m_parent")?.thread).toMatchObject({
id: "ch_thread",
@@ -960,8 +935,9 @@ describe("useCommunityWs — child_create patches parent thread badge with count
})
describe("useCommunityWs — channel.delete refreshes the parent forum feed", () => {
- it.each(["forum", "text"])("invalidates the %s parent feed while preserving ordinary thread openers", async parentType => {
+ it.each(["forum", "text"] as const)("invalidates the %s parent feed while preserving ordinary thread openers", async parentType => {
await mountHook()
+ seedKnownThread("srv_1", "forum_1", parentType, "post_1", "opener_1")
seedCanonicalServer({ id: "srv_1", categories: [{ id: "cat1", name: "Forum", channels: [{ id: "forum_1", name: "Forum", type: parentType, active: false, unread: false }] }] })
seedCanonicalMessages("forum_1", [{ id: "opener_1", content: "Post", thread: { id: "post_1", name: "Post", messageCount: 0 } }])
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
@@ -980,7 +956,7 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()
channelId: "post_1",
parentChannelId: "forum_1",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const invalidatedKeys = invalidateSpy.mock.calls.map((c) => JSON.stringify(c[0]?.queryKey))
expect(invalidatedKeys).toContain(JSON.stringify(communityKeys.channelMessages("forum_1")))
@@ -989,7 +965,7 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()
expect(capturedQueryClient.getQueryData<{ pages: { messages: unknown[] }[] }>(bugKey)?.pages[0].messages).toHaveLength(parentType === "forum" ? 0 : 1)
})
- it("does not throw and still evicts own caches when parentChannelId is absent (legacy event)", async () => {
+ it("does not throw and still evicts own caches when the optional parentChannelId is absent", async () => {
await mountHook()
// Seed the deleted channel's own message cache so we can assert eviction.
act(() => { capturedQueryClient.setQueryData(communityKeys.channelMessages("post_1"), { pages: [], pageParams: [] }) })
@@ -1001,7 +977,7 @@ describe("useCommunityWs — channel.delete refreshes the parent forum feed", ()
serverId: "srv_1",
channelId: "post_1",
}
- expect(() => capturedOnMessage!(event)).not.toThrow()
+ expect(() => capturedOnMessage!(currentCommunityEventFixture(event))).not.toThrow()
expect(removeSpy.mock.calls.some(([filters]) => filters?.predicate?.(query) || JSON.stringify(filters?.queryKey) === JSON.stringify(query.queryKey))).toBe(true)
expect(capturedQueryClient.getQueryState(query.queryKey)).toBeUndefined()
@@ -1025,7 +1001,7 @@ describe("useCommunityWs — server.update icon removal", () => {
serverId: "srv_1",
changes: { icon: null },
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
const detail = canonicalRegistry!.collections.servers.get("srv_1")
expect(detail?.icon).toBeNull()
})
@@ -1037,10 +1013,10 @@ describe("useCommunityWs — server.delete resets store when focused server dies
seedCommunityAttentionScope(capturedQueryClient, { channelId: "ch_dead", serverId: "srv_doomed", seq: 1 })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:server.delete",
serverId: "srv_doomed",
- } satisfies CommunityServerDelete)
+ } satisfies CommunityServerDelete))
expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("ch_dead")?.ordinaryUnread)).toBe(false)
})
@@ -1059,7 +1035,7 @@ describe("useCommunityWs — server.delete resets store when focused server dies
type: "community:server.delete",
serverId: "srv_doomed",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(getCapturedRuntime().ui.get().currentServerId).toBeNull()
expect(getCapturedRuntime().ui.get().currentChannelId).toBeNull()
@@ -1076,7 +1052,7 @@ describe("useCommunityWs — server.delete resets store when focused server dies
type: "community:server.delete",
serverId: "srv_other",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect(getCapturedRuntime().ui.get().currentServerId).toBe("srv_active")
expect(getCapturedRuntime().ui.get().currentChannelId).toBe("ch_1")
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 42ff2ea3c..f125e796d 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -1,8 +1,10 @@
+import { messageSeedFixture, serverRailResponseFixture } from "@/test/community-resource-fixtures"
+import { profileResourceFixture, channelResourceFixture, messageResourceFixture, serverDirectoryFixture, forumSidebarEnvelopeFixture } from "@/test/community-resource-fixtures"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { createElement, type ReactNode } from "react"
import { act, renderHook, type RenderHookResult } from "@/test/react-dom-harness"
import { CommunityDbProvider } from "@/lib/community-db/projections"
-import type { CommunityMessageCreate } from "@alook/shared"
+import { CommunityChannelResourceSchema, type CommunityMessageCreate } from "@alook/shared"
import { vi } from "vitest"
import type { UseUserWsOptions, UserWsConnectionPhase } from "@/lib/use-user-ws"
import {
@@ -29,7 +31,7 @@ const communityApiFetch = vi.hoisted(() => vi.fn(async (...args: unknown[]) => {
if (url === "/api/community/users/me/read-state") {
return { revision: 0, readStates: [] }
}
- if (url === "/api/community/users/me/attention") return { scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+ if (url === "/api/community/users/me/attention") return { resources: { viewerId: (args[1] as { authenticationAccount?: string } | undefined)?.authenticationAccount ?? "u_me", servers: [], serverMemberships: [], channels: [], memberships: [], profiles: [], messages: [] }, scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
throw new Error(`unexpected API fetch: ${url}`)
}))
@@ -119,7 +121,7 @@ function resetHarnessState() {
if (url === "/api/community/users/me/read-state") {
return { revision: 0, readStates: [] }
}
- if (url === "/api/community/users/me/attention") return { scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+ if (url === "/api/community/users/me/attention") return { resources: { viewerId: (args[1] as { authenticationAccount?: string } | undefined)?.authenticationAccount ?? "u_me", servers: [], serverMemberships: [], channels: [], memberships: [], profiles: [], messages: [] }, scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
throw new Error(`unexpected API fetch: ${url}`)
})
}
@@ -217,7 +219,7 @@ export function unmountHook() {
export function seedCanonicalMessages(channelId: string, messages: MessageInput[]) {
if (!canonicalRegistry) throw new Error("Community test owner missing")
- act(() => ingestMessages(canonicalRegistry!, channelId, messages.map((message) => ({ type: "chat", content: "", seq: 1, ...message }))))
+ act(() => ingestMessages(canonicalRegistry!, channelId, messageSeedFixture(channelId, messages)))
}
export function seedCanonicalStream(scope: MessageScope, event: MessageOverlayEvent) {
@@ -229,11 +231,11 @@ export function canonicalMessage(id: string) {
return messageProjectionHook?.result.current?.get(id)
}
-export function seedCanonicalServer(server: Partial<Parameters<typeof ingestServerDetail>[1]> & { id: string }) {
+export function seedCanonicalServer(scenario: Parameters<typeof serverDirectoryFixture>[0]) {
if (!canonicalRegistry) throw new Error("Community test owner missing")
- const detail = { name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "u_me", categories: [], ...server }
+ const detail = serverDirectoryFixture(scenario)
act(() => {
- ingestServers(canonicalRegistry!, { servers: [{ id: detail.id, name: detail.name, initial: detail.name[0]!, active: false, unread: false, mentions: 0, ownerId: detail.ownerId }] })
+ ingestServers(canonicalRegistry!, serverRailResponseFixture({ servers: [{ ...detail.server, initial: detail.server.name[0]!, active: false, unread: false, mentions: 0, role: "owner", memberId: `member-${detail.server.id}` }] }, canonicalRegistry!.accountId))
ingestServerDetail(canonicalRegistry!, detail)
})
}
@@ -242,8 +244,9 @@ export function messageCreate(channelId: string, msgId = "m_1"): CommunityMessag
return {
type: "community:message.create",
channelId,
+ profiles: [profileResourceFixture({ id: "u_author", name: "author" })],
message: {
- id: msgId,
+ ...messageResourceFixture({ id: msgId, channelId }),
type: "chat",
authorId: "u_author",
authorName: "author",
@@ -291,101 +294,29 @@ export function forumSidebarFixture(ids = ["post_1"]) {
}
export function seedCanonicalForumSidebar(serverId: string, ids = ["post_1"]) {
- act(() => {
- 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,
- },
- })
- })
+ if (!canonicalRegistry) throw new Error("Community test owner missing")
+ const envelope = forumSidebarEnvelopeFixture(serverId, ids, canonicalRegistry.accountId!)
+ seedCanonicalServer({ ...envelope.resources.servers[0], channels: [envelope.resources.channels[0]] })
+ act(() => publishCommunityForumSidebar(capturedQueryClient, {
+ serverId, resources: envelope.resources,
+ channels: envelope.resources.channels.filter(channel => channel.type === "thread").map(channel => ({ ...channel, activityAt: envelope.serverNow, unread: false, participating: true })),
+ openers: envelope.resources.messages,
+ 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,
-) {
- act(() => {
- 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 seedCanonicalThread(serverId: string, parentId: string, parentType: "text" | "forum", childId: string) {
+ if (!canonicalRegistry) throw new Error("Community test owner missing")
+ seedCanonicalServer({ id: serverId, ownerId: "u_me", categories: [{ id: `${serverId}-category`, name: "Category", channels: [{ id: parentId, name: "Parent", type: parentType }] }] })
+ act(() => publishCommunityChannelMetadata(capturedQueryClient, {
+ metadata: channelResourceFixture({ id: childId, serverId, name: "Child", type: "thread", parentChannelId: parentId,
+ parentMessageId: `${childId}-opener`, creatorId: "u_me", lastMessageAt: "2026-08-01T00:00:00.000Z" }),
+ proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined },
+ }))
}
export function hasCanonicalChannel(channelId: string) {
@@ -409,7 +340,7 @@ export function seedCanonicalFocusedChannel(metadata: { name: string; parentChan
const channelId = state.currentChannelId ?? state.subscription.channelId
if (!channelId) throw new Error("Focused test channel missing")
publishCommunityChannelMetadata(capturedQueryClient, {
- metadata: { creatorId: null, archived: false, lastMessageAt: null, parentMessageId: null, parentChannelId: null, ...canonicalRegistry.collections.channels.get(channelId), id: channelId, serverId: canonicalRegistry.collections.channels.get(channelId)?.serverId ?? state.currentServerId ?? "s1", type: metadata.parentChannelId ? "thread" : "text", ...metadata },
+ metadata: channelResourceFixture({ ...Object.fromEntries(Object.entries(canonicalRegistry.collections.channels.get(channelId) ?? {}).filter(([key]) => key in CommunityChannelResourceSchema.shape)), id: channelId, serverId: canonicalRegistry.collections.channels.get(channelId)?.serverId ?? state.currentServerId ?? "s1", type: metadata.parentChannelId ? "thread" : "text", ...metadata }),
proof: { token: captureCommunityLiveSnapshotToken(capturedQueryClient), signal: undefined },
})
})
diff --git a/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts b/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts
index 908151565..9189c6dfa 100644
--- a/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/typing-events.dom.test.ts
@@ -1,10 +1,12 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { currentCommunityEventFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { getCapturedRuntime } from "./test-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import type { CommunityMessageCreate, CommunityTypingStart } from "@alook/shared"
import { act } from "@/test/react-dom-harness"
import { applyTypingIndicator } from "./typing"
import { communityKeys } from "@/lib/query-keys"
-import { getCanonicalCommunityTypingMembership } from "@/lib/community-db/sync"
+import { getCanonicalCommunityTypingMembership, setCanonicalCommunityChannelMember } from "@/lib/community-db/sync"
import { useTypingNamesForScope, useTypingUsersForScope } from "@/stores/community"
import {
capturedOnMessage,
@@ -26,19 +28,20 @@ describe("useCommunityWs — typing follows membership", () => {
it.each(["text", "forum"] as const)("clears a departed %s child participant and timer, denies a repeated start, and permits rejoin", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("s1", "parent", parentType, "child")
+ act(() => { setCanonicalCommunityChannelMember(capturedQueryClient, "parent", "u_me", "access", true) })
getCapturedRuntime().ui.actions.subscribe({ channelId: "child" })
await mountHook({ viewerUserId: "u_me" })
const display = await mountCanonicalHook(() => ({ users: useTypingUsersForScope("ch:child"), names: useTypingNamesForScope("ch:child") }))
const membership = { type: "community:channel.membership.change", serverId: "s1", channelId: "child", userId: "u_other", relation: "notify", present: true }
- capturedOnMessage!(membership)
- capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other", name: "Other" })
- capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_kept" })
+ capturedOnMessage!(currentCommunityEventFixture(membership))
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "child", userId: "u_other", name: "Other" }))
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "child", userId: "u_kept" }))
act(() => applyTypingIndicator(capturedQueryClient, "dm:dm_other", "u_other", null))
const oldTimer = getCapturedRuntime().ui.get().typingTimers.get("ch:child|u_other")
expect(oldTimer).toBeDefined()
const clear = vi.spyOn(globalThis, "clearTimeout")
try {
- capturedOnMessage!({ ...membership, present: false })
+ capturedOnMessage!(currentCommunityEventFixture({ ...membership, present: false }))
expect(clear).toHaveBeenCalledWith(oldTimer)
expect(getCapturedRuntime().ui.get().typingTimers.has("ch:child|u_other")).toBe(false)
expect(getCapturedRuntime().ui.get().typingByScope.get("ch:child")).toEqual(new Map([["u_kept", null]]))
@@ -47,11 +50,11 @@ describe("useCommunityWs — typing follows membership", () => {
expect(hasCanonicalChannel("child")).toBe(true)
expect(hasCanonicalChannelAccess("parent", "u_me")).toBe(true)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "s1")).toBe(false)
- capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "child", userId: "u_other" }))
expect(getCapturedRuntime().ui.get().typingByScope.get("ch:child")?.has("u_other")).toBe(false)
capturedQueryClient.setQueryData(communityKeys.channelMembers("child", "notify"), { serverId: "s1", relation: "notify", members: [] })
- capturedOnMessage!(membership)
- capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })
+ capturedOnMessage!(currentCommunityEventFixture(membership))
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "child", userId: "u_other" }))
expect(getCanonicalCommunityTypingMembership(capturedQueryClient, "child", "u_other")).not.toBe(false)
expect(getCapturedRuntime().ui.get().typingByScope.get("ch:child")?.get("u_other")).toBeNull()
expect(getCapturedRuntime().ui.get().typingTimers.has("ch:child|u_other")).toBe(true)
@@ -63,18 +66,19 @@ describe("useCommunityWs — typing follows membership", () => {
it.each(["text", "forum"] as const)("removes access to a %s parent from the typer and its known child without changing another scope", async (parentType) => {
await mountHook({ viewerUserId: "u_me" })
seedCanonicalThread("s1", "parent", parentType, "child")
+ act(() => { setCanonicalCommunityChannelMember(capturedQueryClient, "parent", "u_me", "access", true) })
getCapturedRuntime().ui.actions.subscribe({ channelId: "child" })
await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "child", userId: "u_other" }))
act(() => {
applyTypingIndicator(capturedQueryClient, "ch:parent", "u_other", null)
applyTypingIndicator(capturedQueryClient, "dm:dm_other", "u_other", null)
})
- capturedOnMessage!({ type: "community:channel.membership.change", serverId: "s1", channelId: "parent", userId: "u_other", relation: "access", present: false })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", serverId: "s1", channelId: "parent", userId: "u_other", relation: "access", present: false }))
expect(getCapturedRuntime().ui.get().typingByScope.has("ch:child")).toBe(false)
expect(getCapturedRuntime().ui.get().typingByScope.has("ch:parent")).toBe(false)
expect(getCapturedRuntime().ui.get().typingByScope.has("dm:dm_other")).toBe(true)
- capturedOnMessage!({ type: "community:typing.start", channelId: "child", userId: "u_other" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "child", userId: "u_other" }))
expect(getCapturedRuntime().ui.get().typingByScope.has("ch:child")).toBe(false)
})
@@ -82,13 +86,13 @@ describe("useCommunityWs — typing follows membership", () => {
await mountHook({ viewerUserId: "u_me" })
getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm_1" })
await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!({ type: "community:typing.start", channelId: "dm_1", userId: "u_peer" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "dm_1", userId: "u_peer" }))
act(() => applyTypingIndicator(capturedQueryClient, "ch:other", "u_peer", "Peer"))
- capturedOnMessage!({ type: "community:channel.membership.change", serverId: null, channelId: "dm_1", userId: "u_peer", relation: "access", present: false })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", serverId: null, channelId: "dm_1", userId: "u_peer", relation: "access", present: false }))
expect(getCapturedRuntime().ui.get().typingByScope.has("dm:dm_1")).toBe(false)
expect(getCapturedRuntime().ui.get().typingTimers.has("dm:dm_1|u_peer")).toBe(false)
expect(getCapturedRuntime().ui.get().typingByScope.get("ch:other")?.get("u_peer")).toBe("Peer")
- capturedOnMessage!({ type: "community:typing.start", channelId: "dm_1", userId: "u_peer" })
+ capturedOnMessage!(currentCommunityEventFixture({ type: "community:typing.start", channelId: "dm_1", userId: "u_peer" }))
expect(getCapturedRuntime().ui.get().typingByScope.has("dm:dm_1")).toBe(false)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm_1")).toBe(false)
})
@@ -107,7 +111,7 @@ describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {
channelId: "dm_other",
userId: "u_other",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
// Focus is on ch_1, so the unfocused DM channel's typing.start is dropped
// entirely — no scope gains a typer.
@@ -129,7 +133,7 @@ describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {
channelId: "ch_1",
userId: "u_other",
}
- capturedOnMessage!(event)
+ capturedOnMessage!(currentCommunityEventFixture(event))
expect([...(getCapturedRuntime().ui.get().typingByScope.get("ch:ch_1")?.keys() ?? [])]).toEqual([
"u_other",
@@ -143,16 +147,16 @@ describe("useCommunityWs — typing.start honours focus (no DM leak)", () => {
resetHookMemoization()
await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:typing.start",
channelId: "ch_1",
userId: "u_other",
- })
- capturedOnMessage!({
+ }))
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:typing.stop",
channelId: "ch_1",
userId: "u_other",
- })
+ }))
const state = getCapturedRuntime().ui.get()
expect(state.typingByScope.get("ch:ch_1")).toBeUndefined()
@@ -172,11 +176,11 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {
// A DM is a channel — typing arrives as `typing.start` keyed by the DM's
// channel id. The scope key resolves to `dm:` because the subscription's
// `dmConversationId` slot holds that channel id.
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:typing.start",
channelId: "dm_1",
userId: "u_peer",
- })
+ }))
const state = getCapturedRuntime().ui.get()
// The typer is confined to dm:dm_1 — a channel view reading ch:* sees nothing.
@@ -194,11 +198,11 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {
await mountHook({ viewerUserId: "u_me" })
// Bot is "typing" in the DM (typing.start on the DM channel).
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({
type: "community:typing.start",
channelId: "dm_bot",
userId: "u_bot",
- })
+ }))
expect([...(getCapturedRuntime().ui.get().typingByScope.get("dm:dm_bot")?.keys() ?? [])]).toEqual([
"u_bot",
])
@@ -206,10 +210,21 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {
// Its reply arrives as message.create on the same DM channel. The scope key
// must resolve to dm:dm_bot (via the subscription), clearing the pill — not
// leak into a ch: bucket.
- capturedOnMessage!({
+ capturedOnMessage!(currentCommunityEventFixture({ profiles: messageProfilesFixture([messageResourceFixture({
+ channelId: "dm_bot",
+ id: "m_bot_reply",
+ authorId: "u_bot",
+ authorName: "bot",
+ authorAvatarVersion: 0,
+ content: "done",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-07-03T00:00:00.000Z",
+ })]),
type: "community:message.create",
channelId: "dm_bot",
- message: {
+ message: messageResourceFixture({
+ channelId: "dm_bot",
id: "m_bot_reply",
authorId: "u_bot",
authorName: "bot",
@@ -218,8 +233,8 @@ describe("useCommunityWs — typing state is scoped per conversation", () => {
type: "chat",
seq: 1,
createdAt: "2026-07-03T00:00:00.000Z",
- },
- } as CommunityMessageCreate)
+ }),
+ } as CommunityMessageCreate))
const state = getCapturedRuntime().ui.get()
expect(state.typingByScope.get("dm:dm_bot")).toBeUndefined()
diff --git a/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts b/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
index 30eb0e1b6..dff56b6da 100644
--- a/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
@@ -1,3 +1,4 @@
+import { attentionSnapshotScenarioFixture, currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { captureCommunityLiveSnapshotToken, publishCommunityConversationReadState } from "@/lib/community-db/sync"
import { afterEach, beforeEach, expect, it, vi } from "vitest"
import { act, waitFor } from "@/test/react-dom-harness"
@@ -8,7 +9,7 @@ const at = "2026-10-27T00:00:00.000Z"
function attention(seq: number, kind: "text" | "dm" | "child" = "text") {
const parent = { id: "parent", serverId: "s1", name: "Parent", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "peer", archived: false, lastMessageAt: at }
const channel = { ...parent, id: "c1", name: "Channel", type: kind === "child" ? "thread" : "text", parentChannelId: kind === "child" ? "parent" : null, parentMessageId: kind === "child" ? "opener" : null, ...(kind === "child" ? { openerSeq: 1, openerUnread: false } : {}) }
- return {
+ return attentionSnapshotScenarioFixture({
scopes: [{ scopeId: "c1", channelId: "c1", serverId: kind === "dm" ? null : "s1", parentChannelId: kind === "child" ? "parent" : null, ordinaryUnread: true, lastUnreadSeq: seq, attentionCount: 0, lastAttentionSeq: null, ...(kind === "dm" ? { unreadCount: seq } : {}) }],
items: [], limit: 100, truncated: false,
included: {
@@ -18,7 +19,7 @@ function attention(seq: number, kind: "text" | "dm" | "child" = "text") {
profiles: [{ userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0 }],
messages: kind === "child" ? [{ id: "opener", channelId: "parent", authorId: "peer", type: "chat", content: "Opener", seq: 1, createdAt: at }] : [],
},
- }
+ }, "u_me")
}
function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done }); return { promise, resolve } }
function transport(read: () => Promise<ReturnType<typeof attention>>) {
@@ -38,7 +39,7 @@ it.each(["text", "dm", "child"] as const)("uses qualified HTTP attention for a %
transport(() => gate.promise)
const original = { categories: [{ channels: [{ id: "c1", unread: true }] }] }
capturedQueryClient.setQueryData(communityKeys.server("s1"), original)
- await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me", { ...(kind === "dm" ? {} : { serverId: "s1", railChannelId: kind === "child" ? "parent" : "c1" }) })) })
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture(unreadBump("c1", "u_me", { ...(kind === "dm" ? {} : { serverId: "s1", railChannelId: kind === "child" ? "parent" : "c1" }) }))) })
expect(canonicalRegistry!.collections.attentionScopes.size).toBe(0)
expect(capturedQueryClient.getQueryData(communityKeys.server("s1"))).toBe(original)
await act(async () => { gate.resolve(attention(4, kind)) })
@@ -54,9 +55,9 @@ it("rejects an ignored-abort old attention response after a newer arrival", asyn
const old = deferred<ReturnType<typeof attention>>()
let requests = 0
transport(() => ++requests === 1 ? old.promise : Promise.resolve(attention(5)))
- await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me", { serverId: "s1" })) })
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture(unreadBump("c1", "u_me", { serverId: "s1" }))) })
await waitFor(() => expect(requests).toBe(1))
- await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me", { serverId: "s1" })) })
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture(unreadBump("c1", "u_me", { serverId: "s1" }))) })
await waitFor(() => expect(canonicalRegistry!.collections.attentionScopes.get("c1")?.lastUnreadSeq).toBe(5))
await act(async () => { old.resolve(attention(4)) })
expect(canonicalRegistry!.collections.attentionScopes.get("c1")?.lastUnreadSeq).toBe(5)
@@ -66,7 +67,7 @@ it("rejects an ignored-abort old attention response after a newer arrival", asyn
it("ignores another account's bump without creating unread or issuing attention IO", async () => {
await mountHook({ viewerUserId: "u_me" })
const requests = getCommunityApiFetchMock().mock.calls.length
- await act(async () => { await capturedOnMessage!(unreadBump("c1", "someone-else", { serverId: "s1" })) })
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture(unreadBump("c1", "someone-else", { serverId: "s1" }))) })
expect(canonicalRegistry!.collections.attentionScopes.size).toBe(0)
expect(getCommunityApiFetchMock().mock.calls).toHaveLength(requests)
})
@@ -81,7 +82,7 @@ it("rejects a pre-confirmation attention count and retries with the same origina
const fresh = attention(5, "dm")
fresh.scopes[0]!.unreadCount = 3
transport(() => ++requests === 1 ? old.promise : Promise.resolve(fresh))
- await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me")) })
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture(unreadBump("c1", "u_me"))) })
expect(requests).toBe(1)
await act(async () => {
publishCommunityConversationReadState(capturedQueryClient, { channelId: "c1", lastReadMessageId: "m2", lastReadAt: at, lastReadSeq: 2 }, 2, { token: captureCommunityLiveSnapshotToken(capturedQueryClient) }, "advance")
diff --git a/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx b/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx
index 446351882..8da7ebaa3 100644
--- a/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx
+++ b/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx
@@ -1,3 +1,4 @@
+import { resourceBundleFixture, forumFeedScenarioFixture, friendBucketScenarioFixture } from "@/test/community-resource-fixtures"
import { afterEach, expect, it, vi } from "vitest"
import { QueryClientProvider } from "@tanstack/react-query"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -13,6 +14,9 @@ import { useNotificationSettings } from "./use-notification-settings"
import { useDms } from "./use-dms"
import { useForumFeed } from "./use-forum-feed"
+const emptyPins = () => ({ pins: [], resources: resourceBundleFixture() })
+const emptyThreads = () => forumFeedScenarioFixture("c1", { serverId: "s1", parentType: "text", threads: [], included: {}, hasMore: false })
+
const load = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))
afterEach(() => { load.mockReset(); localStorage.clear() })
@@ -26,8 +30,8 @@ it("retains hidden message and panel caches without starting requests, then load
owner.client.setQueryData(communityKeys.threads("c1"), { parentChannelId: "c1", parentType: "text", serverId: "s1", threads: [] }, { updatedAt: 1 })
let presented = false
const held = new Promise(() => {})
- load.mockImplementation((url: string) => url.includes("entry=1") ? held : url.endsWith("/pins") ? { pins: [] }
- : { parentChannelId: "c1", parentType: "text", serverId: "s1", threads: [], included: { parentMessages: [], firstMessages: [], tags: [], participants: [] } })
+ load.mockImplementation(async (url: string) => url.includes("entry=1") ? held : url.endsWith("/pins") ? emptyPins()
+ : emptyThreads())
const hook = renderHook(() => ({ feed: useMessages("c1", { serverId: "s1" }), pins: usePins("c1"), threads: useThreads("c1") }), {
wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>
<ConversationActivityContext value={false}><ConversationPresentationContext value={presented}>{children}</ConversationPresentationContext></ConversationActivityContext>
@@ -57,7 +61,7 @@ it("reuses the entry-provided Forum first page instead of starting a parallel th
owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })
owner.client.removeQueries({ queryKey: communityKeys.forumFeed("c1", null), exact: true })
let release!: () => void
- load.mockImplementation((url: string) => url.includes("entry=1") ? new Promise(resolve => { release = () => resolve(value) }) : { tags: [] })
+ load.mockImplementation(async (url: string) => url.includes("entry=1") ? new Promise(resolve => { release = () => resolve(value) }) : { tags: [] })
const hook = renderHook(() => useForumFeed("s1", "c1"), {
wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>,
})
@@ -71,8 +75,8 @@ it("reuses the entry-provided Forum first page instead of starting a parallel th
it("shares account collections with subscribed consumers without refreshing them on consumer mount", async () => {
const owner = await createCommunityQueryOwner()
- load.mockImplementation((url: string) => url.endsWith("/accepted") ? { friends: [] }
- : url.endsWith("/blocked") ? { blocked: [] } : url.endsWith("/pending") ? { pending: [] }
+ load.mockImplementation(async (url: string) => url.endsWith("/accepted") ? friendBucketScenarioFixture("friends", [])
+ : url.endsWith("/blocked") ? friendBucketScenarioFixture("blocked", []) : url.endsWith("/pending") ? friendBucketScenarioFixture("pending", [])
: url.endsWith("/dms") ? { conversations: [] } : [])
const wrapper = ({ children }: { children: React.ReactNode }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>
const consumer = renderHook(() => ({ friends: useFriends({ enabled: false }), settings: useNotificationSettings(false), dms: useDms(false, true) }), { wrapper })
@@ -96,7 +100,7 @@ it("shares account collections with subscribed consumers without refreshing them
it("reads the complete active threads only on panel demand and keeps pin status available while closed", async () => {
const owner = await createCommunityQueryOwner()
let requested = false
- load.mockImplementation((url: string) => url.endsWith("/pins") ? { pins: [] } : { serverId: "s1", parentType: "text", threads: [], included: { parentMessages: [], firstMessages: [], tags: [], participants: [] } })
+ load.mockImplementation(async (url: string) => url.endsWith("/pins") ? emptyPins() : emptyThreads())
const hook = renderHook(() => ({ threads: useThreads("c1", requested), pins: usePins("c1") }), {
wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>,
})
diff --git a/src/web/src/hooks/community/facade-membership-composition.dom.test.ts b/src/web/src/hooks/community/facade-membership-composition.dom.test.ts
index bca672bc5..ea5d68f85 100644
--- a/src/web/src/hooks/community/facade-membership-composition.dom.test.ts
+++ b/src/web/src/hooks/community/facade-membership-composition.dom.test.ts
@@ -1,3 +1,5 @@
+import { serverMembersReadFixture, friendBucketScenarioFixture, staleFriendBucketFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION, CommunityMembersReadSchema } from "@alook/shared"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -26,16 +28,16 @@ beforeEach(() => async () => {
})
function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }
function buckets(url: string) {
- if (url.endsWith("/blocked")) return { blocked: [] }
- if (url.endsWith("/pending")) return { pending: [] }
+ if (url.endsWith("/blocked")) return friendBucketScenarioFixture("blocked", [])
+ if (url.endsWith("/pending")) return friendBucketScenarioFixture("pending", [])
throw new Error("unexpected " + url)
}
describe("membership facade composition", () => {
it("pages the canonical server roster before subtracting channel members", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
- if (new URL(url, "https://alook.test").searchParams.get("cursor") === "next") return { members: [bob], hasMore: false }
- if (url.includes("/servers/s1/members?")) return { members: [alice], hasMore: true, cursor: "next" }
- if (url === "/api/community/channels/c1/members?relation=access") return { members: [alice] }
+ if (new URL(url, "https://alook.test").searchParams.get("cursor") === "next") return serverMembersReadFixture("s1", [bob])
+ if (url.includes("/servers/s1/members?")) return serverMembersReadFixture("s1", [alice], { hasMore: true, cursor: "next" })
+ if (url === "/api/community/channels/c1/members?relation=access") return CommunityMembersReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", relation: "access", members: [{ channelId: "c1", userId: alice.userId, relation: "access", memberId: alice.id, role: alice.role, source: alice.source, isCreator: alice.isCreator }], profiles: [{ id: alice.userId, name: alice.name, discriminator: alice.discriminator, avatar: alice.avatar, avatarVersion: alice.avatarVersion }] })
return buckets(url)
})
const rendered = renderHook(() => useAddableMembers("s1", "c1"), { wrapper: Owner })
@@ -47,8 +49,8 @@ describe("membership facade composition", () => {
it("subtracts canonical server members from accepted friends", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
- if (url === "/api/community/friends/accepted") return { friends: [{ ...alice, id: "friend_1" }, { ...bob, id: "friend_2" }] }
- if (url.includes("/api/community/servers/s1/members?")) return { members: [alice], hasMore: false }
+ if (url === "/api/community/friends/accepted") return friendBucketScenarioFixture("friends", [{ ...alice, id: "friend_1" }, { ...bob, id: "friend_2" }])
+ if (url.includes("/api/community/servers/s1/members?")) return serverMembersReadFixture("s1", [alice])
return buckets(url)
})
const rendered = renderHook(() => useInvitableFriends("s1"), { wrapper: Owner })
@@ -59,8 +61,8 @@ describe("membership facade composition", () => {
it("rejects a stale accepted-friends read instead of caching a false-empty candidate set", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
- if (url === "/api/community/friends/accepted") return { friends: [], stale: true }
- if (url.includes("/api/community/servers/s1/members?")) return { members: [], hasMore: false }
+ if (url === "/api/community/friends/accepted") return staleFriendBucketFixture("friends")
+ if (url.includes("/api/community/servers/s1/members?")) return serverMembersReadFixture("s1", [])
return buckets(url)
})
const rendered = renderHook(() => useInvitableFriends("s1"), { wrapper: Owner })
@@ -71,14 +73,14 @@ describe("membership facade composition", () => {
it("keeps last-good candidates when a QueryClient refetch gets a stale response", async () => {
apiFetchMock.mockImplementation(async (url: string) => {
- if (url === "/api/community/friends/accepted") return { friends: [{ ...bob, id: "friend_2" }] }
- if (url.includes("/api/community/servers/s1/members?")) return { members: [], hasMore: false }
+ if (url === "/api/community/friends/accepted") return friendBucketScenarioFixture("friends", [{ ...bob, id: "friend_2" }])
+ if (url.includes("/api/community/servers/s1/members?")) return serverMembersReadFixture("s1", [])
return buckets(url)
})
const rendered = renderHook(() => useInvitableFriends("s1"), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.friends).toHaveLength(1))
const lastGood = client.getQueryData(communityKeys.invitableFriends("s1"))
- apiFetchMock.mockImplementation(async (url: string) => url === "/api/community/friends/accepted" ? { friends: [], stale: true } : url.includes("/members?") ? { members: [], hasMore: false } : buckets(url))
+ apiFetchMock.mockImplementation(async (url: string) => url === "/api/community/friends/accepted" ? staleFriendBucketFixture("friends") : url.includes("/members?") ? serverMembersReadFixture("s1", []) : buckets(url))
await act(async () => { await rendered.result.current.refetch() })
await waitFor(() => expect(rendered.result.current.error).toMatchObject({ message: "stale D1 read" }))
expect(client.getQueryData(communityKeys.invitableFriends("s1"))).toBe(lastGood)
diff --git a/src/web/src/hooks/community/forum-feed-window.test.ts b/src/web/src/hooks/community/forum-feed-window.test.ts
index 69f0ea529..534231f08 100644
--- a/src/web/src/hooks/community/forum-feed-window.test.ts
+++ b/src/web/src/hooks/community/forum-feed-window.test.ts
@@ -1,9 +1,10 @@
import { describe, expect, it } from "vitest"
-import { communityReadSchemas } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, communityReadSchemas } from "@alook/shared"
import { normalizeThreadResources } from "./forum-feed-window"
describe("versioned forum resource normalization", () => {
- it.each([2, 3] as const)("preserves contract %s resources, scopes and pagination", (contractVersion) => {
+ it("preserves current resources, scopes and pagination", () => {
+ const contractVersion = BUSINESS_SCHEMA_VERSION
const channel = { id: "forum", type: "forum", serverId: "server", name: "Forum", topic: "Topic", categoryId: null,
parentChannelId: null, parentMessageId: null, creatorId: "author", position: 0, archived: false, createdAt: "now", lastMessageAt: null, messageCount: 1 }
const message = { id: "opener", channelId: "forum", seq: 1, authorId: "author", authorName: "Author", authorAvatarVersion: 0,
@@ -12,18 +13,18 @@ describe("versioned forum resource normalization", () => {
const body = communityReadSchemas(contractVersion).threads.parse({ contractVersion, channelId: "forum", channel,
threads: [{ ...channel, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener" }],
included: { messages: [message, { ...message, id: "reply", channelId: "thread", content: "Reply" }],
- profiles: [contractVersion === 2 ? { ...profile, statusEmoji: "😀", statusText: "Available" } : profile],
+ profiles: [profile],
members: [{ channelId: "thread", userId: "author", relation: "notify", source: "spoke", isCreator: true, role: null, memberId: null }], tags: [{ messageId: "opener", tag: "bug" }],
participantCounts: [{ channelId: "thread", count: 1 }] }, page: { hasMore: true, nextCursor: "cursor" } })
const result = normalizeThreadResources("forum", body)
expect(result.channel).toEqual(channel)
- expect(result.threads).toEqual(body.threads.map((thread) => ({ ...thread, resourceComplete: true })))
- expect(result.included.messages).toEqual(body.included.messages.map((row) => ({ ...row, resourceComplete: contractVersion === 3 })))
+ expect(result.threads).toEqual(body.threads)
+ expect(result.included.messages).toEqual(body.included.messages)
expect(result.included.profiles).toEqual([profile])
expect(result.included.previews).toEqual([body.included.messages[1]])
expect(result.included.members).toEqual(body.included.members)
expect(result.page).toEqual(body.page)
- expect(() => normalizeThreadResources("forum", { ...body, contractVersion: 4 } as never)).toThrow("Unknown thread resource contract")
+ for (const version of [1, 2, 3]) expect(() => normalizeThreadResources("forum", { ...body, contractVersion: version })).toThrow()
expect(() => normalizeThreadResources("forum", { ...body, threads: [{ ...body.threads[0], messageCount: -1 }] } as never)).toThrow()
})
})
diff --git a/src/web/src/hooks/community/forum-feed-window.ts b/src/web/src/hooks/community/forum-feed-window.ts
index 1bd5a3ff3..22739e688 100644
--- a/src/web/src/hooks/community/forum-feed-window.ts
+++ b/src/web/src/hooks/community/forum-feed-window.ts
@@ -1,8 +1,6 @@
-import { FORUM_ARCHIVE_TAG, CommunityChannelResourceSchema, CommunityMessagePreviewSchema, CommunityMessageResourceSchema, communityReadSchemas, communityMessagePreviewFromLegacy, type CommunityLegacyThreadsRead, type CommunityChannelResource, type CommunityThreadsRead, type CommunityMessageResource, type CommunityResourceProfile, type CommunityMemberRelation } from "@alook/shared"
-import { canonicalUserImage } from "@/lib/community/storage"
+import { FORUM_ARCHIVE_TAG, communityReadSchemas, type CommunityChannelResource, type CommunityThreadsRead, type CommunityMessageResource, type CommunityMemberRelation } from "@alook/shared"
import type { InfiniteData } from "@tanstack/react-query"
-import { threadParticipantResources } from "@/lib/community/participant-resources"
-import type { MessageInput, Msg, Thread } from "@/lib/community/models/message"
+import type { Msg, Thread } from "@/lib/community/models/message"
import type { ChannelRow } from "@/lib/community-db/schema"
export function projectThread(thread: ChannelRow, opener: Msg | undefined, parentType: string): Thread {
@@ -16,63 +14,17 @@ export function projectThread(thread: ChannelRow, opener: Msg | undefined, paren
}
}
-export type ForumFeedTransportPage = Pick<CommunityThreadsRead["page"], "hasMore"> & {
- serverId: NonNullable<CommunityChannelResource["serverId"]>
- parentType: string
- threads: Array<Pick<CommunityChannelResource, "id" | "name" | "creatorId" | "parentMessageId" | "lastMessageAt" | "createdAt"> & {
- messageCount: CommunityChannelResource["messageCount"] | null
- activityAt: string
- }>
- included: {
- parentMessages: Array<Required<Pick<CommunityMessageResource, "id" | "channelId" | "seq" | "content" | "authorId" | "authorName" | "authorAvatarVersion">> & Partial<Pick<CommunityMessageResource, "createdAt">> & { authorImage: CommunityResourceProfile["avatar"] }>
- firstMessages: Array<Pick<CommunityMessageResource, "channelId" | "content">>
- tags: CommunityThreadsRead["included"]["tags"]
- participants: Array<Pick<CommunityMemberRelation, "channelId" | "userId"> & { userName: CommunityResourceProfile["name"] | null; discriminator?: CommunityResourceProfile["discriminator"]; userImage: CommunityResourceProfile["avatar"]; userAvatarVersion: CommunityResourceProfile["avatarVersion"]; participantCount?: number }>
- }
- nextCursor?: NonNullable<CommunityThreadsRead["page"]["nextCursor"]>
-}
+export type ForumFeedTransportPage = CommunityThreadsRead
-export type CommunityThreadResources = {
- channel: Pick<CommunityChannelResource, "id" | "serverId" | "type">
- threads: Array<Pick<CommunityChannelResource, "id"> & Partial<Omit<CommunityChannelResource, "id">> & { resourceComplete?: boolean }>
- included: Omit<CommunityThreadsRead["included"], "messages" | "profiles"> & { profiles: Array<Pick<CommunityResourceProfile, "id"> & Partial<Omit<CommunityResourceProfile, "id">>>; messages: Array<MessageInput & { channelId: string }>; previews: Array<Pick<CommunityMessageResource, "channelId" | "content"> & Partial<Pick<CommunityMessageResource, "id">>> }
- page: CommunityThreadsRead["page"]
+export type CommunityThreadResources = Omit<CommunityThreadsRead, "included"> & {
+ included: CommunityThreadsRead["included"] & { previews: CommunityMessageResource[] }
}
-export function normalizeThreadResources(channelId: string, value: ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead): CommunityThreadResources {
- if ("contractVersion" in value) {
- if (value.contractVersion !== 2 && value.contractVersion !== 3) throw new Error("Unknown thread resource contract")
- const data = communityReadSchemas(value.contractVersion).threads.parse(value)
- return {
- ...data, threads: data.threads.map((thread) => ({ ...CommunityChannelResourceSchema.parse(thread), resourceComplete: true })),
- included: { ...data.included,
- messages: data.included.messages.map((message) => data.contractVersion === 3
- ? { ...CommunityMessageResourceSchema.parse(message), channelId: message.channelId, resourceComplete: true }
- : { ...communityMessagePreviewFromLegacy(message, message.channelId), channelId: message.channelId, resourceComplete: false }),
- profiles: data.contractVersion === 3 ? data.included.profiles : data.included.profiles.map(({ statusEmoji: _emoji, statusText: _text, ...identity }) => identity),
- previews: data.included.messages.filter((message) => message.channelId !== channelId),
- },
- }
- }
- const participants = threadParticipantResources(value.included.participants.map((participant) => ({
- channelId: participant.channelId, userId: participant.userId, participantCount: participant.participantCount,
- isCreator: value.threads.some((thread) => thread.id === participant.channelId && thread.creatorId === participant.userId),
- profile: { id: participant.userId, ...(participant.userName !== null ? { name: participant.userName } : {}), ...(participant.discriminator ? { discriminator: participant.discriminator } : {}), avatar: canonicalUserImage(participant.userId, participant.userImage, participant.userAvatarVersion), avatarVersion: participant.userAvatarVersion },
- })))
- return {
- channel: { id: channelId, serverId: value.serverId, type: value.parentType === "forum" ? "forum" : "text" },
- threads: value.threads.map(({ activityAt: _activity, messageCount, ...thread }) => ({
- ...thread, type: "thread", serverId: value.serverId, parentChannelId: channelId,
- ...(messageCount === null ? {} : { messageCount }), resourceComplete: false,
- })),
- included: {
- messages: value.included.parentMessages.map(({ authorImage, ...message }) => ({
- ...CommunityMessagePreviewSchema.partial({ type: true }).parse({ ...message, channelId, authorAvatar: canonicalUserImage(message.authorId, authorImage, message.authorAvatarVersion) }), channelId, resourceComplete: false,
- })),
- previews: value.included.firstMessages, tags: value.included.tags, ...participants,
- },
- page: { hasMore: value.hasMore, nextCursor: value.nextCursor ?? null },
- }
+export function normalizeThreadResources(channelId: string, value: unknown): CommunityThreadResources {
+ const data = communityReadSchemas().threads.parse(value)
+ if (data.channelId !== channelId || data.channel.id !== channelId
+ || data.threads.some(thread => thread.parentChannelId !== channelId || thread.serverId !== data.channel.serverId)) throw new Error("Thread resource scope mismatch")
+ return { ...data, included: { ...data.included, previews: data.included.messages.filter(message => message.channelId !== channelId) } }
}
export type ForumFeedPage = Pick<CommunityThreadsRead["page"], "hasMore"> & {
diff --git a/src/web/src/hooks/community/forum-sidebar-owner.dom.test.tsx b/src/web/src/hooks/community/forum-sidebar-owner.dom.test.tsx
index 5079824d4..bedba7a40 100644
--- a/src/web/src/hooks/community/forum-sidebar-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/forum-sidebar-owner.dom.test.tsx
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { channelResourceFixture, messageResourceFixture, serverResourceFixture, fullResourceBundleFixture, serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -22,9 +24,16 @@ function Root({ id = sdk.id, consumers = 2 }: { id?: string; consumers?: number
type Request = { signal: AbortSignal; authenticationAccount?: string; resolve: (value: unknown) => void }
const requests: Request[] = []
function seedForum(current: QueryClient) {
- ingestServerDetail(getCommunityDbRegistry(current)!, { id: "server", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: sdk.id, categories: [{ id: "category", name: "Channels", channels: [{ id: "forum", name: "Forum", type: "forum", active: false, unread: false }] }] })
+ ingestServerDetail(getCommunityDbRegistry(current)!, serverDirectoryFixture({ id: "server", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: sdk.id, categories: [{ id: "category", name: "Channels", channels: [{ id: "forum", name: "Forum", type: "forum", active: false, unread: false }] }] }))
+}
+function envelope(content: string, viewerId = "A") {
+ const now = new Date().toISOString()
+ const parent = channelResourceFixture({ id: "forum", serverId: "server", type: "forum" })
+ const child = channelResourceFixture({ id: "child", serverId: "server", type: "thread", name: "Thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "peer", lastMessageAt: now })
+ const channel = { id: "child", serverId: "server", name: "Thread", parentChannelId: "forum", parentMessageId: "opener", activityAt: now, expiresAt: new Date(Date.now() + 72 * 3600_000).toISOString(), unread: false }
+ return { schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: "server", channels: [channel], canonicalChannels: [channel], retainedChannel: null, retainedDisposition: null,
+ resources: fullResourceBundleFixture(viewerId, [serverResourceFixture({ id: "server", ownerId: viewerId, isOwner: true })], [parent, child], [messageResourceFixture({ id: "opener", channelId: "forum", content })]), serverNow: now }
}
-function envelope(content: string) { return { channels: [{ id: "child", serverId: "server", type: "thread", name: "Thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "peer", archived: false, activityAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 72 * 3600_000).toISOString(), unread: false }], included: { parentMessages: [{ id: "opener", content, seq: 1, channelId: "forum", type: "chat" }] }, serverNow: new Date().toISOString() } }
beforeEach(async () => { await clearAllPersistedCaches(); requests.length = 0; api.mockReset(); sdk.id = "A"; api.mockImplementation((_path: string, options: Omit<Request, "resolve">) => new Promise((resolve) => { requests.push({ ...options, resolve }) })) })
describe("actual native forum sidebar reads", () => {
it("deduplicates StrictMode consumers and publishes canonical sidebar rows with metadata-only transport", async () => {
@@ -53,7 +62,7 @@ describe("actual native forum sidebar reads", () => {
await waitFor(() => expect(client).not.toBe(original))
await waitFor(() => expect(requests).toHaveLength(2))
expect(requests[1].authenticationAccount).toBe("B")
- await act(async () => { seedForum(client); requests[1].resolve(envelope("B own")); await new Promise((done) => setTimeout(done, 0)) })
+ await act(async () => { seedForum(client); requests[1].resolve(envelope("B own", "B")); await new Promise((done) => setTimeout(done, 0)) })
await waitFor(() => expect(screen.getByTestId("sidebar-0").textContent).toBe("B own"))
await act(async () => { requests[0].resolve(envelope("late A")); await new Promise((done) => setTimeout(done, 0)) })
expect(screen.getByTestId("sidebar-0").textContent).toBe("B own")
diff --git a/src/web/src/hooks/community/friend-read-owner.dom.test.tsx b/src/web/src/hooks/community/friend-read-owner.dom.test.tsx
index 92fad2672..c63b8a921 100644
--- a/src/web/src/hooks/community/friend-read-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/friend-read-owner.dom.test.tsx
@@ -1,3 +1,4 @@
+import { channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -38,7 +39,22 @@ const probes = {
}
type Kind = keyof typeof probes
const kinds = Object.keys(probes) as Kind[]
-function Root({ kind, consumers = 2 }: { kind: Kind; consumers?: number }) { const Probe = probes[kind]; return <QueryProvider userId="A">{Array.from({ length: consumers }, (_, index) => <Probe key={index} />)}</QueryProvider> }
+function ReactionScope({ children }: { children: React.ReactNode }) {
+ const qc = useQueryClient(), registry = getCommunityDbRegistry(qc)!
+ const [ready, setReady] = React.useState(false)
+ React.useEffect(() => {
+ let active = true
+ void (async () => {
+ await registry.ready; await registry.preload()
+ registry.collections.channels.utils.writeUpsert({ ...channelResourceFixture({ id: "channel", serverId: "server" }), muted: false, pending: false, tags: [] })
+ registry.collections.messages.utils.writeUpsert(messageResourceFixture({ id: "message", channelId: "channel" }))
+ if (active) setReady(true)
+ })()
+ return () => { active = false }
+ }, [registry])
+ return ready ? children : null
+}
+function Root({ kind, consumers = 2 }: { kind: Kind; consumers?: number }) { const Probe = probes[kind]; const children = Array.from({ length: consumers }, (_, index) => <Probe key={index} />); return <QueryProvider userId="A">{kind === "reactions" ? <ReactionScope>{children}</ReactionScope> : children}</QueryProvider> }
const peer = { id: "peer", userId: "peer", name: "Late Peer", discriminator: "0001", avatar: "", avatarVersion: 0, status: "offline", sub: "" }
function response(path: string) {
if (path.endsWith("accepted")) return { friends: [{ ...peer, id: "friendship" }] }
diff --git a/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
index f23373d3c..0e8bf2392 100644
--- a/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
+++ b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
@@ -1,3 +1,4 @@
+import { resourceBundleFixture, friendBucketScenarioFixture } from "@/test/community-resource-fixtures"
import { useAccountAttentionProjection, reconcileAccountAttention } from "./use-account-attention"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { publishCommunityFriendships, publishAccountAttentionSnapshot, captureCommunityLiveSnapshotToken, projectCommunityWsEventToDb } from "@/lib/community-db/sync"
@@ -71,8 +72,11 @@ function friendsData(ids: readonly string[]): FriendsResponse {
}
}
+function friendResources(ids: readonly string[]) {
+ return resourceBundleFixture({ profiles: pendingRows.filter(row => ids.includes(row.id)).map(row => ({ id: row.userId, name: row.name, discriminator: "0001", avatar: null, avatarVersion: row.avatarVersion ?? 0 })) })
+}
function attentionData(ids: readonly string[]) {
- return {
+ return { resources: friendResources(ids),
scopes: [], limit: 100, truncated: false,
items: inboxRows.filter((row) => ids.includes(row.id)).map((row) => ({ id: `friend_request:${row.id}`, kind: "friend_request" as const, sourceId: row.id, actorUserId: row.userId, createdAt: row.createdAt })),
included: { servers: [], channels: [], dms: [], messages: [], profiles: inboxRows.filter((row) => ids.includes(row.id)).map((row) => ({ userId: row.userId, name: row.name, discriminator: "0001", avatar: row.avatar, avatarVersion: row.avatarVersion ?? 0 })) },
@@ -97,11 +101,11 @@ function installTransport(transport: Transport) {
apiFetchMock.mockImplementation(async (path: string) => {
const action = path.match(/^\/api\/community\/friends\/([^/]+)\/(accept|reject)$/)
if (action) return transport.action(action[1]!)
- if (path === "/api/community/friends/accepted") return { friends: [] }
- if (path === "/api/community/friends/blocked") return { blocked: [] }
+ if (path === "/api/community/friends/accepted") return friendBucketScenarioFixture("friends", [])
+ if (path === "/api/community/friends/blocked") return friendBucketScenarioFixture("blocked", [])
if (path === "/api/community/friends/pending") {
const ids = await transport.readFriends()
- return { pending: pendingRows.filter((row) => ids.includes(row.id)) }
+ return friendBucketScenarioFixture("pending", pendingRows.filter((row) => ids.includes(row.id)).map(row => ({ ...row, discriminator: "0001" })))
}
if (path === "/api/community/users/me/attention") {
return attentionData(await transport.readInbox())
diff --git a/src/web/src/hooks/community/inbox-read-reservation.test.ts b/src/web/src/hooks/community/inbox-read-reservation.test.ts
index c58233aa0..329822e61 100644
--- a/src/web/src/hooks/community/inbox-read-reservation.test.ts
+++ b/src/web/src/hooks/community/inbox-read-reservation.test.ts
@@ -1,8 +1,9 @@
+import { serverDirectoryFixture, messageResourceFixture, channelResourceFixture, resourceBundleFixture } from "@/test/community-resource-fixtures"
import { QueryClient, QueryObserver } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { getCommunityDbRegistry, createCommunityDbRegistry, registerCommunityDbRegistry } from "@/lib/community-db/collections"
-import { ingestServerDetail, ingestMessages, ingestAttentionSnapshot, captureCommunityLiveSnapshotToken, publishCommunityChannelFields } from "@/lib/community-db/sync"
+import { ingestServerDetail, ingestMessages, ingestAttentionSnapshot, captureCommunityLiveSnapshotToken, publishCommunityChannelFields, publishCommunityChannelMetadata } from "@/lib/community-db/sync"
import {
activateInboxProjectionTicket,
armInboxReadReservationCandidate,
@@ -59,15 +60,16 @@ async function seedProjection(queryClient: QueryClient, data: {
const channels = server.channels.flatMap((parent) => {
scopes.push({ scopeId: parent.channelId, channelId: parent.channelId, serverId, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 7, lastAttentionSeq: null, attentionCount: 0 })
for (const child of parent.children ?? []) if (child.openerUnread && child.openerMessageId && child.openerSeq !== undefined) {
- ingestMessages(registry, parent.channelId, [{ id: child.openerMessageId, type: "chat", seq: child.openerSeq, createdAt: child.lastMessageAt }])
+ ingestMessages(registry, parent.channelId, [messageResourceFixture({ id: child.openerMessageId, channelId: parent.channelId, authorId: "user-1", type: "chat", seq: child.openerSeq, createdAt: child.lastMessageAt })])
items.push({ id: "forum:" + child.channelId, kind: "forum_post", sourceId: child.channelId, scopeId: parent.channelId, childChannelId: child.channelId, messageId: child.openerMessageId, openerSeq: child.openerSeq, readTarget: { channelId: parent.channelId, seq: child.openerSeq }, createdAt: child.lastMessageAt })
}
return [{ id: parent.channelId, name: parent.channelId, type: parent.children?.length ? "forum" as const : "text" as const, active: false, unread: true, lastMessageAt: parent.lastMessageAt }, ...(parent.children ?? []).map((child) => ({ id: child.channelId, name: child.channelId, type: "thread" as const, active: false, unread: true, lastMessageAt: child.lastMessageAt, parentChannelId: parent.channelId, parentMessageId: child.openerMessageId }))]
})
- ingestServerDetail(registry, { id: serverId, name: serverId, discriminator: "0001", description: "", icon: null, ownerId: "user-1", categories: [{ id: "category:" + serverId, name: "Category", channels }] })
+ ingestServerDetail(registry, serverDirectoryFixture({ id: serverId, name: serverId, discriminator: "0001", description: "", icon: null, ownerId: "user-1", categories: [{ id: "category:" + serverId, name: "Category", channels: channels.filter(channel => !channel.parentChannelId) }] }))
+ for (const channel of channels.filter(channel => channel.parentChannelId)) publishCommunityChannelMetadata(queryClient, { metadata: channelResourceFixture({ id: channel.id, serverId, name: channel.name, type: "thread", parentChannelId: channel.parentChannelId, parentMessageId: channel.parentMessageId, lastMessageAt: channel.lastMessageAt }), proof: { token: captureCommunityLiveSnapshotToken(queryClient) } })
for (const channel of channels) publishCommunityChannelFields(queryClient, channel.id, { lastMessageAt: channel.lastMessageAt }, { token: captureCommunityLiveSnapshotToken(queryClient) })
}
- ingestAttentionSnapshot(registry, { scopes, items, limit: 100, truncated: false })
+ ingestAttentionSnapshot(registry, { resources: resourceBundleFixture({ viewerId: "user-1" }), scopes, items, limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } })
}
function response(channelId = "focused", lastMessageAt = "2026-08-27T01:00:00.000Z") {
diff --git a/src/web/src/hooks/community/member-null-identity.dom.test.tsx b/src/web/src/hooks/community/member-null-identity.dom.test.tsx
new file mode 100644
index 000000000..ec2a20666
--- /dev/null
+++ b/src/web/src/hooks/community/member-null-identity.dom.test.tsx
@@ -0,0 +1,50 @@
+import { serverMembersReadFixture } from "@/test/community-resource-fixtures"
+import { createElement, type PropsWithChildren } from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { renderHook, waitFor } from "@/test/react-dom-harness"
+import { useChannelMembers } from "./use-channel-members"
+import { useServerMembers } from "./use-server-members"
+
+const load = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => load(...args), toastApiError: vi.fn() }))
+beforeEach(() => load.mockReset())
+
+const profile = { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 3 }
+const useChannel = () => useChannelMembers("channel", true, "server", "access")
+const useServer = () => useServerMembers("server")
+const member = { channelId: "channel", userId: "peer", relation: "access" as const, source: "explicit" as const,
+ memberId: "member-peer", role: "member", isCreator: false }
+
+describe("current nullable identity through actual member hooks", () => {
+ it.each(["channel", "server"] as const)("completes the %s member read with a real NULL discriminator", async surface => {
+ const owner = await createCommunityQueryOwner()
+ load.mockResolvedValue(surface === "channel"
+ ? { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "channel", relation: "access", members: [member], profiles: [profile] }
+ : serverMembersReadFixture("server", [{ ...profile, id: member.memberId, userId: profile.id, role: "member", sub: "", status: "offline" }], { limit: 50 }))
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client }, children)
+ const hook = renderHook(() => (surface === "channel" ? useChannel : useServer)(), { wrapper })
+ await waitFor(() => expect(hook.result.current.loading).toBe(false))
+ expect(hook.result.current.failed).toBe(false)
+ expect(hook.result.current.members).toEqual([expect.objectContaining({ userId: "peer", name: "Peer", discriminator: "0042" })])
+ expect(owner.registry.collections.profiles.get("peer")).toMatchObject(profile)
+ hook.unmount()
+ })
+
+ it.each(["channel", "server"] as const)("keeps a genuinely absent %s profile failed without a fake identity", async surface => {
+ const owner = await createCommunityQueryOwner()
+ owner.runtime.ws.actions.setPresence("peer", "online")
+ expect(owner.runtime.ws.get().presenceByUserId.get("peer")).toBe("online")
+ load.mockResolvedValue(surface === "channel"
+ ? { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "channel", relation: "access", members: [member], profiles: [] }
+ : { viewerId: "viewer", serverId: "server", members: [{ id: member.memberId, userId: profile.id, role: "member" }], hasMore: false, total: 1, limit: 50 })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client }, children)
+ const hook = renderHook(() => (surface === "channel" ? useChannel : useServer)(), { wrapper })
+ await waitFor(() => expect(hook.result.current.loading).toBe(false))
+ expect(hook.result.current.failed).toBe(true)
+ expect(owner.registry.collections.profiles.has("peer")).toBe(false)
+ hook.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/member-read.status.test.ts b/src/web/src/hooks/community/member-read.status.test.ts
new file mode 100644
index 000000000..13c59af31
--- /dev/null
+++ b/src/web/src/hooks/community/member-read.status.test.ts
@@ -0,0 +1,35 @@
+import { afterEach, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { communityKeys } from "@/lib/query-keys"
+import { membersPageQueryFn } from "./use-server-members"
+
+const state = vi.hoisted(() => ({ db: null as unknown, wire: null as unknown }))
+vi.mock("@/lib/db", () => ({ getDb: () => state.db }))
+vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) => (req: NextRequest) => handler(req, { env: {}, actor: { kind: "human", userId: "viewer" }, params: { id: "server" } }) }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: async () => {
+ const response = await GET(new NextRequest("https://app.example.test/api/community/servers/server/members"), {} as never)
+ if (!response.ok) throw new Error(`Actual member producer refused ${response.status}`)
+ state.wire = await response.json()
+ return state.wire
+}, toastApiError: vi.fn() }))
+import { GET } from "@/app/api/community/servers/[id]/members/route"
+
+const fixtures: ReturnType<typeof createCommunitySqliteDb>[] = []
+afterEach(() => { for (const fixture of fixtures) fixture.sqlite.close(); fixtures.length = 0 })
+it("preserves real SQL NULL member status through the actual producer, query and warm canonical profile", async () => {
+ const fixture = createCommunitySqliteDb(); fixtures.push(fixture); state.db = fixture.db
+ const { sqlite } = fixture
+ const stamp = "2026-10-28T00:00:00Z"
+ for (const id of ["viewer", "peer"]) sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt") VALUES (?,?,?,?,0,?,?)').run(id, `${id}@example.test`, id, "0042", stamp, stamp)
+ sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES ('server','Server','0042','','viewer',?)").run(stamp)
+ for (const id of ["viewer", "peer"]) sqlite.prepare("INSERT INTO community_server_member (id,server_id,user_id,role,joined_at) VALUES (?,'server',?,'member',?)").run(`member-${id}`, id, stamp)
+ sqlite.exec("INSERT INTO community_user_profile (user_id,status_text,status_emoji) VALUES ('peer',NULL,NULL)")
+ expect(sqlite.prepare("SELECT status_text FROM community_user_profile WHERE user_id='peer'").get()).toEqual({ status_text: null })
+ const { client, registry } = await createCommunityQueryOwner()
+ registry.collections.profiles.utils.writeUpsert({ id: "peer", name: "peer", discriminator: "0042", avatar: null, avatarVersion: 0, statusText: "Stale cached status" })
+ await client.query({ queryKey: communityKeys.members("server"), queryFn: ({ signal }) => membersPageQueryFn("server")({ pageParam: null, client, signal }) })
+ const wire = state.wire as { members: Array<{ userId: string; statusText: string | null }> }
+ expect({ wire: wire.members.find(row => row.userId === "peer")?.statusText, canonical: registry.collections.profiles.get("peer")?.statusText }).toEqual({ wire: null, canonical: null })
+})
diff --git a/src/web/src/hooks/community/message-surface-ownership.test.ts b/src/web/src/hooks/community/message-surface-ownership.test.ts
index 2dc844100..c8c790624 100644
--- a/src/web/src/hooks/community/message-surface-ownership.test.ts
+++ b/src/web/src/hooks/community/message-surface-ownership.test.ts
@@ -1,3 +1,5 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { channelResourceFixture, messageResourceFixture, forumFeedScenarioFixture } from "@/test/community-resource-fixtures"
import { QueryClient } from "@tanstack/react-query"
import { afterEach, describe, expect, it } from "vitest"
import type { CommunityWsEvent } from "@alook/shared"
@@ -49,7 +51,8 @@ describe("embedded message surface ownership", () => {
registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
unregister = registerCommunityDbRegistry(registry)
- const transport: Msg = {
+ const transport = messageResourceFixture({
+ channelId: "c1",
id: "m1",
type: "chat",
seq: 1,
@@ -57,14 +60,14 @@ describe("embedded message surface ownership", () => {
authorName: "Author",
content: "initial",
createdAt: "2026-09-26T00:00:00.000Z",
- }
+ })
const transportSurfaces = {
mentions: [transport],
marked: [transport],
pins: [transport],
context: [transport],
}
- const forumPage: ForumFeedTransportPage = {
+ const forumPage: ForumFeedTransportPage = forumFeedScenarioFixture("c1", {
serverId: "s1",
parentType: "forum",
threads: [{
@@ -94,7 +97,7 @@ describe("embedded message surface ownership", () => {
participants: [],
},
hasMore: false,
- }
+ })
const threads: ThreadsResponse = {
threads: [{
id: "post-1",
@@ -118,12 +121,13 @@ describe("embedded message surface ownership", () => {
})
expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
- publishCommunityCreatedChannel(queryClient, {
+ publishCommunityCreatedChannel(queryClient, channelResourceFixture({
id: "post-1", serverId: "s1", parentChannelId: "c1", parentMessageId: "m1", name: "transport", type: "thread", position: 0,
- archived: false, muted: false, unread: false, tags: [], pending: false, createdAt: transport.createdAt,
- }, { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined })
+ archived: false, creatorId: "author", messageCount: 1, createdAt: transport.createdAt,
+ }), { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined })
publishCommunityEmbeddedMessages(queryClient, {
entries: [{ channelId: "c1", message: transport }],
+ profiles: messageProfilesFixture([transport]),
proof: {
token: captureCommunityLiveSnapshotToken(queryClient),
signal: undefined,
@@ -149,7 +153,7 @@ describe("embedded message surface ownership", () => {
})
})
- it("normalizes legacy embedded messages that omit the transport type", async () => {
+ it("rejects incomplete type-less embedded messages without canonical publication", async () => {
const queryClient = new QueryClient()
registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
@@ -161,15 +165,11 @@ describe("embedded message surface ownership", () => {
createdAt: "2026-09-26T00:00:00.000Z",
} as Msg
- expect(publishCommunityEmbeddedMessages(queryClient, {
+ 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" }),
- ])
+ profiles: messageProfilesFixture([transport]),
+ proof: { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined },
+ })).toThrow()
+ expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
})
})
diff --git a/src/web/src/hooks/community/message-window.reentry.dom.test.tsx b/src/web/src/hooks/community/message-window.reentry.dom.test.tsx
new file mode 100644
index 000000000..ca51afc7b
--- /dev/null
+++ b/src/web/src/hooks/community/message-window.reentry.dom.test.tsx
@@ -0,0 +1,138 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { useLayoutEffect, type PropsWithChildren } from "react"
+import { QueryClientProvider } from "@tanstack/react-query"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { act, render, waitFor } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { dmConversationEntryFixture } from "@/test/conversation-entry-fixtures"
+import { CommunityDbProvider } from "@/lib/community-db/projections"
+import { communityKeys } from "@/lib/query-keys"
+import type { MessageWindowData } from "@/lib/community/message-window"
+import { currentConversationReadState } from "@/lib/community/conversation-entry"
+import { useDmMessages } from "./use-messages"
+import { reconcileWindow } from "./community-ws/reconnect-messages"
+
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
+
+async function wireOwner() {
+ const owner = await createCommunityQueryOwner()
+ const base = dmConversationEntryFixture()
+ const messages = Array.from({ length: 255 }, (_, index) => ({ ...base.messages[0], id: `m${index + 1}`, seq: index + 1,
+ content: `Message ${index + 1}`, createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString(),
+ }))
+ const read = { ...base.readState, lastReadMessageId: "m240", lastReadSeq: 240, lastReadAt: messages[239].createdAt }
+ const entry = { ...base, channel: { ...base.channel, messageCount: 240, lastMessageAt: messages[239].createdAt },
+ messages: messages.slice(214, 240), readState: read, readStateRevision: 121,
+ selection: { reason: "read_pointer" as const, anchorMessageId: "m240" },
+ page: { olderCursor: `${messages[214].createdAt}|m215`, newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 240 },
+ }
+ const requests: Array<{ query: string; version: string | null }> = []
+ let catchUp = false
+ let legacyPages = false
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, options?: RequestInit) => {
+ const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost")
+ if (url.pathname !== "/api/community/channels/c1/messages") throw new Error(`Unexpected wire request ${url.pathname}`)
+ const version = new Headers(input instanceof Request ? input.headers : options?.headers).get(COMMUNITY_CONTRACT_HEADER)
+ requests.push({ query: url.search, version })
+ if (url.searchParams.has("entry")) return new Response(JSON.stringify(entry), {
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), "content-type": "application/json" },
+ })
+ const cursor = url.searchParams.get("cursor")
+ const since = url.searchParams.get("since")
+ const before = cursor ? Number(cursor.split("|").at(-1)!.slice(1)) : 215
+ const selected = cursor ? messages.slice(Math.max(0, before - 51), before - 1)
+ : since ? messages.slice(240, catchUp ? 255 : 240) : messages.slice(214, 240)
+ const last = selected.at(-1)
+ const page = { olderCursor: selected[0] && selected[0].seq > 1 ? `${selected[0].createdAt}|${selected[0].id}` : null,
+ newerCursor: catchUp && !since ? `${messages[239].createdAt}|m240` : null,
+ hasMoreOlder: !!selected[0] && selected[0].seq > 1, hasMoreNewer: catchUp && !since,
+ latestSeq: catchUp ? 255 : last ? Math.max(240, last.seq) : 240,
+ }
+ const responseVersion = legacyPages ? "2" : version
+ return new Response(JSON.stringify({ contractVersion: Number(responseVersion), channelId: "c1",
+ profiles: base.profiles, messages: responseVersion === String(BUSINESS_SCHEMA_VERSION) ? selected : selected.map(message => ({ ...message, authorAvatar: "P" })),
+ page, surfaceReceipt: base.surfaceReceipt,
+ }), { headers: { [COMMUNITY_CONTRACT_HEADER]: responseVersion ?? "", "content-type": "application/json" } })
+ }))
+ let latest!: ReturnType<typeof useDmMessages>
+ function Probe() {
+ const feed = useDmMessages("c1", { viewerUserId: "viewer" })
+ useLayoutEffect(() => { latest = feed })
+ return <div data-testid="projected-rows">{feed.messages.map(message => <span key={message.id}>{message.id}</span>)}</div>
+ }
+ function Providers({ children }: PropsWithChildren) {
+ return <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>
+ }
+ const app = (active = true) => <Providers>{active ? <Probe /> : <div data-testid="away" />}</Providers>
+ const view = render(app())
+ await waitFor(() => expect(latest.messages).toHaveLength(26))
+ const key = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m240" })
+ return { ...owner, view, key, requests, get latest() { return latest }, app,
+ enableCatchUp: () => { catchUp = true }, forceLegacyPages: () => { legacyPages = true },
+ }
+}
+
+describe("complete message windows through the real HTTP decoder", () => {
+ it("retains three older pages and admits the same DM on ordinary remount", async () => {
+ const h = await wireOwner()
+ try {
+ for (let page = 1; page <= 3; page++) {
+ const request = h.latest.fetchOlder()
+ expect(request.accepted).toBe(true)
+ if (!request.accepted) throw new Error("Older request rejected")
+ await act(async () => { expect((await request.completed).status).toBe("success") })
+ await waitFor(() => expect(h.latest.messages).toHaveLength(26 + page * 50))
+ }
+ const cached = h.client.getQueryData<MessageWindowData>(h.key)!
+ expect(cached.pages).toHaveLength(4)
+ const complete = [...h.registry.collections.messages.values()].length
+ h.view.rerender(h.app(false))
+ h.view.rerender(h.app())
+ try {
+ await waitFor(() => expect(h.latest.initialPositionKnown).toBe(true))
+ expect(h.latest.messages).toHaveLength(176)
+ } finally {
+ console.info("wire-remount", { completeBefore: complete, cachedPages: cached.pages.length,
+ finalRows: h.latest.messages.length, initialPositionKnown: h.latest.initialPositionKnown,
+ entryCanRead: h.latest.entryCanRead, positionDataState: h.latest.positionDataState, requests: h.requests })
+ }
+ expect(complete).toBe(176)
+ expect(h.client.getQueryData<MessageWindowData>(h.key)?.pages).toHaveLength(4)
+ expect(currentConversationReadState(h.client, "c1")?.lastReadSeq).toBe(240)
+ expect(h.requests.filter(request => request.query.includes("cursor="))).toHaveLength(3)
+ for (const request of h.requests.filter(request => !request.query.includes("entry="))) expect(request.version).toBe(String(BUSINESS_SCHEMA_VERSION))
+ } finally { h.view.unmount(); h.client.clear() }
+ })
+
+ it("rejects a downgraded page without publishing partial rows or retiring the valid window", async () => {
+ const h = await wireOwner()
+ try {
+ h.forceLegacyPages()
+ const request = h.latest.fetchOlder()
+ expect(request.accepted).toBe(true)
+ if (!request.accepted) throw new Error("Older request rejected")
+ await act(async () => { expect((await request.completed).status).toBe("error") })
+ expect(h.latest.messages).toHaveLength(26)
+ expect(h.client.getQueryData<MessageWindowData>(h.key)?.pages).toHaveLength(1)
+ expect(h.registry.collections.messages.get("m165")).toBeUndefined()
+ expect(h.registry.collections.messages.get("m240")).toBeDefined()
+ expect(currentConversationReadState(h.client, "c1")?.lastReadSeq).toBe(240)
+ } finally { h.view.unmount(); h.client.clear() }
+ })
+
+ it("keeps reconciled new resources qualified for a later remount without advancing reads", async () => {
+ const h = await wireOwner()
+ try {
+ h.enableCatchUp()
+ await act(async () => { await reconcileWindow(h.client, { kind: "dm", scopeId: "c1" }, h.key, 255) })
+ await waitFor(() => expect(h.latest.messages).toHaveLength(41))
+ h.view.rerender(h.app(false))
+ h.view.rerender(h.app())
+ await waitFor(() => expect(h.latest.initialPositionKnown).toBe(true))
+ expect(h.latest.messages).toHaveLength(41)
+ expect(h.registry.collections.messages.get("m255")).toBeDefined()
+ expect(currentConversationReadState(h.client, "c1")?.lastReadSeq).toBe(240)
+ expect(h.requests.some(request => request.query.includes("since=") && request.version === String(BUSINESS_SCHEMA_VERSION))).toBe(true)
+ } finally { h.view.unmount(); h.client.clear() }
+ })
+})
diff --git a/src/web/src/hooks/community/mutations/bot-creation.dom.test.tsx b/src/web/src/hooks/community/mutations/bot-creation.dom.test.tsx
index c81559c52..b67e6ea62 100644
--- a/src/web/src/hooks/community/mutations/bot-creation.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/bot-creation.dom.test.tsx
@@ -1,3 +1,4 @@
+import { messageSeedFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -15,7 +16,7 @@ vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => api(...ar
beforeEach(() => api.mockReset())
async function owner() {
const state = await createCommunityQueryOwner()
- ingestMessages(state.registry, "dm-1", [{ id: "message-1", type: "chat", seq: 1, content: "", botCreation: botCreationFixture() }])
+ ingestMessages(state.registry, "dm-1", messageSeedFixture("dm-1", [{ id: "message-1", type: "chat", seq: 1, content: "", botCreation: botCreationFixture() }]))
state.client.setQueryData(communityKeys.bots(), { bots: [] })
state.client.setQueryData(communityKeys.machines(), { machines: [] })
function Wrapper({ children }: PropsWithChildren) { return createElement(CommunityTestProvider, { ...state, retainOwner: true }, children) }
@@ -33,7 +34,7 @@ describe("bot creation owner decision", () => {
it("does not overwrite a renamed bot when an old approved card is loaded", async () => {
const state = await owner()
writeCommunityProfilePatches([{ id: "created-1", identityAbout: { name: "Renamed Bot", discriminator: "0042" }, avatar: { avatar: "new-avatar", avatarVersion: 2 } }], state.registry, { command: true })
- ingestMessages(state.registry, "dm-1", [{ id: "historical-card", type: "chat", seq: 2, botCreation: approved() }])
+ ingestMessages(state.registry, "dm-1", messageSeedFixture("dm-1", [{ id: "historical-card", type: "chat", seq: 2, botCreation: approved() }]))
expect(state.registry.collections.profiles.get("created-1")).toMatchObject({ name: "Renamed Bot", avatar: "new-avatar", avatarVersion: 2 })
api.mockResolvedValueOnce({ botCreation: approved() })
await act(async () => { await state.view.result.current.mutateAsync(input) })
diff --git a/src/web/src/hooks/community/mutations/channel-directory-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/channel-directory-owner.dom.test.tsx
index c05248871..935e33dad 100644
--- a/src/web/src/hooks/community/mutations/channel-directory-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/channel-directory-owner.dom.test.tsx
@@ -1,3 +1,4 @@
+import { channelResourceFixture, serverResourceFixture, fullResourceBundleFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -19,6 +20,9 @@ vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => sdk.
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }) }))
vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
const directory = [{ id: "srv", name: "Studio", discriminator: "0001", channels: [{ id: "ch", name: "general", type: "text" as const }] }]
+function directoryResponse(viewerId: string) { return { directory, resources: fullResourceBundleFixture(viewerId,
+ [serverResourceFixture({ id: "srv", name: "Studio", discriminator: "0001", ownerId: viewerId, isOwner: true })],
+ [channelResourceFixture({ id: "ch", serverId: "srv", name: "general" })]) } }
let current: ReturnType<typeof useRenameChannel>, currentClient: QueryClient
function Probe() {
const data = useChannelRefDirectory(), command = useRenameChannel(), client = useQueryClient(); useLayoutEffect(() => { current = command; currentClient = client; if (!clients.includes(client)) clients.push(client) })
@@ -33,7 +37,7 @@ async function mount() {
api.mockImplementation((path: string, options?: { method?: string; authenticationAccount?: string; signal?: AbortSignal }) => {
if (options?.method === "PATCH") return held.promise
const account = options?.authenticationAccount ?? "unknown"
- if (!seen.has(account)) { seen.add(account); return Promise.resolve({ directory }) }
+ if (!seen.has(account)) { seen.add(account); return Promise.resolve(directoryResponse(account)) }
return new Promise((_, reject) => options?.signal?.addEventListener("abort", () => reject(new DOMException("Cancelled fresh read", "AbortError")), { once: true }))
})
const view = render(<Root />)
@@ -88,7 +92,7 @@ describe("native directory fact owner and channel transaction", () => {
expect(qc.getQueryData(communityKeys.channelRefDirectory())).toBeUndefined()
})
it("retires the native warm read and its observers through actual QueryProvider unmount without manually clearing its client", async () => {
- const held: Array<{ signal: AbortSignal; finish: (data: { directory: typeof directory }) => void }> = []
+ const held: Array<{ signal: AbortSignal; finish: (data: ReturnType<typeof directoryResponse>) => void }> = []
api.mockImplementation((_path: string, options: { signal: AbortSignal }) => new Promise((finish) => { held.push({ signal: options.signal, finish }) }))
const view = render(<Root />)
await waitFor(() => expect(currentClient.getQueryCache().find({ queryKey: communityKeys.channelRefDirectory() })?.getObserversCount()).toBe(2))
@@ -99,7 +103,7 @@ describe("native directory fact owner and channel transaction", () => {
await waitFor(() => expect(signal.aborted).toBe(true))
expect(resource.getObserversCount()).toBe(0)
await waitFor(() => expect(original.getQueryCache().getAll()).toHaveLength(0))
- await act(async () => held.forEach((request) => request.finish({ directory })))
+ await act(async () => held.forEach((request) => request.finish(directoryResponse("A"))))
expect(original.getQueryCache().getAll()).toHaveLength(0)
})
})
diff --git a/src/web/src/hooks/community/mutations/channels.dom.test.ts b/src/web/src/hooks/community/mutations/channels.dom.test.ts
index 487d8448e..8fcbda79f 100644
--- a/src/web/src/hooks/community/mutations/channels.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/channels.dom.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture, categoryResourceFixture, serverRailResponseFixture, serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
@@ -28,13 +29,12 @@ afterEach(async () => {
})
function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }
const server = { id: "s1", name: "Studio", discriminator: "0042", description: "", icon: null, ownerId: "viewer" }
-const categories: ServerDetail["categories"] = [{ id: "cat_1", name: "General", private: 0, channels: [{ id: "c1", name: "general", active: false, unread: false }, { id: "c2", name: "random", active: false, unread: true }] }, { id: "cat_2", name: "Ideas", private: 0, channels: [] }]
+const categories: ServerDetail["categories"] = [{ id: "cat_1", name: "General", private: false, channels: [{ id: "c1", name: "general", active: false, unread: false }, { id: "c2", name: "random", active: false, unread: true }] }, { id: "cat_2", name: "Ideas", private: false, channels: [] }]
function publish(snapshot: Parameters<typeof publishCommunityLiveSnapshot>[1]["snapshot"]) { publishCommunityLiveSnapshot(client, { snapshot, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } }) }
function seed(cats = categories) {
- publish({ kind: "servers", data: { servers: [server, { ...server, id: "s2", name: "Elsewhere" }].map((row) => ({ ...row, initial: "S", active: false, unread: false, mentions: 0 })) } })
- publish({ kind: "server-detail", data: { ...server, categories: cats } })
- publish({ kind: "server-detail", data: { ...server, id: "s2", categories: [{ id: "other-cat", name: "Other", channels: [{ id: "c3", name: "other", active: false, unread: false }] }] } })
- client.setQueryData(communityKeys.server("s1"), "s1")
+ publish({ kind: "servers", data: serverRailResponseFixture({ servers: [server, { ...server, id: "s2", name: "Elsewhere" }] }, "viewer") })
+ publish({ kind: "server-detail", data: serverDirectoryFixture({ ...server, categories: cats.filter(category => category.id !== UNCATEGORIZED_CATEGORY_ID), channels: cats.filter(category => category.id === UNCATEGORIZED_CATEGORY_ID).flatMap(category => category.channels) }) })
+ publish({ kind: "server-detail", data: serverDirectoryFixture({ ...server, id: "s2", categories: [{ id: "other-cat", name: "Other", channels: [{ id: "c3", name: "other", active: false, unread: false }] }] }) })
client.setQueryData(communityKeys.channelRefDirectory(), { serverIds: ["s1", "s2"] })
}
function mount<T>(hook: () => T) { return renderHook(() => { const command = hook(), tree = useServerTreeProjection("s1"), directory = useChannelRefDirectoryProjection(), sidebar = useChannelTree(tree?.categories ?? []); return { command, tree, directory, sidebar } }, { wrapper: Owner }) }
@@ -65,7 +65,7 @@ describe("canonical channel rename", () => {
await act(async () => { await rendered.result.current.command.mutateAsync(rename) })
await waitFor(() => expect(treeChannels(rendered.result.current.tree).find((row) => row.id === "c1")?.name).toBe("General-Chat"))
expect(rendered.result.current.directory?.[0]?.channels.find((row) => row.id === "c1")?.name).toBe("General-Chat")
- expect(client.getQueryData(communityKeys.server("s1"))).toBe("s1")
+ expect(client.getQueryData(communityKeys.server("s1"))).toMatchObject({ serverId: "s1" })
expect(registry.collections.channels.get("c3")?.name).toBe("other")
})
it("restores both consumers on failure without optimistic residue", async () => {
@@ -123,7 +123,7 @@ describe("canonical channel move and create", () => {
await waitFor(() => expect(treeChannels(rendered.result.current.tree).find((row) => row.pending)).toMatchObject({ name: "hi", type: "text" }))
const row = treeChannels(rendered.result.current.tree).find((row) => row.pending)!
expect(row.id).toMatch(/^tmp_ch_/)
- await act(async () => { held.resolve({ channel: { id: "ch_real" } }); await pending })
+ await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) }); await pending })
})
it("physically cancels an in-flight server refetch before the optimistic write", async () => {
seed()
@@ -132,7 +132,7 @@ describe("canonical channel move and create", () => {
const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
await waitFor(() => expect(treeChannels(rendered.result.current.tree).some((row) => row.pending)).toBe(true))
expect(signal.aborted).toBe(true)
- await act(async () => { held.resolve({ channel: { id: "ch_real" } }); await pending; await read })
+ await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) }); await pending; await read })
})
it("leaves existing categories unchanged when the target category is absent", async () => {
seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, { ...create, categoryId: "missing" })
@@ -153,18 +153,18 @@ describe("canonical channel move and create", () => {
seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, create)
await waitFor(() => expect(Array.from(registry.collections.channels.values()).some((row) => row.pending)).toBe(true))
const temp = Array.from(registry.collections.channels.values()).find((row) => row.pending)!.id
- await act(async () => { held.resolve({ channel: { id: "ch_real", name: "normalized", position: 8 } }); await pending })
+ await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "normalized", position: 8 }) }); await pending })
expect(registry.collections.channels.has(temp)).toBe(false)
expect(registry.collections.channels.get("ch_real")).toMatchObject({ name: "normalized", pending: false, position: 8 })
})
it.each(["success", "failure"] as const)("invalidates the original server tree on create %s", async (outcome) => {
- seed(); if (outcome === "success") api.mockResolvedValueOnce({ channel: { id: "ch_real" } }); else api.mockRejectedValueOnce(new Error("boom"))
+ seed(); if (outcome === "success") api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) }); else api.mockRejectedValueOnce(new Error("boom"))
const rendered = mount(commands.useCreateChannel)
await act(async () => { await rendered.result.current.command.mutateAsync(create).catch(() => {}) })
expect(client.getQueryState(communityKeys.server("s1"))?.isInvalidated).toBe(true)
})
it("POSTs type, serverId, categoryId and original name to the unified create door", async () => {
- seed(); api.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ seed(); api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: "cat_1", name: "hi" }) })
const rendered = mount(commands.useCreateChannel)
await act(async () => { await rendered.result.current.command.mutateAsync(create) })
expect(api).toHaveBeenCalledWith("/api/community/channels", expect.objectContaining({ method: "POST" }))
@@ -174,12 +174,12 @@ describe("canonical channel move and create", () => {
seed(); const held = deferred(), rendered = mount(commands.useCreateChannel), pending = start(rendered.result.current.command, { ...create, categoryId })
await waitFor(() => expect(rendered.result.current.tree?.categories.find((row) => row.id === UNCATEGORIZED_CATEGORY_ID)?.channels[0]).toMatchObject({ pending: true, name: "hi" }))
expect(JSON.parse(api.mock.calls[0][1].body)).toEqual({ ...create, categoryId: null })
- await act(async () => { held.resolve({ channel: { id: "ch_real" } }); await pending })
+ await act(async () => { held.resolve({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: null, name: "hi" }) }); await pending })
expect(rendered.result.current.tree?.categories.filter((row) => row.id === UNCATEGORIZED_CATEGORY_ID)).toHaveLength(1)
})
it("reuses the canonical uncategorized projection without a duplicate category", async () => {
seed([...categories, { id: UNCATEGORIZED_CATEGORY_ID, name: "", channels: [{ id: "top", name: "Top", active: false, unread: false }] }])
- api.mockResolvedValueOnce({ channel: { id: "ch_real" } })
+ api.mockResolvedValueOnce({ channel: channelResourceFixture({ id: "ch_real", serverId: "s1", categoryId: null, name: "hi", position: 1 }) })
const rendered = mount(commands.useCreateChannel)
await act(async () => { await rendered.result.current.command.mutateAsync({ ...create, categoryId: "" }) })
await waitFor(() => expect(rendered.result.current.tree?.categories.find((row) => row.id === UNCATEGORIZED_CATEGORY_ID)?.channels.map((row) => row.id)).toEqual(["top", "ch_real"]))
@@ -188,15 +188,31 @@ describe("canonical channel move and create", () => {
})
})
+describe("current create resource admission", () => {
+ it.each(["channel", "category"] as const)("rejects incomplete successful %s confirmation without publishing a confirmed row", async kind => {
+ seed()
+ api.mockResolvedValueOnce({ [kind]: { id: "partial-real" } })
+ const rendered = mount(kind === "channel" ? commands.useCreateChannel : commands.useCreateCategory)
+ let error: unknown
+ await act(async () => {
+ try { await rendered.result.current.command.mutateAsync(kind === "channel" ? create : { serverId: "s1", name: "New Ideas" }) }
+ catch (failure) { error = failure }
+ })
+ expect(error).toBeInstanceOf(Error)
+ expect(registry.collections.channels.has("partial-real")).toBe(false)
+ expect(registry.collections.categories.has("partial-real")).toBe(false)
+ })
+})
+
describe("canonical category commands and channel deletion", () => {
it("appends a pending category with a tmp_cat_ id", async () => {
seed(); const held = deferred(), rendered = mount(commands.useCreateCategory), pending = start(rendered.result.current.command, { serverId: "s1", name: " New Ideas " })
await waitFor(() => expect(rendered.result.current.tree?.categories.find((row) => row.pending)).toMatchObject({ name: "New Ideas" }))
expect(rendered.result.current.tree?.categories.find((row) => row.pending)?.id).toMatch(/^tmp_cat_/)
- await act(async () => { held.resolve({ category: { id: "cat_real" } }); await pending })
+ await act(async () => { held.resolve({ category: categoryResourceFixture({ id: "cat_real", serverId: "s1", name: "New Ideas" }) }); await pending })
})
it("swaps the temp category id to the real id and clears pending", async () => {
- seed(); api.mockResolvedValueOnce({ category: { id: "cat_real" } })
+ seed(); api.mockResolvedValueOnce({ category: categoryResourceFixture({ id: "cat_real", serverId: "s1", name: "New Ideas" }) })
const rendered = mount(commands.useCreateCategory)
await act(async () => { await rendered.result.current.command.mutateAsync({ serverId: "s1", name: "New Ideas" }) })
expect(registry.collections.categories.get("cat_real")).toMatchObject({ name: "New Ideas", pending: false })
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index b86ffd657..3c95099e1 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -15,7 +15,7 @@ import {
import { communityKeys } from "@/lib/query-keys"
import { isAbortError } from "@/lib/errors"
import type { ChannelRow, CategoryRow } from "@/lib/community-db/schema"
-import { UNCATEGORIZED_CATEGORY_ID, type ChannelCategoryMove, type ChannelType } from "@alook/shared"
+import { UNCATEGORIZED_CATEGORY_ID, CommunityChannelResourceSchema, CommunityCategoryResourceSchema, type CommunityCategoryResource, type CommunityChannelResource, type ChannelCategoryMove, type ChannelType } from "@alook/shared"
// Prefix marks an optimistic row so every consumer can tell it from a real
// `ch_…` id without a separate flag, and guarantees it never collides with one.
@@ -50,7 +50,7 @@ export type CreateChannelArgs = {
name: string
type: ChannelType
}
-export type CreateChannelResult = { channel: { id: string; name?: string; position?: number } }
+export type CreateChannelResult = { channel: CommunityChannelResource }
async function persistTreeChange<T>(
origin: ReturnType<typeof useCommunityMutationOrigin>,
@@ -100,14 +100,16 @@ export function useCreateChannel() {
return persistTreeChange(origin, queryClient, args, (db) => {
const rows = [...db.collections.channels.values()].filter((row) => row.serverId === args.serverId && row.categoryId === categoryId)
const position = Math.max(-1, ...rows.map((row) => row.position)) + 1
- pending = { id, serverId: args.serverId, categoryId, name: args.name.trim(), type: args.type, resourceComplete: false,
+ pending = { id, serverId: args.serverId, categoryId, name: args.name.trim(), type: args.type, topic: "", createdAt: new Date().toISOString(), messageCount: 0,
parentChannelId: null, parentMessageId: null, creatorId: db.accountId,
position, archived: false, muted: false, tags: [], pending: true, lastMessageAt: null }
db.collections.channels.insert(pending)
}, async (proof, options) => {
const result = await apiFetch<CreateChannelResult>("/api/community/channels", { method: "POST", body: JSON.stringify({ type: args.type, serverId: args.serverId, categoryId, name: args.name }), ...options })
origin.assert(proof.token)
- publishCommunityCreatedChannel(queryClient, { ...pending, id: result.channel.id, name: result.channel.name ?? pending.name, position: result.channel.position ?? pending.position, pending: false }, proof)
+ const channel = CommunityChannelResourceSchema.parse(result.channel)
+ if (channel.serverId !== args.serverId || channel.type !== args.type || channel.categoryId !== categoryId) throw new Error("Created channel scope mismatch")
+ publishCommunityCreatedChannel(queryClient, { ...channel, pending: false }, proof)
return result
})
},
@@ -195,7 +197,7 @@ export type CreateCategoryArgs = {
name: string
private?: boolean
}
-export type CreateCategoryResult = { category: { id: string; name?: string; position?: number; private?: boolean } }
+export type CreateCategoryResult = { category: CommunityCategoryResource }
const tempCategoryId = () => `tmp_cat_${nanoid()}`
@@ -214,7 +216,9 @@ export function useCreateCategory() {
}, async (proof, options) => {
const result = await apiFetch<CreateCategoryResult>(`/api/community/servers/${args.serverId}/categories`, { method: "POST", body: JSON.stringify({ name: args.name, private: args.private }), ...options })
origin.assert(proof.token)
- publishCommunityCreatedCategory(queryClient, { ...pending, id: result.category.id, name: result.category.name ?? pending.name, position: result.category.position ?? pending.position, private: result.category.private ?? pending.private, pending: false }, proof)
+ const category = CommunityCategoryResourceSchema.parse(result.category)
+ if (category.serverId !== args.serverId) throw new Error("Created category scope mismatch")
+ publishCommunityCreatedCategory(queryClient, { ...category, pending: false }, proof)
return result
})
},
diff --git a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
index f87c4c32f..792d25080 100644
--- a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
@@ -1,3 +1,7 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { decodeCommunityReadResponse } from "@/lib/community/read-response"
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { fullResourceBundleFixture, serverResourceFixture, messageResourceFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, useLayoutEffect, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -27,17 +31,21 @@ function deferred() {
return { promise, resolve, reject }
}
function wire(ids: string[]): ForumFeedTransportPage {
- return {
- serverId: "server_1", parentType: "forum", hasMore: false,
- threads: ids.map((id, index) => ({ id, name: id, creatorId: `author_${id}`, messageCount: 1, parentMessageId: `opener_${id}`, createdAt: new Date(Date.now() - index * 1000).toISOString(), lastMessageAt: new Date().toISOString(), activityAt: new Date().toISOString() })),
+ const at = new Date().toISOString()
+ const channel = channelResourceFixture({ id: "forum_1", serverId: "server_1", type: "forum", name: "Forum" })
+ return { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: channel.id, channel,
+ threads: ids.map((id, index) => channelResourceFixture({ id, serverId: channel.serverId, type: "thread", parentChannelId: channel.id, name: id, creatorId: `author_${id}`, messageCount: 1, parentMessageId: `opener_${id}`, createdAt: new Date(Date.now() - index * 1000).toISOString(), lastMessageAt: at })),
included: {
- parentMessages: ids.map((id, index) => ({ id: `opener_${id}`, channelId: "forum_1", seq: index + 1, content: id, authorId: `author_${id}`, authorName: id, authorImage: null, authorAvatarVersion: 0 })),
- firstMessages: ids.map((id) => ({ channelId: id, content: `body ${id}` })),
+ messages: ids.flatMap((id, index) => [messageResourceFixture({ id: `opener_${id}`, channelId: channel.id, seq: index + 1, content: id, authorId: `author_${id}`, authorName: id, authorAvatar: null, authorAvatarVersion: 0 }),
+ messageResourceFixture({ id: `first_${id}`, channelId: id, content: `body ${id}`, authorId: `author_${id}` })]),
tags: ids.map((id) => ({ messageId: `opener_${id}`, tag: "bug" })),
- participants: [],
- },
+ members: ids.map(id => ({ channelId: id, userId: "viewer", relation: "notify", source: "spoke", isCreator: false, role: "owner", memberId: "member-server_1" })),
+ profiles: [{ id: "viewer", name: "Viewer", discriminator: "0001", avatar: null, avatarVersion: 0 }, ...ids.map(id => ({ id: `author_${id}`, name: id, discriminator: "0002", avatar: null, avatarVersion: 0 }))],
+ participantCounts: ids.map(id => ({ channelId: id, count: 1 })),
+ }, page: { hasMore: false, nextCursor: null },
}
}
+
const tagInput = { serverId: "server_1", forumChannelId: "forum_1", threadId: "p2", openerMessageId: "opener_p2", previousTags: ["bug"], tags: ["bug", "archived"] }
const deleteInput = { serverId: "server_1", forumChannelId: "forum_1", threadId: "p2", openerMessageId: "opener_p2" }
async function setup(ids = ["before", "p2", "after"], observeCatalog = false) {
@@ -59,12 +67,12 @@ async function setup(ids = ["before", "p2", "after"], observeCatalog = false) {
}, { wrapper })
function seed(rows: string[], append = false) {
const page = wire(rows), token = captureCommunityLiveSnapshotToken(owner.client)
- publishCommunityForumSidebar(owner.client, { serverId: "server_1", channels: page.threads.map((row) => ({ ...row, name: row.name!, unread: false, parentChannelId: "forum_1", type: "thread", archived: false })), openers: page.included.parentMessages, proof: { token, signal: undefined } })
+ publishCommunityForumSidebar(owner.client, { serverId: "server_1", resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server_1" })], [page.channel, ...page.threads], page.included.messages, page.included.profiles), channels: page.threads.map((row) => ({ ...row, name: row.name!, unread: false, parentChannelId: "forum_1", type: "thread", archived: false })), openers: page.included.messages.filter(message => message.channelId === "forum_1"), proof: { token, signal: undefined } })
publishCommunityForumFeed(owner.client, "forum_1", normalizeThreadResources("forum_1", page), { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
for (const filter of [null, "bug", "archived"]) owner.client.setQueryData<InfiniteData<ForumFeedPage>>(communityKeys.forumFeed("forum_1", filter), (current) => ({ pages: append && current ? [{ ...current.pages[0], threads: [...current.pages[0].threads, ...forumFeedWindow(normalizeThreadResources("forum_1", page)).threads] }] : [forumFeedWindow(normalizeThreadResources("forum_1", page))], pageParams: [null] }))
}
act(() => {
- projectCommunityWsEventToDb(owner.client, { type: "community:channel.create", serverId: "server_1", channel: { id: "forum_1", name: "Forum", type: "forum", categoryId: null, position: 0, createdAt: new Date().toISOString() } })
+ projectCommunityWsEventToDb(owner.client, { type: "community:channel.create", serverId: "server_1", channel: channelResourceFixture({ id: "forum_1", serverId: "server_1", name: "Forum", type: "forum", createdAt: new Date().toISOString() }) })
seed(ids)
owner.client.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [{ messages: ids.map((id) => ({ id: `opener_${id}` })) }], pageParams: [null] })
owner.client.setQueryData([...communityKeys.channelMessages("forum_1"), "tag", "bug"], { pages: [], pageParams: [null] })
@@ -84,39 +92,51 @@ async function begin(view: View, command: "tags" | "remove", input = command ===
return { held, request }
}
+function mockForumCreation(nonce: string, title: string, content: string, held?: ReturnType<typeof deferred>) {
+ const opener = messageResourceFixture({ id: "created-opener", channelId: "forum_1", seq: 40, content: title, authorId: "viewer", authorName: "Viewer", authorAvatarVersion: 0, clientNonce: `${nonce}:opener` })
+ const child = channelResourceFixture({ id: "p_new", serverId: "server_1", type: "thread", parentChannelId: "forum_1", parentMessageId: opener.id, name: title })
+ const reply = messageResourceFixture({ id: "created-reply", channelId: child.id, content, clientNonce: `${nonce}:reply` })
+ const response = new Response(null, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+ const posted = decodeCommunityReadResponse("/api/community/channels/forum_1/messages", "POST", response, { profiles: messageProfilesFixture([opener]), contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "forum_1", message: opener, deduped: false, threadId: child.id })
+ const metadata = decodeCommunityReadResponse(`/api/community/channels/${child.id}`, "GET", response, { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: child.id, channel: child, access: { channelId: child.id, canRead: true, canSend: true, canCreateDiscussion: false } })
+ const replied = decodeCommunityReadResponse(`/api/community/channels/${child.id}/messages`, "POST", response, { profiles: messageProfilesFixture([reply]), contractVersion: BUSINESS_SCHEMA_VERSION, channelId: child.id, message: reply, deduped: false })
+ mocks.api.mockResolvedValueOnce(posted).mockResolvedValueOnce(metadata).mockReturnValueOnce(held?.promise ?? Promise.resolve(replied))
+ return { opener, child, replied }
+}
+
describe("Native forum creation", () => {
it("POSTs opener and reply with exact nonce suffixes and optional fields omitted", async () => {
const view = await setup()
- mocks.api.mockResolvedValueOnce({ threadId: "p_new" }).mockResolvedValueOnce({})
+ mockForumCreation("command_1", "hi", "body")
await act(async () => { await view.view.result.current.create.mutateAsync({ nonce: "command_1", channelId: "forum_1", name: "hi", content: "body" }) })
- expect(mocks.api).toHaveBeenCalledTimes(2)
+ expect(mocks.api).toHaveBeenCalledTimes(3)
+ expect(mocks.api.mock.calls[1][0]).toBe("/api/community/channels/p_new")
expect(mocks.api.mock.calls[0][0]).toBe("/api/community/channels/forum_1/messages")
expect(JSON.parse(mocks.api.mock.calls[0][1].body)).toEqual({ content: "hi", nonce: "command_1:opener" })
- expect(mocks.api.mock.calls[1][0]).toBe("/api/community/channels/p_new/messages")
- expect(JSON.parse(mocks.api.mock.calls[1][1].body)).toEqual({ content: "body", nonce: "command_1:reply" })
+ expect(mocks.api.mock.calls[2][0]).toBe("/api/community/channels/p_new/messages")
+ expect(JSON.parse(mocks.api.mock.calls[2][1].body)).toEqual({ content: "body", nonce: "command_1:reply" })
})
it("publishes the actual returned opener and linked child before the reply settles", async () => {
const view = await setup(), held = deferred()
- const opener = { id: "created-opener", seq: 40, type: "chat", content: "New post", authorId: "viewer", authorName: "Viewer", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-08T01:00:00Z" }
- mocks.api.mockResolvedValueOnce({ threadId: "p_new", message: opener }).mockReturnValueOnce(held.promise)
+ const { opener, replied } = mockForumCreation("create_1", "New post", "Body", held)
let request!: Promise<unknown>
act(() => { request = view.view.result.current.create.mutateAsync({ nonce: "create_1", channelId: "forum_1", name: "New post", content: "Body" }) })
- await waitFor(() => expect(mocks.api).toHaveBeenCalledTimes(2))
+ await waitFor(() => expect(mocks.api).toHaveBeenCalledTimes(3))
expect(view.registry.collections.messages.get(opener.id)).toMatchObject({ channelId: "forum_1", content: "New post", clientNonce: "create_1:opener", seq: 40 })
expect(view.registry.collections.channels.get("p_new")).toMatchObject({ serverId: "server_1", parentChannelId: "forum_1", parentMessageId: opener.id, name: "New post", type: "thread" })
- await act(async () => { held.resolve({}); await request })
+ await act(async () => { held.resolve(replied); await request })
expect(view.registry.collections.messages.get("opener_p2")).toBeDefined()
})
it("reserves attachment IDs for both messages and broadcasts mentionType on the opener", async () => {
const view = await setup(), attachments = [{ id: "att_1", filename: "abc.png", contentType: "image/png", size: 100, width: 10, height: 10 }]
- mocks.api.mockResolvedValueOnce({ threadId: "p_new" }).mockResolvedValueOnce({})
+ mockForumCreation("command_1", "heads up", "Heads up @everyone")
await act(async () => { await view.view.result.current.create.mutateAsync({ nonce: "command_1", channelId: "forum_1", name: "heads up", content: "Heads up @everyone", attachments, mentionType: "everyone" }) })
expect(JSON.parse(mocks.api.mock.calls[0][1].body)).toEqual({ content: "heads up", attachments: ["att_1"], mentionType: "everyone", nonce: "command_1:opener" })
- expect(JSON.parse(mocks.api.mock.calls[1][1].body).attachments).toEqual(["att_1"])
+ expect(JSON.parse(mocks.api.mock.calls[2][1].body).attachments).toEqual(["att_1"])
})
it("invalidates the original composed forum list on success", async () => {
const view = await setup()
- mocks.api.mockResolvedValueOnce({ threadId: "p_new" }).mockResolvedValueOnce({})
+ mockForumCreation("command_1", "n", "c")
await act(async () => { await view.view.result.current.create.mutateAsync({ nonce: "command_1", channelId: "forum_1", name: "n", content: "c" }) })
expect(view.client.getQueryState(communityKeys.channelMessages("forum_1"))?.isInvalidated).toBe(true)
expect(view.client.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(true)
diff --git a/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
index b4b1f49f3..b501acdf8 100644
--- a/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
@@ -1,3 +1,4 @@
+import { channelResourceFixture, messageResourceFixture, fullResourceBundleFixture, serverResourceFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -26,8 +27,12 @@ async function seed(qc: QueryClient) {
const registry = getCommunityDbRegistry(qc)!
await act(async () => { await registry.ready; await registry.preload() })
act(() => {
- projectCommunityWsEventToDb(qc, { type: "community:channel.create", serverId: "server", channel: { id: "forum", name: "Forum", type: "forum", categoryId: null, position: 0, createdAt: new Date().toISOString() } })
- publishCommunityForumSidebar(qc, { serverId: "server", channels: [{ id: "child", name: "Original", parentChannelId: "forum", parentMessageId: "opener", activityAt: new Date().toISOString(), unread: false, type: "thread", serverId: "server", archived: false }], openers: [{ id: "opener", channelId: "forum", seq: 1, type: "chat", content: "Original opener" }], proof: { token: captureCommunityLiveSnapshotToken(qc), signal: undefined } })
+ projectCommunityWsEventToDb(qc, { type: "community:channel.create", serverId: "server", channel: { ...channelResourceFixture({ id: "forum", name: "Forum", type: "forum", serverId: "server" }), type: "forum" } })
+ const parent = channelResourceFixture({ id: "forum", type: "forum", serverId: "server" })
+ const child = channelResourceFixture({ id: "child", type: "thread", name: "Original", serverId: "server", parentChannelId: "forum", parentMessageId: "opener" })
+ const opener = messageResourceFixture({ id: "opener", channelId: "forum", content: "Original opener" })
+ publishCommunityForumSidebar(qc, { serverId: "server", resources: fullResourceBundleFixture(registry.accountId!, [serverResourceFixture({ id: "server" })], [parent, child], [opener]),
+ channels: [{ ...child, activityAt: new Date().toISOString(), unread: false, participating: true }], openers: [opener], proof: { token: captureCommunityLiveSnapshotToken(qc), signal: undefined } })
const runtime = getCommunityRuntime(qc); runtime.ui.actions.setCurrentServerId("server"); runtime.ui.actions.setCurrentChannelId("child"); runtime.ui.actions.registerUiHandlers({ replacePath: navigate })
})
await waitFor(() => expect(screen.getByTestId("child").textContent).toBe("Original"))
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index 686cea84c..5d5ea097d 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -1,5 +1,8 @@
"use client"
+import type { CommunityMessagePosted } from "@alook/shared"
+import type { CommunityChannelResource } from "@alook/shared"
+
import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
import { useCallback } from "react"
@@ -24,7 +27,7 @@ import {
type ForumPostUnitIdentity,
} from "@/hooks/community/community-ws/channel-scope-projection"
import { collectChannelScopeIds, beginCommunityCommandRevision, publishCommunityCreatedChannel, publishCommunityForumTags, publishCommunityMessages } from "@/lib/community-db/sync"
-import { projectPostedMessage, type PostedMessage } from "@/lib/community/message-wire"
+import { projectPostedMessage } from "@/lib/community/message-wire"
import { reconcileForumSidebarArchiveTag } from "../use-forum-sidebar-threads"
export type CreateForumThreadArgs = {
@@ -57,7 +60,7 @@ export function useCreateForumThread() {
await Promise.all([origin.registry!.collections.channels.preload(), origin.registry!.collections.messages.preload(), origin.registry!.collections.channelMemberships.preload()])
assert()
const attachmentIds = attachments?.map((a) => a.id)
- const structure = await origin.request<CreateForumThreadResult & { message: PostedMessage }>(token,
+ const structure = await origin.request<CreateForumThreadResult & Pick<CommunityMessagePosted, "message" | "profiles">>(token,
`/api/community/channels/${channelId}/messages`,
{
method: "POST", signal: assertActive?.signal, assertActive,
@@ -67,16 +70,19 @@ export function useCreateForumThread() {
assert()
const parent = origin.registry!.collections.channels.get(channelId)
if (parent && structure.message) {
- publishCommunityMessages(queryClient, { channelId, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })
- publishCommunityCreatedChannel(queryClient, { id: structure.threadId, serverId: parent.serverId, categoryId: null, name, type: "thread", parentChannelId: channelId, parentMessageId: structure.message.id, creatorId: structure.message.authorId, position: 0, archived: false, muted: false, tags: [], pending: false, resourceComplete: false }, { token, signal: assertActive?.signal })
+ publishCommunityMessages(queryClient, { channelId, profiles: structure.profiles, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })
+ const child = await origin.request<CommunityChannelResource>(token, `/api/community/channels/${structure.threadId}`, { method: "GET", signal: assertActive?.signal, assertActive })
+ assert()
+ if (child.parentChannelId !== channelId || child.parentMessageId !== structure.message.id || child.serverId !== parent.serverId) throw new Error("Created forum child scope mismatch")
+ publishCommunityCreatedChannel(queryClient, child, { token, signal: assertActive?.signal })
}
assert()
- const reply = await origin.request<{ message: PostedMessage }>(token, `/api/community/channels/${structure.threadId}/messages`, {
+ const reply = await origin.request<Pick<CommunityMessagePosted, "message" | "profiles">>(token, `/api/community/channels/${structure.threadId}/messages`, {
method: "POST", signal: assertActive?.signal, assertActive,
body: JSON.stringify({ content, attachments: attachmentIds, nonce: `${nonce}:reply` }),
})
assert()
- if (reply.message) publishCommunityMessages(queryClient, { channelId: structure.threadId, messages: [projectPostedMessage(reply.message, `${nonce}:reply`, structure.threadId)], proof: { token, signal: assertActive?.signal } })
+ if (reply.message) publishCommunityMessages(queryClient, { channelId: structure.threadId, profiles: reply.profiles, messages: [projectPostedMessage(reply.message, `${nonce}:reply`, structure.threadId)], proof: { token, signal: assertActive?.signal } })
for (const query of resources) if (queryClient.getQueryCache().find({ queryKey: query.queryKey, exact: true }) === query) void queryClient.invalidateQueries({ queryKey: query.queryKey, exact: true }, { cancelRefetch: false }).catch(() => undefined)
return structure
},
diff --git a/src/web/src/hooks/community/mutations/friends.dom.test.ts b/src/web/src/hooks/community/mutations/friends.dom.test.ts
index 57ceb1f56..3f99771b4 100644
--- a/src/web/src/hooks/community/mutations/friends.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/friends.dom.test.ts
@@ -1,3 +1,4 @@
+import { attentionSnapshotScenarioFixture, dmListRowFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider, QueryObserver } from "@tanstack/react-query"
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
@@ -15,7 +16,7 @@ type Row = Parameters<typeof publishCommunityFriendships>[1][number]
const incoming = (id: string): Row => ({ id, userId: `u_${id}`, kind: "incoming" })
function attention() {
const rows = Array.from(registry.collections.friendships.values()).filter((row) => row.kind === "incoming")
- return { scopes: [], limit: 50, truncated: false, items: rows.map((row) => ({ id: `friend_request:${row.id}`, kind: "friend_request" as const, sourceId: row.id, actorUserId: row.userId, createdAt: "2026-09-27T00:00:00.000Z" })), included: { servers: [], channels: [], dms: [], messages: [], profiles: rows.map((row) => ({ userId: row.userId, name: row.id, discriminator: "0001", avatar: row.id, avatarVersion: 1 })) } }
+ return attentionSnapshotScenarioFixture({ scopes: [], limit: 50, truncated: false, items: rows.map((row) => ({ id: `friend_request:${row.id}`, kind: "friend_request" as const, sourceId: row.id, actorUserId: row.userId, createdAt: "2026-09-27T00:00:00.000Z" })), included: { servers: [], channels: [], dms: [], messages: [], profiles: rows.map((row) => ({ userId: row.userId, name: row.id, discriminator: "0001", avatar: row.id, avatarVersion: 1 })) } })
}
beforeEach(async () => {
api.mockReset()
@@ -155,8 +156,8 @@ describe("native friendship commands", () => {
})
it("publishes a canonical block and invalidates Friends", async () => {
seed()
- ingestDms(registry, { conversations: [{ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" }] })
- ingestMessages(registry, "dm_a", [{ id: "private", type: "chat", content: "private body", seq: 1 }])
+ ingestDms(registry, { conversations: [dmListRowFixture({ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" })] })
+ ingestMessages(registry, "dm_a", [messageResourceFixture({ id: "private", channelId: "dm_a", content: "private body" })])
const rendered = mount(commands.useBlockUser), invalidate = vi.spyOn(client, "invalidateQueries"), success = vi.fn()
await act(async () => { await rendered.result.current.command.mutateAsync({ userId: "u_a" }, { onSuccess: success }) })
expect(registry.collections.friendships.get("blocked:u_a")?.kind).toBe("blocked")
@@ -168,8 +169,8 @@ describe("native friendship commands", () => {
})
it("keeps visible DM reading intact when the normal block command fails", async () => {
seed()
- ingestDms(registry, { conversations: [{ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" }] })
- ingestMessages(registry, "dm_a", [{ id: "private", type: "chat", content: "private body", seq: 1 }])
+ ingestDms(registry, { conversations: [dmListRowFixture({ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "private preview" })] })
+ ingestMessages(registry, "dm_a", [messageResourceFixture({ id: "private", channelId: "dm_a", content: "private body" })])
const held = hold(), rendered = mount(commands.useBlockUser), pending = start(rendered.result.current.command, { userId: "u_a" })
await waitFor(() => expect(api).toHaveBeenCalledOnce())
await act(async () => { held.reject(new Error("block failed")); await pending })
@@ -179,7 +180,7 @@ describe("native friendship commands", () => {
})
it("starts a new permission generation after a confirmed own unblock", async () => {
seed([{ id: "blocked:u_a", userId: "u_a", kind: "blocked" }])
- ingestDms(registry, { conversations: [{ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "" }] })
+ ingestDms(registry, { conversations: [dmListRowFixture({ id: "dm_a", userId: "u_a", name: "A", discriminator: "0001", avatar: "A", avatarVersion: 0, status: "offline", preview: "" })] })
registry.runtime.ws.actions.revokeChannelAccess(null, "dm_a")
const generation = registry.runtime.ws.get().channelAccessScopes.get("dm_a")!.generation
const rendered = mount(commands.useUnblockUser)
diff --git a/src/web/src/hooks/community/mutations/members.dom.test.ts b/src/web/src/hooks/community/mutations/members.dom.test.ts
index 563b693c8..40e91ac9a 100644
--- a/src/web/src/hooks/community/mutations/members.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/members.dom.test.ts
@@ -1,3 +1,4 @@
+import { serverMembersReadFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -21,13 +22,13 @@ function deferred() {
async function setup(kind: "role" | "kick") {
const owner = await createCommunityQueryOwner()
const key = serverMembershipKey("srv_1", "u_1")
- const member = { id: "mem_1", userId: "u_1", role: "member", name: "n", discriminator: "0000", avatar: "N", status: "offline", sub: "" }
+ const member = { id: "mem_1", userId: "u_1", role: "member", avatarVersion: 0, name: "n", discriminator: "0000", avatar: "N", status: "offline", sub: "" }
owner.registry.collections.serverMemberships.utils.writeUpsert({ id: key, serverId: "srv_1", userId: "u_1", memberId: "mem_1", role: "member", viewer: false })
- owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, id: "u_1", kind: "human", name: "n", discriminator: "0000", avatar: "N", avatarVersion: 0, presence: "offline" }))
+ owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ id: "u_1", kind: "human", name: "n", discriminator: "0000", avatar: "N", avatarVersion: 0 }))
owner.client.setQueryData(communityKeys.members("srv_1"), { pages: [{ members: [{ id: "mem_1", userId: "u_1" }], hasMore: false, limit: 50, total: 1, liveRevision: 0 }], pageParams: [null] })
const held = deferred()
let remote = [member]
- apiFetch.mockImplementation((_path: string, options?: { method?: string }) => options?.method ? held.promise.then(() => { remote = kind === "role" ? [{ ...member, role: "admin" }] : [] }) : Promise.resolve({ members: remote, hasMore: false, limit: 50, total: remote.length }))
+ apiFetch.mockImplementation((_path: string, options?: { method?: string }) => options?.method ? held.promise.then(() => { remote = kind === "role" ? [{ ...member, role: "admin" }] : [] }) : Promise.resolve(serverMembersReadFixture("srv_1", remote, { search: _path.includes("/members/search"), limit: 50 })))
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
const rendered = renderHook(() => ({ role: useSetMemberRole(), kick: useKickMember(), roster: useServerMembers("srv_1") }), { wrapper })
await waitFor(() => expect(rendered.result.current.roster.members[0]?.role).toBe("member"))
diff --git a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
index c28e38db9..571a173bd 100644
--- a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
@@ -1,3 +1,4 @@
+import { singleMessageReadFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -32,7 +33,7 @@ async function mount() {
const key = `${options.authenticationAccount}:${path}`
if (seen.has(key)) return new Promise((_, fail) => options.signal?.addEventListener("abort", () => fail(new DOMException("aborted", "AbortError")), { once: true }))
seen.add(key)
- return Promise.resolve({ id: "m1", channelId: "c1", seq: 1, type: "chat", content: "original", authorId: "peer", authorName: "Peer", authorAvatar: "", authorAvatarVersion: 0, createdAt: "2026-10-02T00:00:00Z" })
+ return Promise.resolve(singleMessageReadFixture(messageResourceFixture({ id: "m1", channelId: "c1", seq: 1, type: "chat", content: "original", authorId: "peer", authorName: "Peer", authorAvatar: "", authorAvatarVersion: 0, createdAt: "2026-10-02T00:00:00Z" })))
})
const view = render(<Root />)
await waitFor(() => expect(screen.getByTestId("canonical").textContent).toBe("original"))
diff --git a/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts b/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts
index c89cfaa7e..3b71c6660 100644
--- a/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/message-reactions.dom.test.ts
@@ -1,3 +1,5 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
@@ -31,7 +33,7 @@ function Owner({ children }: PropsWithChildren) { return createElement(QueryClie
const args = { serverId: "s1", channelId: "ch_1", messageId: "m_1", emoji: "👍", userId: "u_me" }
const mine = [{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] }]
function seed(reactions: Msg["reactions"] = [], channelId = "ch_1", id = "m_1") {
- publishCommunityMessages(client, { channelId, messages: [{ id, seq: 1, type: "chat", content: "hello", reactions }], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ publishCommunityMessages(client, { profiles: messageProfilesFixture([messageResourceFixture({ id, channelId, seq: 1, content: "hello", reactions })]), channelId, messages: [messageResourceFixture({ id, channelId, seq: 1, content: "hello", reactions })], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
}
function rows(id = "m_1") { return registry.collections.messages.get(id)?.reactions }
function mounted() { return renderHook(() => ({ add: useAddReactionApi(), toggle: useToggleReactionApi(), messages: useCanonicalMessagesById() }), { wrapper: Owner }) }
diff --git a/src/web/src/hooks/community/mutations/messages.dom.test.ts b/src/web/src/hooks/community/mutations/messages.dom.test.ts
index efff5d71b..4585ddc4d 100644
--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts
@@ -1,3 +1,8 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { AccountAttentionSnapshotSchema, AttentionIncludedChannelSchema, AttentionIncludedMessageSchema, type AccountAttentionSnapshot, BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { messageResourceFixture, channelResourceFixture, serverResourceFixture, fullResourceBundleFixture, messageSeedFixture } from "@/test/community-resource-fixtures"
+import { serverDirectoryFixture } from "@/test/community-resource-fixtures"
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
import { getMessageStreamState, canonicalMessageReader } from "@/test/community-query-owner"
import { materializeMessageStream } from "@/lib/community/message-stream"
import { createElement, type PropsWithChildren } from "react"
@@ -44,18 +49,11 @@ function makeCache(msgs: Array<{ id: string } & Record<string, unknown>> = []) {
}
}
-function postedMessage(id: string, seq: number) {
- return {
- id,
- seq,
- createdAt: "2026-08-07T10:00:00.000Z",
- content: "canonical content",
- authorId: "u_me",
- authorName: "Canonical Name",
- authorImage: "https://avatar.test/me.png",
- type: "default",
- embeds: [{ title: "Canonical embed" }],
- }
+function postedMessage(id: string, seq: number, channelId: string, fields: Partial<import("@alook/shared").CommunityMessageResource> = {}) {
+ return messageResourceFixture({ id, seq, channelId,
+ createdAt: "2026-08-07T10:00:00.000Z", content: "canonical content", authorId: "u_me",
+ authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png",
+ embeds: [{ title: "Canonical embed" }], ...fields })
}
function sidebarData(threadId = "post_1") {
@@ -78,8 +76,8 @@ function sidebarData(threadId = "post_1") {
async function seedParent(type: "forum" | "text", parentId = "forum_1") {
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: parentId, name: "Parent", active: false, unread: false, type }] }] })
+ sync.ingestServers(canonicalRegistry, serverRailResponseFixture({ servers: [{ id: "s1", name: "Server", initial: "S", active: false, unread: false, mentions: 0, ownerId: "u_me" }] }, (canonicalRegistry)!.accountId))
+ sync.ingestServerDetail(canonicalRegistry, serverDirectoryFixture({ id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "u_me", categories: [{ id: "cat_1", name: "Category", channels: [{ id: parentId, name: "Parent", active: false, unread: false, type }] }] }))
capturedQc.setQueryData(communityKeys.server("s1"), "s1")
}
beforeEach(async () => {
@@ -112,39 +110,70 @@ function attentionIncluded(overrides: {
}
}
+function attentionScenarioFixture(scenario: Pick<AccountAttentionSnapshot, "scopes" | "items" | "limit" | "truncated"> & { included?: ReturnType<typeof attentionIncluded> }) {
+ const scopes = scenario.scopes
+ const channels = scopes.map(scope => channelResourceFixture({ id: scope.channelId, serverId: scope.serverId ?? null,
+ type: scope.serverId ? "text" : "dm", name: scope.serverId ? "Channel" : null }))
+ const servers = [...new Set(scopes.flatMap(scope => scope.serverId ? [scope.serverId] : []))].map(id => serverResourceFixture({ id, ownerId: "u_me" }))
+ const declaredProfiles = new Map((scenario.included?.profiles ?? []).map(profile => [String(profile.userId), profile]))
+ const peerIds = scopes.filter(scope => !scope.serverId).map(scope => `peer-${scope.channelId}`)
+ const profiles = [...new Set([...scenario.items.flatMap(item => item.actorUserId ? [item.actorUserId] : item.messageId ? ["system"] : []), ...peerIds, ...declaredProfiles.keys()])].map(id => {
+ const declared = declaredProfiles.get(id)
+ return { id, name: typeof declared?.name === "string" ? declared.name : id,
+ discriminator: typeof declared?.discriminator === "string" ? declared.discriminator : "0042",
+ avatar: typeof declared?.avatar === "string" ? declared.avatar : null,
+ avatarVersion: typeof declared?.avatarVersion === "number" ? declared.avatarVersion : 0 }
+ })
+ const declaredMessages = new Map((scenario.included?.messages ?? []).map(message => [String(message.id), message]))
+ const messages = [...new Set(scenario.items.flatMap(item => item.messageId ? [item.messageId] : []))].map(id => {
+ const item = scenario.items.find(row => row.messageId === id)!
+ const scope = scopes.find(row => row.scopeId === item.scopeId)!
+ const declared = declaredMessages.get(id)
+ return messageResourceFixture({ id, channelId: scope.channelId, authorId: item.actorUserId ?? "system", seq: scope.lastAttentionSeq ?? scope.lastUnreadSeq, createdAt: item.createdAt,
+ ...(typeof declared?.content === "string" ? { content: declared.content } : {}),
+ ...(typeof declared?.seq === "number" ? { seq: declared.seq } : {}) })
+ })
+ const resources = fullResourceBundleFixture("u_me", servers, channels, messages, profiles)
+ const included = { servers: servers.map(({ id, name, discriminator }) => ({ id, name, discriminator })),
+ channels: channels.filter(row => row.type !== "dm").map(row => AttentionIncludedChannelSchema.strip().parse(row)),
+ dms: scopes.filter(scope => !scope.serverId).map(scope => {
+ const profile = profiles.find(row => row.id === `peer-${scope.channelId}`)!
+ return { id: scope.channelId, userId: profile.id, name: profile.name, discriminator: "1234", avatar: profile.avatar, avatarVersion: profile.avatarVersion,
+ lastMessageAt: "2026-09-27T00:00:00Z", lastUnreadSeq: scope.lastUnreadSeq }
+ }),
+ profiles: profiles.map(({ id, ...profile }) => ({ userId: id, ...profile })),
+ messages: messages.map(row => AttentionIncludedMessageSchema.strip().parse(row)),
+ }
+ return AccountAttentionSnapshotSchema.parse({ scopes, items: scenario.items, limit: scenario.limit, truncated: scenario.truncated, resources, included })
+}
+
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: [{
+ sync.ingestServers(canonicalRegistry, serverRailResponseFixture({ servers: [{
id: "s1", name: "Server", initial: "S", active: false, unread: false,
mentions: 0, ownerId: "u_me",
- }] })
- sync.ingestServerDetail(canonicalRegistry, {
+ }] }, (canonicalRegistry)!.accountId))
+ sync.ingestServerDetail(canonicalRegistry, serverDirectoryFixture({
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,
- },
- })
+ const server = serverResourceFixture({ id: "s1", ownerId: "u_me" })
+ const parent = channelResourceFixture({ id: "forum_1", serverId: "s1", type: "forum" })
+ const channel = channelResourceFixture({ id: "post_1", serverId: "s1", name: "Post", type: "thread", parentChannelId: "forum_1", parentMessageId: "opener_1", lastMessageAt: "2026-08-06T00:00:00.000Z" })
+ const opener = messageResourceFixture({ id: "opener_1", channelId: "forum_1", content: "Old title" })
+ sync.publishCommunityForumSidebar(capturedQc, { serverId: "s1", resources: fullResourceBundleFixture("u_me", [server], [parent, channel], [opener], messageProfilesFixture([opener])),
+ channels: [{ ...channel, activityAt: channel.lastMessageAt!, unread: false, participating: true }], openers: [opener],
+ proof: { token: sync.captureCommunityLiveSnapshotToken(capturedQc) } })
}
async function canonicalSidebar() {
@@ -167,11 +196,12 @@ describe("useSendMessage — happy path", () => {
const runtime = canonicalRegistry.runtime
runtime.ui.actions.setCurrentServerId(scope.serverId)
runtime.ui.actions.subscribe({ channelId: scope.id })
- const replyTo = { id: "reply_1", authorName: "Reply Author", text: "preview" }
+ const replyTo = { id: "reply_1", authorId: "reply-author", authorName: "Reply Author", text: "preview" }
const attachment = { id: "file_1", filename: "notes.txt", contentType: "text/plain", size: 1024 }
const remoteAttachment = { kind: "file" as const, name: attachment.filename,
url: "/api/community/channels/ch_1/attachments/file_1", contentType: attachment.contentType,
sizeBytes: attachment.size, size: "1.0 KB" }
+ const wireAttachment = { id: attachment.id, name: remoteAttachment.name, url: remoteAttachment.url, contentType: remoteAttachment.contentType, sizeBytes: remoteAttachment.sizeBytes, thumbnailUrl: null, width: null, height: null }
const revoke = vi.fn(), originalRevoke = URL.revokeObjectURL
URL.revokeObjectURL = revoke
try {
@@ -190,11 +220,11 @@ describe("useSendMessage — happy path", () => {
const { dispatchCommunityWsEvent } = await import("@/hooks/community/community-ws/registry")
const { getMessageStreamState } = await import("@/test/community-query-owner")
const { materializeMessageStream } = await import("@/lib/community/message-stream")
- const older = { id: "older", seq: 1, type: "chat" as const, content: "anchor", authorId: "peer", createdAt: "2026-08-07T09:00:00.000Z" }
+ const older = messageResourceFixture({ id: "older", channelId: scope.id, seq: 1, content: "anchor", authorId: "peer", createdAt: "2026-08-07T09:00:00.000Z" })
let currentBase: import("@/lib/community/message-stream").CanonicalMessage[] = [older]
for (const stage of stages) {
if (stage === "post") {
- await act(async () => { release({ message: postedMessage("server_id_1", 9) }); await pending })
+ await act(async () => { release({ profiles: messageProfilesFixture([postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo, attachments: [wireAttachment] })]), message: postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo, attachments: [wireAttachment] }) }); await pending })
expect(getMessageStreamState(capturedQc, scope).liveIds).toContain("server_id_1")
expect(materializeMessageStream([], getMessageStreamState(capturedQc, scope), canonicalMessageReader(capturedQc)).find(row => row.id === "server_id_1")).toMatchObject({
id: "server_id_1", seq: 9, authorName: "Canonical Name", content: "canonical content",
@@ -202,12 +232,17 @@ describe("useSendMessage — happy path", () => {
embeds: [{ title: "Canonical embed" }], replyTo, attachments: [remoteAttachment], clientNonce: "n1", failed: false,
})
} else if (stage === "ws") {
- await act(async () => { dispatchCommunityWsEvent({ type: "community:message.create", serverId: scope.serverId,
- channelId: scope.id, message: { id: "server_id_1", seq: 9, type: "chat", authorId: "u_me",
+ await act(async () => { dispatchCommunityWsEvent({ profiles: messageProfilesFixture([{ id: "server_id_1", channelId: scope.id, seq: 9, type: "chat", authorId: "u_me",
+ authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png", authorAvatarVersion: 0, content: "canonical content",
+ createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyToId: replyTo.id, replyTo,
+ embeds: [{ title: "Canonical embed" }],
+ attachments: [wireAttachment],
+ }]), type: "community:message.create", serverId: scope.serverId,
+ channelId: scope.id, message: { id: "server_id_1", channelId: scope.id, seq: 9, type: "chat", authorId: "u_me",
authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png", authorAvatarVersion: 0, content: "canonical content",
- createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyTo,
+ createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyToId: replyTo.id, replyTo,
embeds: [{ title: "Canonical embed" }],
- attachments: [{ ...attachment, url: remoteAttachment.url }],
+ attachments: [wireAttachment],
} }, { deliveryMode: "single", queryClient: capturedQc, communityStore: runtime.ui, wsStore: runtime.ws,
sub: { channelId: scope.id }, viewerUserIdRef: { current: "u_me" },
matchesFocus: event => event.channelId === scope.id }) })
@@ -215,24 +250,24 @@ describe("useSendMessage — happy path", () => {
const { channelMessagesQueryFn } = await import("@/hooks/community/use-messages")
const { decodeCommunityReadResponse } = await import("@/lib/community/read-response")
const path = `/api/community/channels/${scope.id}/messages`
- const confirmed = { id: "server_id_1", seq: 9, type: "chat", authorId: "u_me",
- authorName: "Canonical Name", authorAvatar: "https://avatar.test/me.png", authorAvatarVersion: 0,
- content: "canonical content", createdAt: "2026-08-07T10:00:00.000Z", clientNonce: "n1", replyTo,
- embeds: [{ title: "Canonical embed" }], attachments: [remoteAttachment] }
- apiFetchMock.mockResolvedValueOnce(decodeCommunityReadResponse(path, "GET", new Response(),
- { messages: [older, confirmed], latestSeq: 9, hasMore: false }))
+ const confirmed = postedMessage("server_id_1", 9, scope.id, { clientNonce: "n1", replyToId: replyTo.id, replyTo, attachments: [wireAttachment] })
+ apiFetchMock.mockResolvedValueOnce(decodeCommunityReadResponse(path, "GET", new Response(null, { headers: { "X-Alook-Community-Contract": String(BUSINESS_SCHEMA_VERSION) } }), { profiles: messageProfilesFixture([older, confirmed]),
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: scope.id, messages: [older, confirmed],
+ surfaceReceipt: { channelId: scope.id, surfaceKind: "channel" },
+ page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 9 },
+ }))
await act(async () => { await channelMessagesQueryFn(scope.id, undefined, { queryClient: capturedQc })({ pageParam: { mode: "newest" } })
const canonical = canonicalRegistry.collections.messages.get(confirmed.id)
if (typeof canonical?.seq !== "number") throw new Error("Missing confirmed canonical seq")
currentBase = [older, { ...canonical, seq: canonical.seq }]
runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: currentBase, latestSeq: 9 }) })
- expect(canonicalRegistry.collections.messages.get(confirmed.id)?.attachments).toEqual([{ name: remoteAttachment.name, url: remoteAttachment.url, contentType: remoteAttachment.contentType, sizeBytes: remoteAttachment.sizeBytes }])
+ expect(canonicalRegistry.collections.messages.get(confirmed.id)?.attachments).toEqual([wireAttachment])
expect(materializeMessageStream(currentBase, getMessageStreamState(capturedQc, scope), canonicalMessageReader(capturedQc))).toEqual([
expect.objectContaining({ id: older.id }),
expect.objectContaining({ id: confirmed.id, replyTo, attachments: [remoteAttachment] }),
])
} else {
- await act(async () => { ingestMessages(canonicalRegistry, scope.id, [older])
+ await act(async () => { ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [older]))
runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: [older], latestSeq: 100 }) })
}
}
@@ -251,7 +286,7 @@ describe("useSendMessage — happy path", () => {
it("keeps Query base-only and acknowledges the accepted overlay intent", async () => {
capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))
- apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
+ apiFetchMock.mockResolvedValueOnce({ profiles: messageProfilesFixture([postedMessage("server_id_1", 9, "ch_1", { clientNonce: "n1" })]), message: postedMessage("server_id_1", 9, "ch_1", { clientNonce: "n1" }) })
const mod = await loadMod()
const stream = await import("@/test/community-query-owner")
@@ -278,11 +313,11 @@ describe("useSendMessage — happy path", () => {
expect(overlay.liveIds).toContain("server_id_1")
expect(materializeMessageStream([], overlay, canonicalMessageReader(capturedQc)).find(row => row.id === "server_id_1")).toMatchObject({ seq: 9, authorId: "u_me", content: "canonical content", clientNonce: "n1" })
expect(canonicalRegistry.collections.messages.get("server_id_1")).toMatchObject({ authorId: "u_me", content: "canonical content", embeds: [{ title: "Canonical embed" }] })
- expect(canonicalRegistry.collections.profiles.get("u_me")?.name).toBe("Canonical Name")
+ expect(canonicalRegistry.collections.profiles.get("u_me")).toMatchObject({ id: "u_me", name: "Canonical Name", discriminator: "0042", avatar: "https://avatar.test/me.png", avatarVersion: 0 })
})
it("re-ranks a loaded participating forum thread from the canonical send timestamp", async () => {
- apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
+ apiFetchMock.mockResolvedValueOnce({ profiles: messageProfilesFixture([postedMessage("server_id_1", 9, "post_1")]), message: postedMessage("server_id_1", 9, "post_1") })
const mod = await loadMod()
await installCanonicalRegistry()
await seedCanonicalSidebar()
@@ -306,7 +341,7 @@ describe("useSendMessage — happy path", () => {
it("invalidates the sidebar collection when a just-enrolled thread is not loaded", async () => {
const sidebarKey = communityKeys.forumSidebarThreads("s1")
capturedQc.setQueryData(sidebarKey, { ...sidebarData(), threads: [] })
- apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
+ apiFetchMock.mockResolvedValueOnce({ profiles: messageProfilesFixture([postedMessage("server_id_1", 9, "post_new")]), message: postedMessage("server_id_1", 9, "post_new") })
const mod = await loadMod()
await installCanonicalRegistry()
await seedCanonicalParent("forum")
@@ -341,7 +376,7 @@ describe("useSendMessage — happy path", () => {
capturedQc.getQueryData(metaKey),
capturedQc.getQueryData(hintKey),
]
- apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
+ apiFetchMock.mockResolvedValueOnce({ profiles: messageProfilesFixture([postedMessage("server_id_1", 9, "text_thread")]), message: postedMessage("server_id_1", 9, "text_thread") })
const mod = await loadMod()
mountHook(() => mod.useSendMessage())
@@ -429,7 +464,7 @@ async function acceptDmIntent(nonce = "n1") {
describe("useSendDmMessage — overlay terminal emitter", () => {
it("keeps Query base-only and emits exactly one postAck", async () => {
capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))
- apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_1", 8) })
+ apiFetchMock.mockResolvedValueOnce({ profiles: messageProfilesFixture([postedMessage("server_1", 8, "dm_1", { clientNonce: "n1" })]), message: postedMessage("server_1", 8, "dm_1", { clientNonce: "n1" }) })
const mod = await loadMod()
const stream = await acceptDmIntent()
const dispatch = vi.spyOn(canonicalRegistry.runtime.messageStream.actions, "dispatch")
@@ -493,7 +528,7 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
})
it("continues the upload intent when its view retires after upload succeeds, before native POST", async () => {
- apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
+ apiFetchMock.mockResolvedValueOnce({ profiles: messageProfilesFixture([messageResourceFixture({ id: "confirmed", channelId: "ch_1", seq: 12, content: "keep optimistic", authorId: "u_me", authorName: "Me", authorAvatar: null, authorAvatarVersion: 0, clientNonce: "upload-view", createdAt: "2026-10-09T01:00:00Z", embeds: [] })]), message: messageResourceFixture({ id: "confirmed", channelId: "ch_1", seq: 12, content: "keep optimistic", authorId: "u_me", authorName: "Me", authorAvatar: null, authorAvatarVersion: 0, clientNonce: "upload-view", createdAt: "2026-10-09T01:00:00Z", embeds: [] }) })
const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }, runtime = canonicalRegistry.runtime
const file = new File(["x"], "x.txt", { type: "text/plain" })
runtime.messageStream.actions.accept(scope, { nonce: "upload-view", tempId: "temp-upload-view", message: { type: "chat", content: "file", authorId: "u_me" }, localUploads: [{ file, previewObjectUrl: "blob:view" }] })
@@ -517,7 +552,7 @@ describe("useSendDmMessage — overlay terminal emitter", () => {
})
it("continues the accepted channel intent when its view retires before native POST starts", async () => {
- apiFetchMock.mockResolvedValueOnce({ message: { id: "confirmed", seq: 12, type: "chat", content: "keep optimistic", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T01:00:00Z", embeds: [] } })
+ apiFetchMock.mockResolvedValueOnce({ profiles: messageProfilesFixture([messageResourceFixture({ id: "confirmed", channelId: "ch_1", seq: 12, content: "keep optimistic", authorId: "u_me", authorName: "Me", authorAvatar: null, authorAvatarVersion: 0, clientNonce: "retired_view", createdAt: "2026-10-09T01:00:00Z", embeds: [] })]), message: messageResourceFixture({ id: "confirmed", channelId: "ch_1", seq: 12, content: "keep optimistic", authorId: "u_me", authorName: "Me", authorAvatar: null, authorAvatarVersion: 0, clientNonce: "retired_view", createdAt: "2026-10-09T01:00:00Z", embeds: [] }) })
const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
const runtime = canonicalRegistry.runtime
runtime.messageStream.actions.accept(scope, { nonce: "retired_view", tempId: "temp_retired_view",
@@ -710,14 +745,25 @@ describe("useUnpinMessage — rollback", () => {
// ── useCreateThread ───────────────────────────────────────────────────────
describe("useCreateThread — patches parent message + invalidates threads", () => {
+ it.each(["partial", "server", "parent", "opener"] as const)("rejects %s thread create confirmation without publishing a channel", async mismatch => {
+ const channel = channelResourceFixture({ id: "wrong_thread", type: "thread", serverId: mismatch === "server" ? "other" : "s1",
+ parentChannelId: mismatch === "parent" ? "other" : "ch_parent", parentMessageId: mismatch === "opener" ? "other" : "m_p" })
+ apiFetchMock.mockResolvedValueOnce(mismatch === "partial" ? { id: "wrong_thread" } : channel)
+ const mod = await loadMod()
+ mountHook(() => mod.useCreateThread())
+ await expect(runMutation({ serverId: "s1", channelId: "ch_parent", messageId: "m_p", name: "Discussion" }))
+ .rejects.toThrow(mismatch === "partial" ? undefined : "Created thread scope mismatch")
+ expect(canonicalRegistry.collections.channels.has("wrong_thread")).toBe(false)
+ })
+
it("adds thread indicator to the parent message with messageCount: 0", async () => {
// Regression: previously patched messageCount=1 on the assumption that
// the parent message was cloned into the thread. #6 removed the
// parent-clone, so new threads start empty. `messageCount` MUST be 0
// to avoid the UI showing "1 reply" on an empty thread.
- ingestMessages(canonicalRegistry, "ch_parent", [{ id: "m_p", type: "chat", content: "Opener" }])
+ ingestMessages(canonicalRegistry, "ch_parent", messageSeedFixture("ch_parent", [{ id: "m_p", type: "chat", content: "Opener" }]))
capturedQc.setQueryData(communityKeys.channelMessages("ch_parent"), makeCache([{ id: "m_p" }]))
- apiFetchMock.mockResolvedValueOnce({ id: "thr_1" })
+ apiFetchMock.mockResolvedValueOnce(channelResourceFixture({ id: "thr_1", serverId: "s1", type: "thread", parentChannelId: "ch_parent", parentMessageId: "m_p", name: "Discussion" }))
const mod = await loadMod()
mountHook(() => mod.useCreateThread())
await runMutation({ serverId: "s1", channelId: "ch_parent", messageId: "m_p", name: "Discussion" })
@@ -750,7 +796,7 @@ describe("useMarkAllInboxRead", () => {
const mod = await loadMod()
await installCanonicalRegistry()
const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
- ingestAttentionSnapshot(canonicalRegistry!, {
+ ingestAttentionSnapshot(canonicalRegistry!, attentionScenarioFixture({
scopes: [{
scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: 1, attentionCount: 1,
@@ -765,7 +811,7 @@ describe("useMarkAllInboxRead", () => {
}],
limit: 100,
truncated: false,
- })
+ }))
capturedQc.setQueryData(communityKeys.inboxUnreads(), {
servers: [{ serverId: "s_1", serverName: "s", channels: [{ channelId: "ch_1" }] }],
})
@@ -788,7 +834,7 @@ describe("useMarkAllInboxRead", () => {
expect(canonicalRegistry!.collections.attentionItems.get("mention:men_1")).toBeUndefined()
expect(canonicalRegistry!.collections.attentionItems.get("friend_request:f_1")).toBeDefined()
})
- apiFetchMock.mockResolvedValue({ scopes: [], items: [], limit: 100, truncated: false })
+ apiFetchMock.mockResolvedValue(attentionScenarioFixture({ scopes: [], items: [], limit: 100, truncated: false }))
await act(async () => { release({ revision: 2 }); await pending })
})
@@ -800,7 +846,7 @@ describe("useMarkAllInboxRead", () => {
return { revision: 3 }
}
if (path === "/api/community/users/me/attention") {
- return { scopes: [], items: [], limit: 100, truncated: false }
+ return attentionScenarioFixture({ scopes: [], items: [], limit: 100, truncated: false })
}
if (path === "/api/community/users/me/read-state") {
return { revision: 3, readStates: [] }
@@ -825,7 +871,7 @@ describe("useMarkAllInboxRead", () => {
const mod = await loadMod()
await installCanonicalRegistry()
const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
- const mentionOnly = {
+ const mentionOnly = attentionScenarioFixture({
scopes: [{
scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,
@@ -836,7 +882,7 @@ describe("useMarkAllInboxRead", () => {
}],
limit: 100,
truncated: false,
- }
+ })
ingestAttentionSnapshot(canonicalRegistry!, {
...mentionOnly,
scopes: [{ ...mentionOnly.scopes[0]!, ordinaryUnread: true }],
@@ -873,7 +919,7 @@ describe("useMarkAllInboxRead", () => {
it("restores canonical attention when the atomic read-all request fails", async () => {
await installCanonicalRegistry()
const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
- ingestAttentionSnapshot(canonicalRegistry!, {
+ ingestAttentionSnapshot(canonicalRegistry!, attentionScenarioFixture({
scopes: [{
scopeId: "channel", channelId: "channel", serverId: "s_1", parentChannelId: null,
ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: null, attentionCount: 0,
@@ -881,7 +927,7 @@ describe("useMarkAllInboxRead", () => {
items: [],
limit: 100,
truncated: false,
- })
+ }))
apiFetchMock.mockRejectedValue(new Error("account read-all failed"))
const mod = await loadMod()
mountHook(() => mod.useMarkAllInboxRead())
@@ -899,7 +945,7 @@ describe("useMarkAllInboxRead", () => {
const { ingestAttentionSnapshot, ingestMessages, projectCommunityWsEventToDb } = await import(
"@/lib/community-db/sync"
)
- const canonical = {
+ const canonical = attentionScenarioFixture({
scopes: [{
scopeId: "channel", channelId: "channel", serverId: "s_1", parentChannelId: null,
ordinaryUnread: true, lastUnreadSeq: 1, lastAttentionSeq: null, attentionCount: 0,
@@ -908,7 +954,7 @@ describe("useMarkAllInboxRead", () => {
limit: 100,
truncated: false,
included: attentionIncluded(),
- }
+ })
ingestAttentionSnapshot(canonicalRegistry!, canonical)
let fail!: (error: Error) => void
const held = new Promise((_, reject) => { fail = reject })
@@ -921,7 +967,7 @@ describe("useMarkAllInboxRead", () => {
mountHook(() => mod.useMarkAllInboxRead())
const pending = startMutation(undefined)
await waitFor(() => expect(canonicalRegistry.collections.attentionScopes.get("channel")).toBeUndefined())
- ingestMessages(canonicalRegistry!, "other", [{ id: "event", type: "chat", content: "old" }])
+ ingestMessages(canonicalRegistry!, "other", messageSeedFixture("other", [{ id: "event", type: "chat", content: "old" }]))
projectCommunityWsEventToDb(capturedQc, {
type: "community:reaction.add",
channelId: "other",
@@ -977,7 +1023,7 @@ describe("useDeleteMention — rollback", () => {
const mod = await loadMod()
await installCanonicalRegistry()
const { ingestAttentionSnapshot } = await import("@/lib/community-db/sync")
- const canonical = {
+ const canonical = attentionScenarioFixture({
scopes: [{
scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,
@@ -997,7 +1043,7 @@ describe("useDeleteMention — rollback", () => {
createdAt: "2026-09-27T00:00:00.000Z", seq: 4, type: "chat",
}],
}),
- }
+ })
ingestAttentionSnapshot(canonicalRegistry!, canonical)
capturedQc.setQueryData(communityKeys.inboxMentions(), {
mentions: [{ id: "men_1", channelId: "ch_1", kind: "mention", m: { id: "m_1", seq: 4 } }],
@@ -1025,7 +1071,7 @@ describe("useDeleteMention — rollback", () => {
const { ingestAttentionSnapshot, ingestMessages, projectCommunityWsEventToDb } = await import(
"@/lib/community-db/sync"
)
- const canonical = {
+ const canonical = attentionScenarioFixture({
scopes: [{
scopeId: "ch_1", channelId: "ch_1", serverId: "s_1", parentChannelId: null,
ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,
@@ -1045,7 +1091,7 @@ describe("useDeleteMention — rollback", () => {
createdAt: "2026-09-27T00:00:00.000Z", seq: 4, type: "chat",
}],
}),
- }
+ })
ingestAttentionSnapshot(canonicalRegistry!, canonical)
capturedQc.setQueryData(communityKeys.inboxMentions(), {
mentions: [{ id: "men_1", channelId: "ch_1", kind: "mention", m: { id: "m_1", seq: 4 } }],
@@ -1060,7 +1106,7 @@ describe("useDeleteMention — rollback", () => {
mountHook(() => mod.useDeleteMention())
const pending = startMutation({ mentionId: "men_1" })
await waitFor(() => expect(canonicalRegistry.collections.attentionItems.get("mention:men_1")).toBeUndefined())
- ingestMessages(canonicalRegistry!, "other", [{ id: "event", type: "chat", content: "old" }])
+ ingestMessages(canonicalRegistry!, "other", messageSeedFixture("other", [{ id: "event", type: "chat", content: "old" }]))
projectCommunityWsEventToDb(capturedQc, {
type: "community:reaction.add",
channelId: "other",
@@ -1097,10 +1143,10 @@ describe("useDeleteMention — rollback", () => {
const { ingestAttentionSnapshot, ingestMessages } = await import(
"@/lib/community-db/sync"
)
- ingestMessages(canonicalRegistry!, "ch_1", [{
+ ingestMessages(canonicalRegistry!, "ch_1", messageSeedFixture("ch_1", [{
id: "msg_1", type: "chat", authorId: "u_2", seq: 4,
- }])
- ingestAttentionSnapshot(canonicalRegistry!, {
+ }]))
+ ingestAttentionSnapshot(canonicalRegistry!, attentionScenarioFixture({
scopes: [{
scopeId: "ch_1", channelId: "ch_1", serverId: "srv_1", parentChannelId: null,
ordinaryUnread: false, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 2,
@@ -1116,7 +1162,7 @@ describe("useDeleteMention — rollback", () => {
})),
limit: 100,
truncated: false,
- })
+ }))
mountHook(() => mod.useDeleteMention())
let fail!: (error: Error) => void
apiFetchMock.mockImplementation((path: string) => path === "/api/community/users/me/attention"
@@ -1168,10 +1214,10 @@ describe("useDeleteMention — rollback", () => {
const { ingestAttentionSnapshot, ingestMessages } = await import(
"@/lib/community-db/sync"
)
- ingestMessages(canonicalRegistry!, "ch_1", [{
+ ingestMessages(canonicalRegistry!, "ch_1", messageSeedFixture("ch_1", [{
id: "msg_1", type: "chat", authorId: "u_2", seq: 4,
- }])
- ingestAttentionSnapshot(canonicalRegistry!, {
+ }]))
+ ingestAttentionSnapshot(canonicalRegistry!, attentionScenarioFixture({
scopes: [{
scopeId: "ch_1", channelId: "ch_1", serverId: "srv_1", parentChannelId: null,
ordinaryUnread: true, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: 1,
@@ -1182,7 +1228,7 @@ describe("useDeleteMention — rollback", () => {
}],
limit: 100,
truncated: false,
- })
+ }))
mountHook(() => mod.useDeleteMention())
let fail!: (error: Error) => void
apiFetchMock.mockImplementation((path: string) => path === "/api/community/users/me/attention"
@@ -1247,7 +1293,7 @@ describe("useDeleteMention — rollback", () => {
describe("confirmed send failures", () => {
const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }
const args = { serverId: "s1", channelId: "ch_1", content: "hi", nonce: "n1", author: { id: "u_me", name: "me", avatar: "M" } }
- const confirmed = { id: "server_confirmed", seq: 7, type: "chat" as const, content: "hi", authorId: "u_me", clientNonce: "n1" }
+ const confirmed = messageResourceFixture({ id: "server_confirmed", channelId: "ch_1", seq: 7, content: "hi", authorId: "u_me", clientNonce: "n1" })
it.each(["ordinary", "network", "500", "503"].flatMap(kind => ["canonical", "ws", "base"].map(stage => [kind, stage])))("settles the existing intent when %s failure follows %s confirmation", async (kind, stage) => {
const { ApiError } = await import("@/lib/errors")
const error = kind === "ordinary" ? new Error("late failure") : new ApiError("late failure", kind === "network" ? 0 : Number(kind))
@@ -1257,13 +1303,13 @@ describe("confirmed send failures", () => {
apiFetchMock.mockImplementationOnce(async () => {
if (stage === "ws") {
const { dispatchCommunityWsEvent } = await import("@/hooks/community/community-ws/registry")
- dispatchCommunityWsEvent({ type: "community:message.create", serverId: scope.serverId, channelId: scope.id,
+ dispatchCommunityWsEvent({ profiles: messageProfilesFixture([{ ...confirmed, authorName: "Me", authorAvatar: "M", authorAvatarVersion: 0, createdAt: "2026-08-07T10:00:00.000Z" }]), type: "community:message.create", serverId: scope.serverId, channelId: scope.id,
message: { ...confirmed, authorName: "Me", authorAvatar: "M", authorAvatarVersion: 0, createdAt: "2026-08-07T10:00:00.000Z" } }, {
deliveryMode: "single", queryClient: capturedQc, communityStore: canonicalRegistry.runtime.ui, wsStore: canonicalRegistry.runtime.ws,
sub: { channelId: scope.id }, viewerUserIdRef: { current: "u_me" }, matchesFocus: event => event.channelId === scope.id,
})
} else {
- ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [confirmed]))
if (stage === "base") canonicalRegistry.runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: [confirmed] })
}
throw error
@@ -1278,7 +1324,7 @@ describe("confirmed send failures", () => {
it.each([400, 401, 403, 429])("retains explicit %s despite matching canonical confirmation", async (status) => {
const { ApiError } = await import("@/lib/errors")
const error = new ApiError("explicit rejection", status)
- ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [confirmed]))
apiFetchMock.mockRejectedValueOnce(error)
const mod = await loadMod()
mountHook(() => mod.useSendMessage())
@@ -1288,7 +1334,8 @@ describe("confirmed send failures", () => {
it.each([
{ authorId: "other" }, { clientNonce: "other" }, { seq: undefined }, { seq: 0 },
])("does not accept an invalid confirmation %j", async (change) => {
- ingestMessages(canonicalRegistry, scope.id, [{ ...confirmed, ...change }])
+ if ("seq" in change && change.seq === undefined) expect(() => ingestMessages(canonicalRegistry, scope.id, [{ ...confirmed, ...change }])).toThrow()
+ else ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [{ ...confirmed, ...change }]))
apiFetchMock.mockRejectedValueOnce(new Error("not confirmed"))
const mod = await loadMod()
mountHook(() => mod.useSendMessage())
@@ -1296,7 +1343,7 @@ describe("confirmed send failures", () => {
expect(toastMock).toHaveBeenCalledWith("not confirmed")
})
it.each(["owner", "view", "abort", "synthetic nonce"])("does not confirm after %s loses eligibility", async (mode) => {
- ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [confirmed]))
const { useCommunityMutationOrigin } = await import("../community-origin")
const origin = mountHook(() => useCommunityMutationOrigin()), original = origin.begin().token
const mod = await loadMod()
@@ -1311,7 +1358,7 @@ describe("confirmed send failures", () => {
URL.revokeObjectURL = revoke
try {
canonicalRegistry.runtime.messageStream.actions.accept(scope, { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi", authorId: "u_me" }, localUploads: [{ file: new File(["x"], "x.txt"), previewObjectUrl: "blob:confirmed" }] })
- apiFetchMock.mockImplementationOnce(async () => { ingestMessages(canonicalRegistry, scope.id, [confirmed]); throw new Error("late failure") })
+ apiFetchMock.mockImplementationOnce(async () => { ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [confirmed])); throw new Error("late failure") })
const mod = await loadMod()
mountHook(() => mod.useSendMessage())
await runMutation(args).catch(() => {})
@@ -1323,10 +1370,10 @@ describe("confirmed send failures", () => {
} finally { URL.revokeObjectURL = originalRevoke }
})
it.each([{ id: "" }, { seq: -1 }, { seq: 1.5 }, { seq: Number.MAX_SAFE_INTEGER + 1 }])("rejects invalid server id/seq at canonical ingestion %j", (change) => {
- expect(() => ingestMessages(canonicalRegistry, scope.id, [{ ...confirmed, ...change }])).toThrow()
+ expect(() => ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [{ ...confirmed, ...change }]))).toThrow()
})
it("does not accept another target or an absent outbox as confirmation", async () => {
- ingestMessages(canonicalRegistry, "other_channel", [confirmed])
+ ingestMessages(canonicalRegistry, "other_channel", messageSeedFixture("other_channel", [{ ...confirmed, channelId: "other_channel" }]))
apiFetchMock.mockRejectedValueOnce(new Error("not confirmed"))
const mod = await loadMod()
mountHook(() => mod.useSendMessage())
@@ -1341,7 +1388,7 @@ describe("confirmed send failures", () => {
await runMutation(args).catch(() => {})
expect(toastMock).toHaveBeenCalledWith("not confirmed yet")
expect(getMessageStreamState(capturedQc, scope).outboxByNonce.get("n1")?.status).toBe("failed")
- ingestMessages(canonicalRegistry, scope.id, [confirmed])
+ ingestMessages(canonicalRegistry, scope.id, messageSeedFixture(scope.id, [confirmed]))
canonicalRegistry.runtime.messageStream.actions.dispatch(scope, { type: "wsMessage", message: confirmed })
expect(getMessageStreamState(capturedQc, scope).outboxByNonce.size).toBe(0)
})
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index be82b9aa1..fe146283f 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -1,5 +1,7 @@
"use client"
+import { CommunityChannelResourceSchema, type CommunityChannelResource, type CommunityMessagePosted } from "@alook/shared"
+
import { captureOnboardingFirstMessage } from "@/lib/product-analytics"
import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
@@ -124,7 +126,7 @@ export type SendMessageArgs = {
// the same nonce — `message` is the canonical (original) row, nothing new was
// inserted. The caller treats it as success (reconcile the optimistic row,
// clear the failed pill), never as a failure to resend.
-export type SendMessageResult = { message: PostedMessage; deduped?: boolean }
+export type SendMessageResult = Pick<CommunityMessagePosted, "message" | "profiles"> & { deduped?: boolean }
/**
* Channel/thread send. The server infers thread-vs-channel routing from the
@@ -159,16 +161,8 @@ export function getConfirmedSentMessage(
}
}
-function postedMessageForIntent(message: PostedMessage, nonce: string, channelId: string, attachments?: readonly UploadFileResult[]) {
- const canonical = projectPostedMessage(message, nonce, channelId)
- if (canonical.resourceComplete || canonical.attachments !== undefined || !attachments?.length) return canonical
- return { ...canonical, attachments: attachments.map((attachment) => ({
- id: attachment.id, name: attachment.filename, url: attachmentUrl(channelId, attachment.id),
- contentType: attachment.contentType, sizeBytes: attachment.size,
- ...(attachment.hasThumbnail === undefined ? {} : { thumbnailUrl: attachment.hasThumbnail ? attachmentThumbnailUrl(channelId, attachment.id) : null }),
- ...(attachment.width === undefined ? {} : { width: attachment.width }),
- ...(attachment.height === undefined ? {} : { height: attachment.height }),
- })) }
+function postedMessageForIntent(message: PostedMessage, nonce: string, channelId: string) {
+ return projectPostedMessage(message, nonce, channelId)
}
function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(kind: MessageScope["kind"]) {
@@ -190,8 +184,8 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
})
await origin.registry!.collections.messages.preload()
origin.assert(token); (assertCommand ?? assertActive)?.()
- const message = postedMessageForIntent(result.message, nonce ?? "", scope.id, attachments)
- publishCommunityMessages(queryClient, { channelId: scope.id,
+ const message = postedMessageForIntent(result.message, nonce ?? "", scope.id)
+ publishCommunityMessages(queryClient, { channelId: scope.id, profiles: result.profiles,
messages: [{ ...message, ...(acceptedReply && !("replyTo" in result.message) && (!("replyToId" in result.message) || result.message.replyToId === acceptedReply.id) ? { replyTo: acceptedReply } : {}) }],
proof: { token, ...(scope.kind === "channel" && !assertCommand ? { signal: assertActive?.signal } : {}) } })
return result
@@ -243,7 +237,7 @@ function useSendScopedMessage<Args extends SendMessageArgs | SendDmMessageArgs>(
const scope = sendMessageScope(args)
const nonce = args.nonce ?? ""
if (scope.kind === "dm" || args.nonce) getCommunityRuntime(queryClient).messageStream.actions.dispatch(scope, {
- type: "postAck", nonce, message: postedMessageForIntent(data.message, nonce, scope.id, args.attachments),
+ type: "postAck", nonce, message: postedMessageForIntent(data.message, nonce, scope.id),
})
},
})
@@ -280,7 +274,7 @@ export type CreateThreadArgs = {
name: string
}
-export type CreateThreadResult = { id: string }
+export type CreateThreadResult = CommunityChannelResource
export function useCreateThread() {
const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()
@@ -294,7 +288,10 @@ export function useCreateThread() {
await Promise.all([origin.registry!.collections.channels.preload(), origin.registry!.collections.messages.preload()])
origin.assert(token); args.assertActive?.()
const data = await origin.request<CreateThreadResult>(token, "/api/community/channels", { method: "POST", signal: args.assertActive?.signal, assertActive: args.assertActive, body: JSON.stringify({ type: "thread", messageId: args.messageId, name: args.name }) })
- publishCommunityCreatedChannel(queryClient, { id: data.id, serverId: args.serverId, categoryId: null, name: args.name, type: "thread", parentChannelId: args.channelId, parentMessageId: args.messageId, creatorId: origin.registry!.accountId, position: 0, archived: false, muted: false, tags: [], pending: false, messageCount: 0 }, { token, signal: args.assertActive?.signal })
+ origin.assert(token); args.assertActive?.()
+ const channel = CommunityChannelResourceSchema.parse(data)
+ if (channel.type !== "thread" || channel.serverId !== args.serverId || channel.parentChannelId !== args.channelId || channel.parentMessageId !== args.messageId) throw new Error("Created thread scope mismatch")
+ publishCommunityCreatedChannel(queryClient, { ...channel, pending: false }, { token, signal: args.assertActive?.signal })
if (args.resource && queryClient.getQueryCache().find({ queryKey: communityKeys.threads(args.channelId), exact: true }) === args.resource) void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.channelId), exact: true }, { cancelRefetch: false }).catch(() => undefined)
return data
},
diff --git a/src/web/src/hooks/community/mutations/profile.dom.test.ts b/src/web/src/hooks/community/mutations/profile.dom.test.ts
index 72915e075..b7f6d46a4 100644
--- a/src/web/src/hooks/community/mutations/profile.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/profile.dom.test.ts
@@ -35,7 +35,7 @@ describe("useUpdateProfile", () => {
)
const rendered = renderHook(() => useUpdateProfile(), { wrapper })
- let result!: typeof response
+ let result!: unknown
await act(async () => {
result = await rendered.result.current.mutateAsync({
name: "Renamed",
@@ -51,11 +51,12 @@ describe("useUpdateProfile", () => {
authenticationAccount: "viewer", signal: expect.any(AbortSignal), assertActive: expect.any(Function),
}),
)
- expect(result).toBe(response)
+ expect(result).toEqual(response)
})
it("keeps public methods stable and returns only the original business input to per-call callbacks", async () => {
const owner = await createCommunityQueryOwner()
+ owner.registry.collections.profiles.utils.writeUpsert({ id: "viewer", name: "Before", discriminator: "0042", avatar: null, avatarVersion: 0 })
const { useUpdateProfile } = await import("./profile")
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
const rendered = renderHook(() => useUpdateProfile(), { wrapper })
@@ -93,3 +94,81 @@ describe("useUpdateProfile", () => {
expect(owner.registry.collections.profiles.has("viewer")).toBe(false)
})
})
+
+it.each(["missing-core", "wrong-self"])("rejects a warm complete PATCH %s before command publication", async defect => {
+ const { communityRegistrySnapshot } = await import("@/test/community-registry-snapshot")
+ const { useUpdateProfile } = await import("./profile")
+ const owner = await createCommunityQueryOwner()
+ const initial = { id: "viewer", name: "Before", discriminator: "0042", avatar: null, avatarVersion: 3, aboutMe: "Keep about", bannerColor: null, statusEmoji: null, statusText: "Keep status" }
+ owner.registry.collections.profiles.utils.writeUpsert(initial)
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
+ const hook = renderHook(() => useUpdateProfile(), { wrapper })
+ const before = communityRegistrySnapshot(owner.registry)
+ const malformed: Record<string, unknown> = { ...initial, name: "Must not publish" }
+ if (defect === "missing-core") delete malformed.avatarVersion
+ if (defect === "wrong-self") malformed.id = "foreign"
+ apiFetchMock.mockResolvedValueOnce(malformed)
+ await act(async () => { await expect(hook.result.current.mutateAsync({ name: "Must not publish" })).rejects.toThrow() })
+ expect(communityRegistrySnapshot(owner.registry)).toEqual(before)
+ hook.unmount()
+})
+
+it("publishes only the confirmed command fields and keeps newer unrelated profile facts", async () => {
+ const { writeCommunityProfilePatches } = await import("@/lib/community/profile-seed")
+ const { useUpdateProfile } = await import("./profile")
+ const owner = await createCommunityQueryOwner()
+ const initial = { id: "viewer", name: "Before", discriminator: "0042", avatar: null, avatarVersion: 3, aboutMe: "Original about", bannerColor: null, statusEmoji: null, statusText: "Original status" }
+ owner.registry.collections.profiles.utils.writeUpsert(initial)
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
+ const hook = renderHook(() => useUpdateProfile(), { wrapper })
+ let release!: (value: unknown) => void
+ apiFetchMock.mockImplementationOnce(() => new Promise(done => { release = done }))
+ let operation!: Promise<unknown>
+ act(() => { operation = hook.result.current.mutateAsync({ name: "Confirmed" }) })
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ act(() => writeCommunityProfilePatches([{ id: "viewer", avatar: { avatar: "newer-avatar", avatarVersion: 6 }, status: { statusEmoji: "🌿", statusText: "Newer status" } }], owner.registry, { event: true }))
+ await act(async () => { release({ ...initial, name: "Confirmed", aboutMe: "Unrequested response about", bannerColor: "#abcdef" }); await operation })
+ expect(owner.registry.collections.profiles.get("viewer")).toMatchObject({ ...initial, name: "Confirmed", avatar: "newer-avatar", avatarVersion: 6, statusEmoji: "🌿", statusText: "Newer status" })
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ hook.unmount()
+})
+
+it.each([
+ { label: "status-only", command: { statusText: "Command status" }, name: "Read identity", status: "Command status" },
+ { label: "status-null", command: { statusText: null }, name: "Read identity", status: null },
+ { label: "name-only", command: { name: "Command name" }, name: "Command name", status: "Read status" },
+ { label: "name-with-undefined-status", command: { name: "Command name", statusText: undefined }, name: "Command name", status: "Read status" },
+])("keeps the in-flight card's independent groups for $label", async scenario => {
+ const { useUpdateProfile } = await import("./profile")
+ const { userProfileQueryFn } = await import("../use-user-profile")
+ const { communityKeys } = await import("@/lib/query-keys")
+ const { beginCommunityProfileSeed } = await import("@/lib/community/profile-seed")
+ const owner = await createCommunityQueryOwner()
+ const initial = { id: "viewer", name: "Before", discriminator: "0042", avatar: null, avatarVersion: 3, aboutMe: "Original about", bannerColor: null, statusEmoji: null, statusText: "Original status" }
+ owner.registry.collections.profiles.utils.writeUpsert(initial)
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
+ const hook = renderHook(() => useUpdateProfile(), { wrapper })
+ let releaseCard!: (value: unknown) => void
+ apiFetchMock.mockImplementation((path: string, options: { method?: string }) => {
+ if (path === "/api/community/users/viewer/profile") return new Promise(done => { releaseCard = done })
+ if (path === "/api/community/users/me/profile" && options.method === "PATCH") return Promise.resolve({
+ ...initial,
+ ...(scenario.command.name === undefined ? {} : { name: scenario.command.name }),
+ ...(scenario.command.statusText === undefined ? {} : { statusText: scenario.command.statusText }),
+ })
+ throw new Error(`Unexpected profile transport: ${path}`)
+ })
+ let read!: Promise<unknown>
+ act(() => { read = owner.client.query({ queryKey: communityKeys.profile("viewer"), queryFn: userProfileQueryFn("viewer") }) })
+ await waitFor(() => expect(releaseCard).toBeTypeOf("function"))
+ const beforeCommand = beginCommunityProfileSeed(owner.registry).revision
+ await act(async () => { await hook.result.current.mutateAsync(scenario.command) })
+ const afterCommand = beginCommunityProfileSeed(owner.registry).revision
+ expect(afterCommand).toBe(beforeCommand + 1)
+ const { avatar: _avatar, ...cardFields } = initial
+ await act(async () => { releaseCard({ ...cardFields, kind: "human", name: "Read identity", image: null, mutualServers: 2, statusText: "Read status" }); await read })
+ expect(owner.registry.collections.profiles.get("viewer")).toMatchObject({ name: scenario.name, statusText: scenario.status })
+ expect(beginCommunityProfileSeed(owner.registry).revision).toBe(afterCommand)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ hook.unmount()
+})
diff --git a/src/web/src/hooks/community/mutations/profile.ts b/src/web/src/hooks/community/mutations/profile.ts
index fc63c15ee..a68e9c127 100644
--- a/src/web/src/hooks/community/mutations/profile.ts
+++ b/src/web/src/hooks/community/mutations/profile.ts
@@ -1,5 +1,7 @@
"use client"
+import { parseCommunitySelfProfileRead, type CommunitySelfProfileRead } from "@alook/shared"
+
import { useNativeMutationFacade } from "@/hooks/use-native-mutation-facade"
import { useCallback } from "react"
@@ -18,17 +20,7 @@ export type UpdateProfileArgs = {
statusText?: string | null
}
-export type UpdateProfileResult = {
- id: string
- name: string
- discriminator: string
- avatar: string
- avatarVersion: number
- aboutMe: string
- bannerColor: string | null
- statusEmoji: string | null
- statusText: string | null
-}
+export type UpdateProfileResult = CommunitySelfProfileRead
/**
* PATCH the current user's profile card. The shell applies the canonical
@@ -42,12 +34,12 @@ export function useUpdateProfile() {
mutationFn: async ({ original, assertActive, ...patch }) => {
origin.assert(original); assertActive?.()
const snapshot = beginCommunityProfileSeed(origin.registry)
- const profile = await origin.request<UpdateProfileResult>(original, "/api/community/users/me/profile", { method: "PATCH", body: JSON.stringify(patch), signal: assertActive?.signal, assertActive })
+ const profile = parseCommunitySelfProfileRead(await origin.request<unknown>(original, "/api/community/users/me/profile", { method: "PATCH", body: JSON.stringify(patch), signal: assertActive?.signal, assertActive }), original.viewerId!)
origin.assert(original); assertActive?.()
writeCommunityProfilePatches([{
id: profile.id,
- identityAbout: { ...(patch.name === undefined ? {} : { name: profile.name }), ...(patch.aboutMe === undefined ? {} : { aboutMe: profile.aboutMe }) },
- ...("statusEmoji" in patch || "statusText" in patch ? { status: { ...(patch.statusEmoji === undefined ? {} : { statusEmoji: profile.statusEmoji }), ...(patch.statusText === undefined ? {} : { statusText: profile.statusText }) } } : {}),
+ ...(patch.name !== undefined || patch.aboutMe !== undefined ? { identityAbout: { ...(patch.name === undefined ? {} : { name: profile.name }), ...(patch.aboutMe === undefined ? {} : { aboutMe: profile.aboutMe }) } } : {}),
+ ...(patch.statusEmoji !== undefined || patch.statusText !== undefined ? { status: { ...(patch.statusEmoji === undefined ? {} : { statusEmoji: profile.statusEmoji }), ...(patch.statusText === undefined ? {} : { statusText: profile.statusText }) } } : {}),
}], snapshot.registry, { snapshot, command: true })
return profile
},
diff --git a/src/web/src/hooks/community/mutations/server-commands.dom.test.ts b/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
index 67a7521ec..cc925ae15 100644
--- a/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
@@ -1,3 +1,5 @@
+import { channelResourceFixture, messageResourceFixture, serverRailResponseFixture } from "@/test/community-resource-fixtures"
+import { serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -26,10 +28,9 @@ async function setup() {
{ id: "srv_1", name: "old", description: "d", initial: "O", active: false, unread: false, mentions: 0, ownerId: "viewer", isOwner: true },
{ id: "srv_2", name: "untouched", description: "unchanged description", initial: "U", active: false, unread: false, mentions: 4, ownerId: "viewer", isOwner: true },
]
- ingestServers(owner.registry, { servers })
- ingestServerDetail(owner.registry, { id: "srv_1", name: "old", discriminator: "", description: "d", icon: null, ownerId: "viewer", categories: [] })
+ ingestServers(owner.registry, serverRailResponseFixture({ servers }, (owner.registry)!.accountId))
+ ingestServerDetail(owner.registry, serverDirectoryFixture({ id: "srv_1", name: "old", discriminator: "", description: "d", icon: null, ownerId: "viewer", categories: [] }))
owner.client.setQueryData(communityKeys.servers(), ["srv_1", "srv_2"])
- owner.client.setQueryData(communityKeys.server("srv_1"), "srv_1")
owner.client.setQueryData(communityKeys.channelRefDirectory(), { servers: [] })
const held = deferred(), routeToken = createOwnerServerDeleteRouteToken(owner.client), onSuccess = vi.fn(), onError = vi.fn()
let remote: Array<typeof servers[number] & { icon?: string | null }> = servers
@@ -42,7 +43,7 @@ async function setup() {
})
if (path.endsWith("/categories")) return Promise.resolve({ categories: [] })
if (path.endsWith("/channels")) return Promise.resolve({ channels: [] })
- return Promise.resolve({ servers: remote.map((server) => ({ ...server, role: "owner", discriminator: "", icon: server.icon ?? null })) })
+ return Promise.resolve(serverRailResponseFixture({ servers: remote.map(server => ({ ...server, role: "owner", discriminator: "", icon: server.icon ?? null })) }, "viewer"))
})
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
const view = renderHook(({ detailActive }) => ({ leave: useLeaveServer(), remove: useDeleteServer({ routeToken, onSuccess, onError }), update: useUpdateServer(), create: useCreateServer(), icon: useUploadServerIcon(), rail: useServers(), detail: useServer(detailActive ? "srv_1" : null) }), { wrapper, initialProps: { detailActive: true } })
@@ -57,10 +58,10 @@ async function begin(view: View, operation: "leave" | "remove") {
return { request }
}
function seedPrivateScope(view: View) {
- for (const channel of [{ id: "private_parent", name: "Private parent", type: "text" as const, parentChannelId: null, parentMessageId: null }, { id: "private_child", name: "Private title", type: "thread" as const, parentChannelId: "private_parent", parentMessageId: "private_opener" }]) publishCommunityCreatedChannel(view.client, { ...channel, serverId: "srv_1", categoryId: null, creatorId: "viewer", position: 0, archived: false, muted: false, unread: false, tags: [], pending: false }, { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined })
+ for (const channel of [{ id: "private_parent", name: "Private parent", type: "text" as const, parentChannelId: null, parentMessageId: null }, { id: "private_child", name: "Private title", type: "thread" as const, parentChannelId: "private_parent", parentMessageId: "private_opener" }]) publishCommunityCreatedChannel(view.client, channelResourceFixture({ ...channel, serverId: "srv_1" }), { token: captureCommunityLiveSnapshotToken(view.client), signal: undefined })
view.runtime.ui.actions.setCurrentServerId("srv_1")
view.runtime.ui.actions.setCurrentChannelId("private_child")
- view.runtime.messageStream.actions.dispatch({ kind: "channel", id: "private_child", serverId: "srv_1" }, { type: "wsMessage", message: { id: "message_1", type: "chat", authorId: "user_1", authorName: "User", content: "Private content" } })
+ view.runtime.messageStream.actions.dispatch({ kind: "channel", id: "private_child", serverId: "srv_1" }, { type: "wsMessage", message: messageResourceFixture({ id: "message_1", channelId: "private_child", authorId: "user_1", authorName: "User", content: "Private content" }) })
}
describe("Native server membership commands", () => {
diff --git a/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx
index bad18fa87..02c3f2329 100644
--- a/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/server-rail-owner.dom.test.tsx
@@ -1,3 +1,4 @@
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React from "react"
@@ -46,7 +47,7 @@ async function mount(rail = false) {
if (options.method === "PATCH") return response
const key = `${options.authenticationAccount}:${path}`
if (seen.has(key)) return new Promise((_, fail) => options.signal?.addEventListener("abort", () => fail(new DOMException("Retired refresh", "AbortError")), { once: true }))
- seen.add(key); return Promise.resolve(path.endsWith("/server-folders") ? { folders } : { servers })
+ seen.add(key); return Promise.resolve(path.endsWith("/server-folders") ? { folders } : serverRailResponseFixture({ servers: servers.map(server => ({ ...server, isOwner: false })) }, options.authenticationAccount ?? "A"))
})
const view = render(<Root rail={rail} />)
await waitFor(() => { expect(screen.getByTestId("order").textContent).toBe("a,b,c"); expect(screen.getByTestId("groups").textContent).toBe("one:c") })
diff --git a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
index 38dbef6e4..16b74fe36 100644
--- a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { serverRailResponseFixture, channelResourceFixture, categoryResourceFixture } from "@/test/community-resource-fixtures"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
@@ -51,9 +53,9 @@ async function mount() {
const key = `${options.authenticationAccount}:${path}`
if (seen.has(key)) return new Promise((_, fail) => options.signal?.addEventListener("abort", () => fail(new DOMException("retired", "AbortError")), { once: true }))
seen.add(key)
- if (path.endsWith("/categories")) return Promise.resolve({ categories: [{ id: "cat1", name: "General", private: false }, { id: "cat2", name: "Elsewhere", private: false }] })
- if (path.endsWith("/channels")) return Promise.resolve({ channels: [{ id: "c1", name: "general", categoryId: "cat1", type: "text" }] })
- return Promise.resolve({ servers: [{ id: "s1", name: "original", description: "before", discriminator: "0001", icon: null, ownerId: "A", role: "owner" }] })
+ if (path.endsWith("/categories")) return Promise.resolve({ categories: [categoryResourceFixture({ id: "cat1", name: "General", private: false, creatorId: "A" }), categoryResourceFixture({ id: "cat2", name: "Elsewhere", private: false, creatorId: "A", position: 1 })] })
+ if (path.endsWith("/channels")) return Promise.resolve({ channels: [channelResourceFixture({ id: "c1", name: "general", categoryId: "cat1", type: "text", creatorId: "A" })] })
+ return Promise.resolve(serverRailResponseFixture({ servers: [{ id: "s1", name: "original", description: "before", discriminator: "0001", icon: null, ownerId: "A", role: "owner" }] }, options.authenticationAccount ?? "A"))
})
const view = render(<Root />)
await waitFor(() => expect(screen.getByTestId("server-detail").textContent).toBe("original|before"))
@@ -96,7 +98,7 @@ describe("actual canonical server and tree command owner", () => {
it("stores only list and detail IDs while deduplicating cold identity bootstrap", async () => {
const { original } = await mount()
expect(original.getQueryData(communityKeys.servers())).toEqual(["s1"])
- expect(original.getQueryData(communityKeys.server("s1"))).toBe("s1")
+ expect(original.getQueryData(communityKeys.server("s1"))).toMatchObject({ schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: "s1" })
expect(api.mock.calls.filter(([path]) => path === "/api/community/servers")).toHaveLength(1)
})
it("shows native optimistic fields then commits normalized success before held refreshes can return", async () => {
@@ -124,25 +126,25 @@ describe("actual canonical server and tree command owner", () => {
await act(async () => { resolve({ name: "requested-name", description: "confirmed description" }); await result })
await waitFor(() => expect(screen.getByTestId("server-detail").textContent).toBe("newer-ws|confirmed description"))
expect(original.getQueryData(communityKeys.servers())).toEqual(["s1"])
- expect(original.getQueryData(communityKeys.server("s1"))).toBe("s1")
+ expect(original.getQueryData(communityKeys.server("s1"))).toMatchObject({ schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: "s1" })
})
it("creates a native pending channel and maps its confirmed normalized identity with refresh held", async () => {
const { resolve, original } = await mount()
let result!: Promise<unknown>; act(() => { result = createChannel.mutateAsync({ serverId: "s1", categoryId: "cat1", name: "New Room", type: "text" }).catch((error) => error) })
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain("=New Room"))
- await act(async () => { resolve({ channel: { id: "real-channel", name: "new-room", position: 1 } }); await result })
+ await act(async () => { resolve({ channel: channelResourceFixture({ id: "real-channel", name: "new-room", position: 1, categoryId: "cat1", creatorId: "A" }) }); await result })
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain("real-channel=new-room"))
const registry = getCommunityDbRegistry(original)!
expect([...registry.collections.channels.keys()].some((id) => id.startsWith("tmp_ch_"))).toBe(false)
expect(registry.collections.channels.get("real-channel")).toMatchObject({ pending: false, position: 1 })
- expect(original.getQueryData(communityKeys.server("s1"))).toBe("s1")
+ expect(original.getQueryData(communityKeys.server("s1"))).toMatchObject({ schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: "s1" })
})
it("confirms category identity while preserving the newer WS row that arrived before POST success", async () => {
const { resolve, original } = await mount()
let result!: Promise<unknown>; act(() => { result = createCategory.mutateAsync({ serverId: "s1", name: "New Category", private: true }).catch((error) => error) })
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain(":New Category:"))
- act(() => projectCommunityWsEventToDb(original, { type: "community:category.create", serverId: "s1", category: { id: "real-category", name: "WS Category", position: 2, private: true } }))
- await act(async () => { resolve({ category: { id: "real-category", name: "New Category", position: 2, private: true } }); await result })
+ act(() => projectCommunityWsEventToDb(original, { type: "community:category.create", serverId: "s1", category: categoryResourceFixture({ id: "real-category", name: "WS Category", position: 2, private: true }) }))
+ await act(async () => { resolve({ category: categoryResourceFixture({ id: "real-category", name: "New Category", position: 2, private: true, creatorId: "A" }) }); await result })
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain("real-category:WS Category:"))
expect([...getCommunityDbRegistry(original)!.collections.categories.keys()].some((id) => id.startsWith("tmp_cat_"))).toBe(false)
})
@@ -164,7 +166,7 @@ describe("actual canonical server and tree command owner", () => {
})
it("confirms channel positions without losing a newer WS name", async () => {
const { resolve, original } = await mount()
- act(() => projectCommunityWsEventToDb(original, { type: "community:channel.create", serverId: "s1", channel: { id: "c2", name: "second", type: "text", categoryId: "cat1", position: 1, createdAt: "2026-10-02T00:00:00Z" } }))
+ act(() => projectCommunityWsEventToDb(original, { type: "community:channel.create", serverId: "s1", channel: { ...channelResourceFixture({ id: "c2", name: "second", categoryId: "cat1", position: 1, createdAt: "2026-10-02T00:00:00Z" }), type: "text" } }))
let result!: Promise<unknown>; act(() => { result = reorderChannels.mutateAsync({ serverId: "s1", channelIds: ["c2", "c1"] }).catch((error) => error) })
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain("c2=second,c1=general"))
act(() => projectCommunityWsEventToDb(original, { type: "community:channel.update", serverId: "s1", channelId: "c1", changes: { name: "newer-room" } }))
@@ -308,7 +310,7 @@ describe("actual canonical server and tree command owner", () => {
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain("__uncategorized__::"))
const post = api.mock.calls.find(([path, options]) => path === "/api/community/channels" && options.method === "POST")!
expect(JSON.parse(post[1].body)).toEqual({ serverId: "s1", categoryId: null, name: "Top Level", type: "text" })
- await act(async () => { resolve({ channel: { id: "real-top" } }); expect(await result).toEqual({ channel: { id: "real-top" } }) })
+ await act(async () => { resolve({ channel: channelResourceFixture({ id: "real-top", name: "Top", creatorId: "A", categoryId: null }) }); expect(await result).toEqual({ channel: channelResourceFixture({ id: "real-top", name: "Top", creatorId: "A", categoryId: null }) }) })
expect(getCommunityDbRegistry(original)!.collections.channels.get("real-top")).toMatchObject({ categoryId: null, pending: false })
})
it("does not display a pending channel under a missing named category", async () => {
@@ -316,13 +318,13 @@ describe("actual canonical server and tree command owner", () => {
let result!: Promise<unknown>; act(() => { result = createChannel.mutateAsync({ serverId: "s1", categoryId: "missing", name: "Hidden Pending", type: "text" }) })
await waitFor(() => expect(api.mock.calls.some(([, o]) => o.method === "POST")).toBe(true))
expect(screen.getByTestId("tree").textContent).not.toContain("Hidden Pending")
- await act(async () => { resolve({ channel: { id: "real-hidden" } }); await result })
+ await act(async () => { resolve({ channel: channelResourceFixture({ id: "real-hidden", name: "Hidden", creatorId: "A", categoryId: "missing" }) }); await result })
})
it.each(["channel", "category"] as const)("rolls back failed native %s creation without removing a newer WS row", async (kind) => {
const { reject, original } = await mount()
let result!: Promise<unknown>; act(() => { result = (kind === "channel" ? createChannel.mutateAsync({ serverId: "s1", categoryId: "cat1", name: "Pending", type: "text" }) : createCategory.mutateAsync({ serverId: "s1", name: "Pending" })).catch((error) => error) })
await waitFor(() => expect(screen.getByTestId("tree").textContent).toContain("Pending"))
- act(() => projectCommunityWsEventToDb(original, { type: "community:category.create", serverId: "s1", category: { id: "ws-independent", name: "Independent", position: 2, private: false } }))
+ act(() => projectCommunityWsEventToDb(original, { type: "community:category.create", serverId: "s1", category: categoryResourceFixture({ id: "ws-independent", name: "Independent", position: 2, private: false }) }))
await act(async () => { reject(new Error("denied")); expect(await result).toBeInstanceOf(Error) })
await waitFor(() => expect(screen.getByTestId("tree").textContent).not.toContain("Pending"))
expect(screen.getByTestId("tree").textContent).toContain("ws-independent:Independent:")
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 aaef4fa5f..7349e3b44 100644
--- a/src/web/src/hooks/community/mutations/servers.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/servers.dom.test.tsx
@@ -1,3 +1,4 @@
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import React, { useMemo } from "react"
import { useQueryClient, type QueryClient } from "@tanstack/react-query"
@@ -31,7 +32,7 @@ async function setup(serverId: string, callbacks: Omit<Callbacks, "routeToken">)
await act(async () => {
const registry = getCommunityDbRegistry(client)!
await registry.ready; await registry.preload()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: { servers: [{ id: serverId, name: "Server", initial: "S", active: false, unread: false, mentions: 0, isOwner: true, ownerId: "viewer" }] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [{ id: serverId, name: "Server", isOwner: true, ownerId: "viewer", role: "owner", memberId: `member-${serverId}` }] }) }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
client.setQueryData(communityKeys.servers(), [serverId])
})
return { client, routeToken: originalToken, result: { get current() { return current } }, unmount: () => mounted.rerender(<Root visible={false} />), rerender: ({ activeCallbacks }: { activeCallbacks: Callbacks }) => mounted.rerender(<Root activeCallbacks={activeCallbacks} />) }
diff --git a/src/web/src/hooks/community/observability-consumers.dom.test.tsx b/src/web/src/hooks/community/observability-consumers.dom.test.tsx
index 725e86e41..915c2a972 100644
--- a/src/web/src/hooks/community/observability-consumers.dom.test.tsx
+++ b/src/web/src/hooks/community/observability-consumers.dom.test.tsx
@@ -1,3 +1,4 @@
+import { invitesReadFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -33,7 +34,7 @@ it("projects the native machines query and retains its original cache values", a
it("preserves exact native mutation actions and original scoped requests for consumer commands", async () => {
const { client, registry } = await createCommunityQueryOwner()
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client, registry }, children)
- api.mockImplementation(async (path: string, options?: RequestInit) => path.endsWith("/invites") ? options?.method === "POST" ? { invite: { token: "invite-a", uses: 0, maxUses: null, expiresAt: null } } : { invites: [] } : path.endsWith("/avatar") ? { url: "/avatar.png", avatarVersion: 2 } : path.endsWith("/join") ? { serverId: "server-a" } : { conversation: { id: "dm-a" } })
+ api.mockImplementation(async (path: string, options?: RequestInit) => path.endsWith("/invites") ? options?.method === "POST" ? { invite: { token: "invite-a", uses: 0, maxUses: null, expiresAt: null } } : invitesReadFixture("server-a") : path.endsWith("/avatar") ? { url: "/avatar.png", avatarVersion: 2 } : path.endsWith("/join") ? { serverId: "server-a" } : { conversation: { id: "dm-a" } })
const rendered = renderHook(() => ({ dm: useCreateOrGetDm(), invite: useResolveOrCreateInvite("server-a"), mark: useMarkMessage(), unmark: useUnmarkMessage(), avatar: useUploadUserAvatar(), join: useJoinServer(), notification: useSetBotNotificationSetting() }), { wrapper })
const assert = Object.assign(vi.fn(), { signal: new AbortController().signal })
await act(async () => {
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
index 5bece0d3a..2ae92f95c 100644
--- a/src/web/src/hooks/community/read-coordinator.test.ts
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -1,3 +1,4 @@
+import { messageSeedFixture, fullResourceBundleFixture, channelResourceFixture, serverResourceFixture, messageResourceFixture, resourceBundleFixture } from "@/test/community-resource-fixtures"
import { AccountAttentionSnapshotSchema } from "@alook/shared"
import { QueryClient } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -91,7 +92,7 @@ function submitTimeline(
seq: number,
) {
const registry = getCommunityDbRegistry(leaseClients.get(lease)!)
- if (registry) ingestMessages(registry, "channel-1", [{ id: `message-${seq}`, type: "chat", authorId: "peer", seq, createdAt: new Date(seq * 1000).toISOString(), content: "Message" }])
+ if (registry) ingestMessages(registry, "channel-1", messageSeedFixture("channel-1", [{ id: `message-${seq}`, type: "chat", authorId: "peer", seq, createdAt: new Date(seq * 1000).toISOString(), content: "Message" }]))
return submitReadIntent(lease, {
kind: "timeline",
channelId: "channel-1",
@@ -252,7 +253,7 @@ describe("read coordinator", () => {
actorUserId: "user-2",
createdAt: "2026-09-27T01:00:00.000Z",
}
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [scope],
items: [item],
limit: 100,
@@ -271,7 +272,7 @@ describe("read coordinator", () => {
await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
expect(apiFetch).toHaveBeenCalledOnce()
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [scope],
items: [item],
limit: 100,
@@ -298,12 +299,12 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestMessages(registry, "channel-1", [3, 4].map((seq) => ({
+ ingestMessages(registry, "channel-1", messageSeedFixture("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,
@@ -323,7 +324,7 @@ describe("read coordinator", () => {
lastAttentionSeq: 4,
attentionCount: 2,
}
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [scope],
items,
limit: 100,
@@ -369,7 +370,7 @@ describe("read coordinator", () => {
lastAttentionSeq: null,
attentionCount: 0,
}
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [scope],
items: [],
limit: 100,
@@ -379,7 +380,7 @@ describe("read coordinator", () => {
.mockRejectedValueOnce(new ApiError("unavailable", 500))
.mockResolvedValueOnce({ changed: true, revision: 9, targetSeq: 4 })
reconcileAccountAttention.mockImplementationOnce(async () => {
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [],
items: [],
limit: 100,
@@ -412,7 +413,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -436,7 +437,7 @@ describe("read coordinator", () => {
const lease = timelineLease(queryClient)
submitTimeline(lease, 4)
await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
- ingestMessages(registry, "other", [{ id: "event", type: "chat", content: "old" }])
+ ingestMessages(registry, "other", messageSeedFixture("other", [{ id: "event", type: "chat", content: "old" }]))
projectCommunityWsEventToDb(queryClient, {
type: "community:reaction.add",
channelId: "other",
@@ -460,7 +461,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -504,7 +505,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -541,7 +542,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -617,7 +618,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -644,7 +645,7 @@ describe("read coordinator", () => {
const ticket = registerInboxProjectionTicket(queryClient, 1, target, vi.fn())
activateInboxProjectionTicket(ticket)
if (conflict) {
- ingestMessages(registry, "other", [{ id: "event", type: "chat", content: "old" }])
+ ingestMessages(registry, "other", messageSeedFixture("other", [{ id: "event", type: "chat", content: "old" }]))
projectCommunityWsEventToDb(queryClient, {
type: "community:reaction.add",
channelId: "other",
@@ -675,7 +676,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -718,7 +719,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -768,7 +769,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -816,7 +817,7 @@ describe("read coordinator", () => {
const registry = createCommunityDbRegistry(queryClient, "user-1")
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: registry.accountId! }),
scopes: [{
scopeId: "channel-1",
channelId: "channel-1",
@@ -1172,7 +1173,7 @@ describe("read coordinator", () => {
const db = getCommunityDbRegistry(queryClient)!
await db.preload()
const at = "2026-10-08T00:00:00.000Z"
- const snapshot = (seq: number) => AccountAttentionSnapshotSchema.parse({
+ const snapshot = (seq: number) => AccountAttentionSnapshotSchema.parse({ resources: { ...fullResourceBundleFixture("user-1", [serverResourceFixture({ id: "server-1" })], [channelResourceFixture({ id: "forum-1", serverId: "server-1", type: "forum", creatorId: "peer", lastMessageAt: at }), channelResourceFixture({ id: "channel-1", serverId: "server-1", type: "thread", parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: "peer", lastMessageAt: at })], [messageResourceFixture({ id: "opener-1", channelId: "forum-1", authorId: "peer", seq: 1, createdAt: at, content: "Title" }), messageResourceFixture({ id: `message-${seq}`, channelId: "channel-1", authorId: "peer", seq, createdAt: at, content: "Reply" })], [{ id: "peer", name: "Peer", discriminator: "0002", avatar: null, avatarVersion: 0 }]), memberships: [{ channelId: "forum-1", userId: "user-1", relation: "access", source: "explicit" }, { channelId: "channel-1", userId: "user-1", relation: "access", source: "explicit" }] },
scopes: [{ scopeId: "channel-1", channelId: "channel-1", serverId: "server-1", parentChannelId: "forum-1", ordinaryUnread: true, lastUnreadSeq: seq, lastAttentionSeq: seq, attentionCount: 1 }],
items: [{ id: `reply:message-${seq}`, kind: "reply", sourceId: `message-${seq}`, scopeId: "channel-1", messageId: `message-${seq}`, actorUserId: "peer", createdAt: at }],
limit: 100, truncated: false,
diff --git a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts
index e32925e33..cba71e11d 100644
--- a/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts
+++ b/src/web/src/hooks/community/thread-opener-read-handoff.dom.test.ts
@@ -1,4 +1,5 @@
import React from "react"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import type { QueryClient } from "@tanstack/react-query"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
@@ -162,7 +163,7 @@ function DirectChildHarness({
}) {
const [scrollRootEl, setScrollRootEl] = React.useState<HTMLElement | null>(null)
React.useLayoutEffect(() => {
- if (lifecycle === "ready") ingestMessages(getCommunityDbRegistry(state.queryClient!)!, "child-1", messages.map((message) => ({ ...message, type: "chat" })))
+ if (lifecycle === "ready") ingestMessages(getCommunityDbRegistry(state.queryClient!)!, "child-1", messages.map((message) => messageResourceFixture({ ...message, channelId: "child-1", content: `Child message ${message.seq}` })))
}, [lifecycle, messages])
useTimelineReadObserver({
channelId: "child-1",
diff --git a/src/web/src/hooks/community/use-account-attention.dom.test.ts b/src/web/src/hooks/community/use-account-attention.dom.test.ts
index 41203a46a..6408016a5 100644
--- a/src/web/src/hooks/community/use-account-attention.dom.test.ts
+++ b/src/web/src/hooks/community/use-account-attention.dom.test.ts
@@ -1,7 +1,9 @@
+import { singleMessageReadFixture, messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { attentionSnapshotScenarioFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER, type AccountAttentionSnapshot } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, type AccountAttentionSnapshot } from "@alook/shared"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
@@ -13,9 +15,9 @@ const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
beforeEach(() => { apiFetchMock.mockReset() })
-const message = { id: "message", channelId: "channel", type: "chat", seq: 4, authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 0, content: "background message", createdAt: "2026-10-24T00:00:00Z", replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [], resourceComplete: true }
+const message = { id: "message", channelId: "channel", type: "chat", seq: 4, authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 0, content: "background message", createdAt: "2026-10-24T00:00:00Z", replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] }
function snapshot(lastUnreadSeq = 4): AccountAttentionSnapshot {
- return {
+ return attentionSnapshotScenarioFixture({
scopes: [{ scopeId: "channel", channelId: "channel", serverId: "server", parentChannelId: null, ordinaryUnread: true, lastUnreadSeq, lastAttentionSeq: null, attentionCount: 0 }],
items: [], limit: 100, truncated: false,
included: {
@@ -23,15 +25,15 @@ function snapshot(lastUnreadSeq = 4): AccountAttentionSnapshot {
channels: [{ id: "channel", serverId: "server", name: "general", type: "text", parentChannelId: null, parentMessageId: null, creatorId: null, archived: false, lastMessageAt: message.createdAt }],
dms: [], profiles: [], messages: [],
},
- }
+ })
}
async function mountOwner(value: AccountAttentionSnapshot) {
const owner = await createCommunityQueryOwner()
apiFetchMock.mockImplementation(async (path) => {
if (path === "/api/community/users/me/attention") return value
- if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message] }
- if (path === "/api/community/messages/message") return message
+ if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message], profiles: messageProfilesFixture([message]) }
+ if (path === "/api/community/messages/message") return singleMessageReadFixture(message)
throw new Error(`Unexpected content read ${path}`)
})
function Wrapper({ children }: PropsWithChildren) {
@@ -184,9 +186,9 @@ describe("closed-Inbox account attention message hydration", () => {
it("hydrates an ID-bearing mention without any Inbox component or message window", async () => {
const owner = await mountOwner(snapshot())
const attentionCall = apiFetchMock.mock.calls.find(([path]) => path.endsWith("/attention"))!
- expect(new Headers(attentionCall[1].headers).get(COMMUNITY_CONTRACT_HEADER)).toBe("3")
+ expect(new Headers(attentionCall[1].headers).get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
scheduleAccountAttentionReconcile(owner.client, { messageId: message.id, channelId: "channel" })
- await waitFor(() => expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true))
+ await waitFor(() => expect(owner.registry.collections.messages.get(message.id)).toMatchObject(message))
expect(owner.registry.collections.messages.get(message.id)?.content).toBe(message.content)
expect(apiFetchMock.mock.calls.filter(([path]) => path.includes("/seq/"))).toHaveLength(0)
expect(apiFetchMock.mock.calls.every(([path]) => !path.endsWith("/read"))).toBe(true)
@@ -199,11 +201,11 @@ describe("closed-Inbox account attention message hydration", () => {
let release!: (value: AccountAttentionSnapshot) => void
apiFetchMock.mockImplementation(async (path) => {
if (path.endsWith("/attention")) return new Promise((resolve) => { release = resolve })
- if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message] }
+ if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message], profiles: messageProfilesFixture([message]) }
throw new Error(`Unexpected content read ${path}`)
})
scheduleAccountAttentionReconcile(owner.client, { channelId: "channel" })
- await waitFor(() => expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true))
+ await waitFor(() => expect(owner.registry.collections.messages.get(message.id)).toMatchObject(message))
await waitFor(() => expect(release).toBeTypeOf("function"))
expect(owner.hook.result.current.isFetching).toBe(true)
expect(apiFetchMock.mock.calls.filter(([path]) => path.includes("/seq/"))).toHaveLength(0)
@@ -218,8 +220,8 @@ describe("closed-Inbox account attention message hydration", () => {
const reads: Array<{ signal: AbortSignal; release: (value: AccountAttentionSnapshot) => void }> = []
apiFetchMock.mockImplementation(async (path, options) => {
if (path.endsWith("/attention")) return new Promise((resolve) => { reads.push({ signal: options.signal, release: resolve }) })
- if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message] }
- if (path === "/api/community/channels/other-channel/messages?limit=1") return { messages: [other] }
+ if (path === "/api/community/channels/channel/messages?limit=1") return { messages: [message], profiles: messageProfilesFixture([message]) }
+ if (path === "/api/community/channels/other-channel/messages?limit=1") return { messages: [other], profiles: messageProfilesFixture([other]) }
throw new Error(`Unexpected content read ${path}`)
})
scheduleAccountAttentionReconcile(owner.client, { channelId: "channel" })
@@ -230,8 +232,8 @@ describe("closed-Inbox account attention message hydration", () => {
reads[0].release(snapshot())
reads[1].release(snapshot())
await waitFor(() => {
- expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true)
- expect(owner.registry.collections.messages.get(other.id)?.resourceComplete).toBe(true)
+ expect(owner.registry.collections.messages.get(message.id)).toMatchObject(message)
+ expect(owner.registry.collections.messages.get(other.id)).toMatchObject(other)
expect(owner.hook.result.current.isFetching).toBe(false)
})
expect(apiFetchMock.mock.calls.filter(([path]) => path.includes("messages?limit=1"))).toHaveLength(2)
@@ -244,7 +246,7 @@ describe("closed-Inbox account attention message hydration", () => {
if (mode === "missing-scope") value.scopes = []
const owner = await mountOwner(value)
scheduleAccountAttentionReconcile(owner.client, { channelId: "channel" })
- await waitFor(() => expect(owner.registry.collections.messages.get(message.id)?.resourceComplete).toBe(true))
+ await waitFor(() => expect(owner.registry.collections.messages.get(message.id)).toMatchObject(message))
expect(apiFetchMock.mock.calls.every(([path]) => !path.endsWith("/read"))).toBe(true)
owner.hook.unmount()
})
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 651ee63f8..c655d7c27 100644
--- a/src/web/src/hooks/community/use-bots.dom.test.ts
+++ b/src/web/src/hooks/community/use-bots.dom.test.ts
@@ -86,6 +86,8 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
id: "bot_1",
name: "Seeded Bot",
discriminator: "0001",
+ ownerUserId: "viewer",
+ presence: "offline",
image: null,
avatarVersion: 2,
description: "",
@@ -139,7 +141,7 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
}
return {
plan: { id: "free", displayName: "Free" }, limit: 3, ownedCount: 1, activeCount: Number(active),
- bots: [{ id: "bot_1", name: "Bot", image: null, avatarVersion: 0, isActive: active, presence: active ? "online" : "offline" }],
+ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001", ownerUserId: "viewer", description: "", image: null, avatarVersion: 0, isActive: active, presence: active ? "online" : "offline" }],
}
})
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
@@ -162,7 +164,7 @@ describe("bot mutations wire the bot id into invalidateBotSurfaces", () => {
act(() => createCommunityDbRegistry(queryClient, "viewer").runtime.ws.actions.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" }],
+ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001", ownerUserId: "viewer", description: "", image: null, avatarVersion: 0, isActive: true, presence: "online" }],
}))
await waitFor(() => expect(queryClient.getQueryData(communityKeys.bots())).toBeDefined())
expect(createCommunityDbRegistry(queryClient, "viewer").runtime.ws.get().presenceByUserId.get("bot_1")).toBe("offline")
@@ -473,7 +475,7 @@ describe("bot mutation origin retirement", () => {
unregisterA()
unregisterB = registerCommunityDbRegistry(registryB)
- writeCommunityProfilePatches([{ id: "bot", identityAbout: { name: "B latest" } }], registryB)
+ writeCommunityProfilePatches([{ id: "bot", identityAbout: { name: "B latest", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } }], registryB)
await act(async () => resolve(kind === "avatar"
? { url: "old-photo", avatarVersion: 5 }
: { bot: { id: "bot", name: "Old", image: null, avatarVersion: 4 } }))
@@ -499,6 +501,7 @@ describe("bot mutation origin retirement", () => {
const { useUpdateBot } = await import("./use-bots")
const qc = new QueryClient()
const registry = createCommunityDbRegistry(qc, "viewer")
+ writeCommunityProfilePatches([{ id: "bot", identityAbout: { name: "Before", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } }], registry)
const unregister = registerCommunityDbRegistry(registry)
let resolve!: (value: unknown) => void
apiFetchMock.mockReturnValue(new Promise((done) => { resolve = done }))
@@ -523,3 +526,23 @@ describe("bot mutation origin retirement", () => {
}
})
})
+
+it.each(["wrong-owner", "duplicate-id", "missing-catalog-discriminator"])("rejects a later malformed bot directory %s before canonical publication", async defect => {
+ const { createCommunityQueryOwner } = await import("@/test/community-query-owner")
+ const { communityRegistrySnapshot } = await import("@/test/community-registry-snapshot")
+ const { botsOptions } = await import("@/lib/community/bots")
+ const { client, registry } = await createCommunityQueryOwner()
+ const row = (id: string) => ({ id, name: id, discriminator: "0042", ownerUserId: "viewer", image: null, avatarVersion: 1, description: "Real about", presence: "offline", machineId: "machine", runtime: "codex", modelName: null, reasoningEffort: null, runtimeConfigRevision: 0 })
+ const initial = { isFounder: false, plan: { id: "free", displayName: "Free" }, limit: 3, ownedCount: 2, activeCount: 0, bots: [row("first"), row("second")] }
+ apiFetchMock.mockResolvedValueOnce(initial)
+ await client.query(botsOptions())
+ const before = communityRegistrySnapshot(registry)
+ const malformed = structuredClone(initial)
+ malformed.bots[0]!.name = "Must not publish"
+ if (defect === "wrong-owner") malformed.bots[1]!.ownerUserId = "foreign"
+ if (defect === "duplicate-id") malformed.bots[1]!.id = "first"
+ if (defect === "missing-catalog-discriminator") delete (malformed.bots[1] as Partial<ReturnType<typeof row>>).discriminator
+ apiFetchMock.mockResolvedValueOnce(malformed)
+ await expect(client.query({ ...botsOptions(), staleTime: 0 })).rejects.toThrow()
+ expect(communityRegistrySnapshot(registry)).toEqual(before)
+})
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 a24f68c0c..eb64a8bc4 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
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, CommunityMembersReadSchema, type CommunityMemberRelation, type CommunityResourceProfile } from "@alook/shared"
import { createElement, type PropsWithChildren } from "react"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
@@ -6,6 +7,10 @@ import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"
import { channelMembershipKey, profileSchema, serverMembershipKey } from "@/lib/community-db/schema"
+const profile = (id: string, name: string, discriminator = "0042", avatarVersion = 0): CommunityResourceProfile => ({ id, name, discriminator, avatar: name[0], avatarVersion })
+const relationRow = (channelId: string, userId: string, relation: CommunityMemberRelation["relation"] = "access", source: CommunityMemberRelation["source"] = "explicit", role: string | null = "member", memberId: string | null = `membership_${userId}`, isCreator = false): CommunityMemberRelation => ({ channelId, userId, relation, source, role, memberId, isCreator })
+const roster = (channelId: string, relation: CommunityMemberRelation["relation"], members: CommunityMemberRelation[], profiles: CommunityResourceProfile[]) => CommunityMembersReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId, relation, members, profiles })
+
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -21,14 +26,14 @@ describe("useChannelMembers", () => {
const { useChannelMembers } = await import("./use-channel-members")
const { publishCommunityChannelMembersSnapshot, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
const owner = await createCommunityQueryOwner()
- const peer = { id: "m-peer", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, sub: "", role: "member", status: "offline", source: "explicit", isCreator: false }
- publishCommunityChannelMembersSnapshot(owner.client, "server", "private", "access", [{ channelId: "private", userId: "peer", relation: "access", memberId: "m-peer", role: "member", source: "explicit", isCreator: false }], { token: captureCommunityLiveSnapshotToken(owner.client) }, [{ id: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 }])
+ const peer = relationRow("private", "peer", "access", "explicit", "member", "m-peer")
+ publishCommunityChannelMembersSnapshot(owner.client, "server", "private", "access", [peer], { token: captureCommunityLiveSnapshotToken(owner.client) }, [profile("peer", "Peer")])
apiFetchMock.mockRejectedValue(new Error("controlled first read failure"))
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)
const rendered = renderHook(() => useChannelMembers("private", true, "server", "access"), { wrapper })
await waitFor(() => expect(rendered.result.current).toMatchObject({ isError: true, failed: true, members: [expect.objectContaining({ userId: "peer", discriminator: "0042" })] }))
expect(rendered.result.current.data).toBeUndefined()
- apiFetchMock.mockResolvedValue({ members: [peer] })
+ apiFetchMock.mockResolvedValue(roster("private", "access", [peer], [profile("peer", "Peer")]))
await act(async () => { await rendered.result.current.refetch() })
await waitFor(() => expect(rendered.result.current).toMatchObject({ isSuccess: true, loading: false, failed: false, members: [expect.objectContaining({ userId: "peer" })] }))
expect(apiFetchMock).toHaveBeenCalledTimes(2)
@@ -36,11 +41,11 @@ describe("useChannelMembers", () => {
it("separates missing usable profiles from true empty and withdraws disabled access candidates", async () => {
const { useChannelMembers } = await import("./use-channel-members")
const owner = await createCommunityQueryOwner()
- apiFetchMock.mockResolvedValue({ members: [{ id: "m-peer", userId: "peer", name: "Peer", discriminator: "", avatar: "P", avatarVersion: 0, sub: "", role: "member", status: "offline", source: "explicit", isCreator: false }] })
+ apiFetchMock.mockResolvedValue(roster("private", "access", [relationRow("private", "peer", "access", "explicit", "member", "m-peer")], []))
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)
const rendered = renderHook(({ enabled }) => useChannelMembers("private", enabled, "server", "access"), { wrapper, initialProps: { enabled: true } })
await waitFor(() => expect(rendered.result.current).toMatchObject({ isSuccess: true, loading: false, failed: true }))
- await act(async () => owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, id: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 })))
+ await act(async () => owner.registry.collections.profiles.utils.writeUpsert(profileSchema.parse(profile("peer", "Peer"))))
await waitFor(() => expect(rendered.result.current).toMatchObject({ loading: false, failed: false, members: [expect.objectContaining({ userId: "peer", discriminator: "0042" })] }))
expect(rendered.result.current.profiles.get("peer")?.discriminator).toBe("0042")
await act(async () => owner.registry.collections.serverMemberships.utils.writeDelete(serverMembershipKey("server", "peer")))
@@ -51,23 +56,7 @@ describe("useChannelMembers", () => {
expect(apiFetchMock).toHaveBeenCalledOnce()
})
it("fetches the roster through the identity-aware query function", async () => {
- apiFetchMock.mockResolvedValue({
- members: [{
- id: "membership_1",
- userId: "member_1",
- name: "Alice",
- discriminator: "0042",
- avatar: "A",
- avatarVersion: 4,
- sub: "",
- role: "member",
- status: "offline",
- statusEmoji: null,
- statusText: "",
- source: "explicit",
- isCreator: false,
- }],
- })
+ apiFetchMock.mockResolvedValue(roster("private/channel", "access", [relationRow("private/channel", "member_1", "access", "explicit", "member", "membership_1")], [profile("member_1", "Alice", "0042", 4)]))
const { useChannelMembers } = await import("./use-channel-members")
const queryClient = (await createCommunityQueryOwner()).client
const wrapper = ({ children }: PropsWithChildren) => createElement(
@@ -91,7 +80,7 @@ describe("useChannelMembers", () => {
const { publishCommunityChannelMetadata, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
const owner = await createCommunityQueryOwner()
publishCommunityChannelMetadata(owner.client, { metadata: { categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z", id: "dm", serverId: null, name: null, type: "dm", parentChannelId: null, parentMessageId: null, creatorId: null, archived: false, lastMessageAt: null }, proof: { token: captureCommunityLiveSnapshotToken(owner.client) } })
- apiFetchMock.mockResolvedValue({ members: ["viewer", "peer"].map((userId) => ({ id: userId, userId, name: userId, discriminator: "0001", avatar: "", avatarVersion: 0, sub: "", role: null, status: "offline", statusEmoji: null, statusText: "", source: "explicit", isCreator: false })) })
+ apiFetchMock.mockResolvedValue(roster("dm", "access", ["viewer", "peer"].map(userId => relationRow("dm", userId, "access", "explicit", null, null)), [profile("viewer", "viewer", "0001"), profile("peer", "peer", "0001")]))
const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, children)
const rendered = renderHook(() => useChannelMembers("dm", true, undefined, "access"), { wrapper })
await waitFor(() => expect(rendered.result.current.members).toHaveLength(2))
@@ -109,17 +98,13 @@ describe("useChannelMembers", () => {
const wrapper = ({ children }: PropsWithChildren) => createElement(
QueryClientProvider, { client: owner.client }, children,
)
- const member = (userId: string, name: string) => ({
- id: `membership_${userId}`, userId, name, discriminator: "0042", avatar: name,
- avatarVersion: 0, sub: "", role: "member", status: "offline", statusEmoji: null,
- statusText: "", isCreator: userId === "viewer",
- })
+ const profiles = [profile("viewer", "Viewer"), profile("bob", "Bob"), profile("carol", "Carol")]
const parentMembers = [
- { ...member("viewer", "Viewer"), role: "owner", source: "admin" },
- { ...member("bob", "Bob"), source: "explicit" },
- { ...member("carol", "Carol"), source: "inherited" },
+ relationRow("parent", "viewer", "access", "admin", "owner", "membership_viewer", true),
+ relationRow("parent", "bob", "access", "explicit"),
+ relationRow("parent", "carol", "access", "inherited"),
]
- const participants = parentMembers.slice(0, 2).map((row) => ({ ...row, source }))
+ const participants = parentMembers.slice(0, 2).map(row => ({ ...row, channelId: "thread", relation: "notify" as const, source }))
let failParticipants = true
let participantGets = 0
let parentGets = 0
@@ -128,11 +113,11 @@ describe("useChannelMembers", () => {
participantGets += 1
return failParticipants
? Promise.reject(new Error("controlled first-load failure"))
- : Promise.resolve({ members: participants })
+ : Promise.resolve(roster("thread", "notify", participants, profiles.slice(0, 2)))
}
if (url.endsWith("/parent/members?relation=access")) {
parentGets += 1
- return Promise.resolve({ members: parentMembers })
+ return Promise.resolve(roster("parent", "access", parentMembers, profiles))
}
throw new Error(`Unexpected roster request: ${url}`)
})
diff --git a/src/web/src/hooks/community/use-channel-members.ts b/src/web/src/hooks/community/use-channel-members.ts
index 294841709..159f10634 100644
--- a/src/web/src/hooks/community/use-channel-members.ts
+++ b/src/web/src/hooks/community/use-channel-members.ts
@@ -6,7 +6,7 @@ import { useCallback,useMemo } from "react"
import { QueryObserver,useMutation,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 { communityReadSchemas, CommunityResourceProfileSchema, type CommunityMembersRead, type CommunityRole, type CommunityChannelResource, type CommunityMemberRelation, type CommunityResourceProfile } from "@alook/shared"
+import { type CommunityMembersRead, type CommunityRole, type CommunityChannelResource, type CommunityMemberRelation, type CommunityResourceProfile } from "@alook/shared"
import type { CommunityProfile, CommunityUserCore, Presence } from "@/lib/community/models/people"
import { fetchAllServerMembers } from "./fetch-all-server-members"
@@ -26,15 +26,9 @@ export type ChannelMember = CommunityUserCore & Pick<CommunityMemberRelation, "u
source: NonNullable<ChannelMembershipRow["source"]>
}
-function normalizeChannelRoster(channelId: string, relation: CommunityMemberRelation["relation"], response: { members: ChannelMember[] } | CommunityMembersRead): Omit<CommunityMembersRead, "contractVersion"> & { contractVersion: 2 | 3 } {
- if ("contractVersion" in response) return response
- return communityReadSchemas(2).members.parse({ contractVersion: 2, channelId, relation,
- members: response.members.map((member) => ({ channelId, userId: member.userId, relation, memberId: member.id, source: member.source, isCreator: member.isCreator, role: member.role })),
- profiles: response.members.map((member) => CommunityResourceProfileSchema.strip().parse({ ...member, id: member.userId, discriminator: member.discriminator || null, statusEmoji: member.statusEmoji ?? null, statusText: member.statusText ?? "" })),
- })
-}
export type AddableMember = Pick<ChannelMember, "userId" | "avatar" | "avatarVersion"> & { [Field in "name" | "discriminator"]: ChannelMember[Field] | null }
type ChannelRosterWindow = {
+ creatorIds: string[]
serverId: CommunityChannelResource["serverId"]
relation: CommunityMemberRelation["relation"]
members: Array<Pick<CommunityMemberRelation, "userId"> & { id: NonNullable<CommunityMemberRelation["memberId"]> }>
@@ -59,12 +53,12 @@ function channelMembersOptions(client: QueryClient, channelId: string, serverId?
const scopeId = serverId ?? channel?.serverId ?? (channel?.type === "dm" ? null : undefined)
if (scopeId === undefined) throw new DOMException("Missing channel roster scope", "AbortError")
const dimension = relation ?? "access"
- const response = await apiFetch<{ members: ChannelMember[] } | CommunityMembersRead>("/api/community/channels/" + encodeURIComponent(channelId) + "/members?relation=" + dimension, communityRequestOptions(client, token, signal, assert))
+ const response = await apiFetch<CommunityMembersRead>("/api/community/channels/" + encodeURIComponent(channelId) + "/members?relation=" + dimension, communityRequestOptions(client, token, signal, assert))
assert()
- const resources = normalizeChannelRoster(channelId, dimension, response)
- publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, resources.members, { token, signal }, resources.profiles, { legacyPresentation: resources.contractVersion !== 3 })
+ const resources = response
+ publishCommunityChannelMembersSnapshot(client, scopeId, channelId, dimension, resources.members, { token, signal }, resources.profiles)
assert()
- return { serverId: scopeId, relation: dimension, members: resources.members.map(({ memberId, userId }) => ({ id: memberId ?? userId, userId })) }
+ return { serverId: scopeId, relation: dimension, creatorIds: resources.members.filter(member => member.isCreator).map(member => member.userId), members: resources.members.map(({ memberId, userId }) => ({ id: memberId ?? userId, userId })) }
},
}
}
@@ -110,10 +104,10 @@ export function useChannelMembers(channelId: string, enabled = true, serverId?:
const member = byUser.get(participant.userId)
if (query.data?.serverId !== null && !member?.memberId) return []
const profile = readCommunityProfile(profiles.get(participant.userId), participant.userId)
- return [{ id: member?.memberId ?? participant.userId, userId: participant.userId, name: member?.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member ? member.role as CommunityRole : null, sub: "", status: member?.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source ?? "explicit", isCreator: participant.isCreator ?? false }]
+ return [{ id: member?.memberId ?? participant.userId, userId: participant.userId, name: member?.nickname ?? profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, role: member ? member.role as CommunityRole : null, sub: "", status: member?.viewer ? "online" : profile.presence, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "", source: participant.source, isCreator: query.data?.creatorIds.includes(participant.userId) === true }]
})
- }, [profiles, membershipProjection.data, roster, query.data?.serverId])
- const readState = getMemberReadState(active, { pending: !query.data || query.isRefetching, failed: query.isError && !query.isFetching }, query.data?.serverId === null ? [rosterProjection, profileProjection] : [rosterProjection, membershipProjection, profileProjection], members.filter((member) => member.userId !== rosterProjection.registry?.accountId).map((member) => member.userId), profiles)
+ }, [profiles, membershipProjection.data, roster, query.data?.serverId, query.data?.creatorIds])
+ const readState = getMemberReadState(active, { pending: !query.data || query.isRefetching, failed: query.isError && !query.isFetching }, query.data?.serverId === null ? [rosterProjection, profileProjection] : [rosterProjection, membershipProjection, profileProjection], (roster ?? []).filter((member) => member.userId !== rosterProjection.registry?.accountId).map((member) => member.userId), profileProjection.resourceProfiles)
const data = useMemo(() => active && query.data ? { members } : undefined, [active, query.data, members])
return { ...query, data, members, profiles, ...readState } as UseQueryResult<{ members: ChannelMember[] }> & { members: ChannelMember[]; profiles: typeof profiles; loading: boolean; failed: boolean }
}
diff --git a/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx b/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx
index 9de83da36..438abb4b9 100644
--- a/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx
+++ b/src/web/src/hooks/community/use-channel-metadata.child-create.dom.test.tsx
@@ -2,7 +2,7 @@ import React from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClientProvider } from "@tanstack/react-query"
import type { ApiRequestOptions } from "@/lib/api/client"
-import type { CommunityWsEvent } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, type CommunityWsEvent } from "@alook/shared"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { conversationEntryFixture, conversationEntryFromChannel, seedConversationEntry } from "@/test/conversation-entry-fixtures"
@@ -22,7 +22,7 @@ function deferred<T>() {
return { promise, resolve }
}
-describe("empty thread full identity across legacy child-create ordering", () => {
+describe("empty thread full identity across current child-create ordering", () => {
it.each(["before", "pending", "after", "pending-absent", "full-pending", "revoke", "retire"] as const)("handles child-create order %s without stale publication", async timing => {
const owner = await createCommunityQueryOwner()
const parent = conversationEntryFixture()
@@ -31,15 +31,16 @@ describe("empty thread full identity across legacy child-create ordering", () =>
entry.channel.messageCount = 0
entry.parent = parent.channel
entry.opener = parent.messages[0]
- if (timing !== "pending-absent") publishCommunityCreatedChannel(owner.client, { id: "t1", type: "thread", serverId: "s1", parentChannelId: "c1", parentMessageId: "m1", creatorId: "viewer", createdAt: entry.channel.createdAt, name: "Created thread", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
- const event = () => projectCommunityWsEventToDb(owner.client, { type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "m1", channel: timing === "full-pending" ? { ...entry.channel, name: "Event thread", topic: "Event topic", messageCount: 7 } : { id: "t1", type: "thread", name: "Event thread", creatorId: "viewer", createdAt: entry.channel.createdAt } } as CommunityWsEvent, timing === "full-pending" ? 3 : 2)
+ entry.profiles = parent.profiles
+ if (timing !== "pending-absent") publishCommunityCreatedChannel(owner.client, { ...entry.channel, name: "Created thread", creatorId: "viewer", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
+ const event = () => projectCommunityWsEventToDb(owner.client, { type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "m1", channel: timing === "full-pending" ? { ...entry.channel, name: "Event thread", topic: "Event topic", messageCount: 7 } : { ...entry.channel, name: "Event thread", creatorId: "viewer" } } as CommunityWsEvent, BUSINESS_SCHEMA_VERSION)
if (timing === "before") event()
const pending = deferred<typeof entry>()
load.mockReturnValue(pending.promise)
const wrapper = ({ children }: React.PropsWithChildren) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>
const hook = renderHook(() => useChannelMetadata("s1", "t1"), { wrapper })
await waitFor(() => expect(load).toHaveBeenCalledOnce())
- expect(hook.result.current.canRead).toBe(false)
+ expect(hook.result.current.canRead).toBe(timing !== "pending-absent")
if (["pending", "pending-absent", "full-pending", "revoke", "retire"].includes(timing)) await act(async () => { event() })
if (timing === "revoke") await act(async () => { owner.runtime.ws.actions.revokeChannelAccess("s1", "t1") })
if (timing === "retire") await act(async () => { retireCommunityAccount(owner.registry) })
@@ -49,8 +50,6 @@ describe("empty thread full identity across legacy child-create ordering", () =>
expect(hook.result.current.canRead).toBe(false)
expect(hook.result.current.identityKnown).toBe(false)
expect(hook.result.current.data).toBeUndefined()
- expect(owner.registry.collections.channels.get("t1")?.resourceComplete).not.toBe(true)
- console.log(JSON.stringify({ timing, paths: load.mock.calls.map(([path]) => path) }))
expect(load).toHaveBeenCalledOnce()
hook.unmount()
return
@@ -61,9 +60,8 @@ describe("empty thread full identity across legacy child-create ordering", () =>
const identity = state.data
const meta = identity?.type === "thread" && identity.parentChannelId && identity.parentMessageId ? { ...identity, serverId: "s1", parentChannelId: identity.parentChannelId, parentMessageId: identity.parentMessageId, activityAt: identity.lastMessageAt ?? identity.createdAt } : null
const model = buildChannelRouteModel({ id: "s1", categories: [] } as never, meta, "t1", { channelId: "t1", settled: state.canRead }, identity, owner.registry.collections.channels.get("c1"))
- console.log(JSON.stringify({ timing, canRead: state.canRead, identityKnown: state.identityKnown, resourceComplete: state.canonical?.resourceComplete, canonicalName: state.canonical?.name, routeHydrated: model.routeHydrated, requestCount: load.mock.calls.length }))
expect(state.identityKnown).toBe(true)
- expect(identity).toMatchObject({ id: "t1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", resourceComplete: true, name: timing === "before" ? "Entry thread" : "Event thread" })
+ expect(identity).toMatchObject({ id: "t1", type: "thread", parentChannelId: "c1", parentMessageId: "m1", name: timing === "before" ? "Entry thread" : "Event thread" })
expect(identity).toMatchObject({ topic: timing === "full-pending" ? "Event topic" : "", messageCount: timing === "full-pending" ? 7 : 0 })
expect(model.routeHydrated).toBe(true)
expect(load).toHaveBeenCalledOnce()
@@ -72,7 +70,7 @@ describe("empty thread full identity across legacy child-create ordering", () =>
it.each([
[true, false], [false, false], [true, true], [false, true],
- ] as const)("retains sparse creator semantics with known=%s explicit=%s", async (known, explicit) => {
+ ] as const)("rejects incomplete child resources with known=%s explicit=%s", async (known, explicit) => {
const owner = await createCommunityQueryOwner()
const parent = conversationEntryFixture()
await seedConversationEntry(owner.client, parent)
@@ -80,22 +78,21 @@ describe("empty thread full identity across legacy child-create ordering", () =>
entry.channel.messageCount = 0
entry.parent = parent.channel
entry.opener = parent.messages[0]
- if (known) publishCommunityCreatedChannel(owner.client, { id: "t1", type: "thread", serverId: "s1", parentChannelId: "c1", parentMessageId: "m1", creatorId: "existing-creator", createdAt: entry.channel.createdAt, name: "Created thread", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
+ entry.profiles = parent.profiles
+ if (known) publishCommunityCreatedChannel(owner.client, { ...entry.channel, name: "Created thread", creatorId: "existing-creator", messageCount: 0 }, { token: captureCommunityLiveSnapshotToken(owner.client, "t1") })
const pending = deferred<typeof entry>()
load.mockReturnValue(pending.promise)
const wrapper = ({ children }: React.PropsWithChildren) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>
const hook = renderHook(() => useChannelMetadata("s1", "t1"), { wrapper })
await waitFor(() => expect(load).toHaveBeenCalledOnce())
- await act(async () => { projectCommunityWsEventToDb(owner.client, { type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "m1", channel: { id: "t1", type: "thread", name: "Event thread", createdAt: entry.channel.createdAt, ...(explicit ? { creatorId: "event-creator" } : {}) } } as CommunityWsEvent, 2) })
+ await act(async () => { expect(() => projectCommunityWsEventToDb(owner.client, { type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "m1", channel: { id: "t1", type: "thread", name: "Event thread", createdAt: entry.channel.createdAt, ...(explicit ? { creatorId: "event-creator" } : {}) } } as CommunityWsEvent, BUSINESS_SCHEMA_VERSION)).toThrow() })
const during = owner.registry.collections.channels.get("t1")
const duringCreator = during?.creatorId
- expect(during?.resourceComplete).toBe(false)
- expect(hook.result.current.canRead).toBe(false)
+ expect(hook.result.current.canRead).toBe(known)
await act(async () => { pending.resolve(entry) })
await waitFor(() => expect(hook.result.current.identityKnown).toBe(true))
- console.log(JSON.stringify({ known, explicit, duringCreator, finalCreator: hook.result.current.data?.creatorId }))
- expect(duringCreator).toBe(explicit ? "event-creator" : known ? "existing-creator" : null)
- expect(hook.result.current.data).toMatchObject({ creatorId: explicit ? "event-creator" : "entry-creator", name: "Event thread", resourceComplete: true })
+ expect(duringCreator).toBe(known ? "existing-creator" : undefined)
+ expect(hook.result.current.data).toMatchObject({ creatorId: "entry-creator", name: "Entry thread" })
expect(hook.result.current.canRead).toBe(true)
expect(load).toHaveBeenCalledOnce()
hook.unmount()
diff --git a/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx b/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx
index a81f31f91..77c6150fa 100644
--- a/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx
+++ b/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx
@@ -1,3 +1,4 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClientProvider } from "@tanstack/react-query"
@@ -6,7 +7,8 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { dmConversationEntryFixture as fixture, conversationEntryFixture } from "@/test/conversation-entry-fixtures"
import { CommunityDbProvider, useDmProjection } from "@/lib/community-db/projections"
import { conversationEntryOptions } from "@/lib/community/conversation-entry"
-import { applyCommunityDmBlockAccess, captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
+import { applyCommunityDmBlockAccess, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
import { ConversationReadTimeoutError } from "@/lib/community/conversation-read"
import { COMMUNITY_CONVERSATION_ANCHOR_MISSING } from "@alook/shared"
@@ -56,12 +58,14 @@ describe("qualified canonical channel identity", () => {
it("does not qualify a persisted or structural peer list as current reading permission", async () => {
const { client, wrapper } = await setup()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [{ id: "c1", userId: "peer", name: "Old peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "old" }] } },
- proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ const registry = getCommunityDbRegistry(client)!
+ registry.collections.channels.utils.writeUpsert({ ...channelResourceFixture({ id: "c1", type: "dm", serverId: null, name: null }), muted: false, tags: [], pending: false })
+ registry.collections.profiles.utils.writeUpsert({ id: "peer", name: "Old peer", discriminator: "0042", avatarVersion: 0, avatar: null })
const request = deferred<ReturnType<typeof fixture>>()
load.mockReturnValue(request.promise)
const hook = renderHook(() => useChannelMetadata(null, "c1"), { wrapper })
expect(hook.result.current.canRead).toBe(false)
+ expect(hook.result.current.windowReady).toBe(false)
expect(hook.result.current.identityKnown).toBe(false)
expect(hook.result.current.data).toBeUndefined()
await act(async () => request.resolve(fixture()))
@@ -74,6 +78,7 @@ describe("qualified canonical channel identity", () => {
await qualify()
const hook = renderHook(() => useChannelMetadata(null, "c1"), { wrapper })
expect(hook.result.current.status).toBe("readable")
+ expect(hook.result.current.windowReady).toBe(true)
expect(hook.result.current.data?.name).toBe("")
expect(load).not.toHaveBeenCalled()
hook.unmount()
@@ -86,6 +91,7 @@ describe("qualified canonical channel identity", () => {
const hook = renderHook(() => useChannelMetadata(null, "c1"), { wrapper })
await act(async () => { await hook.result.current.retry() })
expect(hook.result.current.status).toBe("readable")
+ expect(hook.result.current.windowReady).toBe(true)
expect(hook.result.current.canRead).toBe(true)
expect(hook.result.current.denied).toBe(false)
expect(load).toHaveBeenCalledOnce()
@@ -100,6 +106,7 @@ describe("qualified canonical channel identity", () => {
await act(async () => { await hook.result.current.retry() })
await waitFor(() => expect(hook.result.current.denied).toBe(true))
expect(hook.result.current.canRead).toBe(false)
+ expect(hook.result.current.windowReady).toBe(false)
expect(registry.collections.messages.get("m1")).toBeUndefined()
expect(hook.result.current.data).toBeUndefined()
expect(load).toHaveBeenCalledOnce()
@@ -143,6 +150,7 @@ describe("qualified canonical channel identity", () => {
await act(async () => { retireCommunityAccount(registry); request.resolve(fixture()) })
expect(registry.collections.channels.get("c1")).toBeUndefined()
expect(hook.result.current.canRead).toBe(false)
+ expect(hook.result.current.windowReady).toBe(false)
hook.unmount()
})
})
diff --git a/src/web/src/hooks/community/use-channel-metadata.ts b/src/web/src/hooks/community/use-channel-metadata.ts
index 54ff375a4..7b392a48d 100644
--- a/src/web/src/hooks/community/use-channel-metadata.ts
+++ b/src/web/src/hooks/community/use-channel-metadata.ts
@@ -1,6 +1,8 @@
"use client"
import { useMemo } from "react"
+import { useSelector } from "@tanstack/react-store"
+import { useCommunityRuntime } from "@/stores/community/runtime"
import { useQueryClient } from "@tanstack/react-query"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { forumTagFromUrl } from "@/lib/community/forum-tag-selection"
@@ -17,21 +19,26 @@ export function useChannelMetadata(serverId: string | null, channelId: string |
const selectedTag = forumSelection ? forumTagFromUrl(intent?.tag) ?? storedTag : intent?.tag ?? "All"
const tag = selectedTag === "All" ? null : selectedTag
const entry = useConversationResource(channelId ? { channelId, serverId, ...intent, tag } : null, null, false, "metadata", selectedTag !== null)
- const { query, canonical, scope, canRead, revoked, denied } = entry
- const identityKnown = canRead && !!scope && !!canonical && canonical.id === channelId && canonical.serverId === serverId && !canonical.pending && canonical.resourceComplete === true
+ const { query, canonical, scope, canRead, windowReady, revoked, denied } = entry
+ const runtime = useCommunityRuntime()
+ const denialCode = useSelector(runtime.ws, state => {
+ const current = channelId ? state.channelAccessScopes.get(channelId) : undefined
+ return revoked && current?.revoked && current.serverId === serverId ? current.denialCode : undefined
+ })
+ const identityKnown = canRead && !!scope && !!canonical && canonical.id === channelId && canonical.serverId === serverId && !canonical.pending
const error = entry.verificationError
- const status: ChannelReadingStatus = !channelId ? "no-target" : denied ? "denied" : canRead ? "readable"
+ const status: ChannelReadingStatus = !channelId ? "no-target" : denied ? "denied" : windowReady ? "readable"
: error || entry.verificationFailed ? "retryable-error" : query.isFetching || entry.verificationPending ? "pending" : "unresolved"
const data = useMemo(() => {
- if (!identityKnown || !canonical || canonical.resourceComplete !== true || !scope) return undefined
+ if (!identityKnown || !canonical || !scope) return undefined
return { ...canonical, serverId,
createdAt: canonical.createdAt ?? "", name: canonical.name ?? "",
verifiedEpoch: scope.proof.accessEpoch, identityProof: scope.proof, readProof: scope.proof,
parentChannelId: canonical.parentChannelId ?? null, parentMessageId: canonical.parentMessageId ?? null,
creatorId: canonical.creatorId ?? null, lastMessageAt: canonical.lastMessageAt ?? null,
} }, [canonical, identityKnown, scope, serverId])
- return { ...query, error, data, status, identityKnown, canRead, isVerified: canRead,
- isArchived: canonical?.resourceComplete === true && !!canonical.archived, denied, revoked, canonical,
+ return { ...query, error, data, status, identityKnown, canRead, windowReady, displayWindow: entry.displayWindow, isVerified: canRead,
+ isArchived: !!canonical?.archived, denied, revoked, denialCode, canonical,
retry: entry.retryVerification, retrying: entry.verificationFetching,
}
}
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
index a9e76161f..fb0581594 100644
--- a/src/web/src/hooks/community/use-channel-panels.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-panels.dom.test.ts
@@ -1,3 +1,4 @@
+import { messageResourceFixture, resourceBundleFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { describe, expect, it, vi } from "vitest"
@@ -16,11 +17,11 @@ vi.mock("@/lib/api/client", () => ({ apiFetch: api, toastApiError: vi.fn() }))
describe("usePins", () => {
it("includes the same-channel pending pin in the bounded native message selection", async () => {
const owner = await createCommunityQueryOwner("viewer")
- ingestMessages(owner.registry, "c1", [{ id: "pending", seq: 1, type: "chat", content: "Pinned body" }])
- ingestMessages(owner.registry, "foreign", [{ id: "foreign", seq: 1, type: "chat", content: "Foreign body" }])
+ ingestMessages(owner.registry, "c1", [messageResourceFixture({ id: "pending", channelId: "c1", content: "Pinned body" })])
+ ingestMessages(owner.registry, "foreign", [messageResourceFixture({ id: "foreign", channelId: "foreign", content: "Foreign body" })])
let resolve!: () => void
api.mockReset().mockImplementation((_path: string, options: { method?: string }) => options.method === "POST"
- ? new Promise<void>((done) => { resolve = done }) : Promise.resolve({ pins: [] }))
+ ? new Promise<void>((done) => { resolve = done }) : Promise.resolve({ pins: [], resources: resourceBundleFixture() }))
const subscription = vi.spyOn(projections, "useCanonicalMessagesById")
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider,
{ client: owner.client, registry: owner.registry, userId: "viewer", retainOwner: true }, children)
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 5b7b44640..d85ae22cc 100644
--- a/src/web/src/hooks/community/use-channel-panels.test.ts
+++ b/src/web/src/hooks/community/use-channel-panels.test.ts
@@ -1,3 +1,4 @@
+import { forumFeedScenarioFixture, fullResourceBundleFixture, serverResourceFixture, channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { type QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
@@ -19,117 +20,117 @@ beforeEach(async () => {
})
const project = (data: ThreadsResponse) => materializeThreadsResponse(data, new Map(getCanonicalCommunityMessages(qc).map((row) => [row.id, row])), new Map(getCanonicalCommunityChannels(qc).map((row) => [row.id, row])))
+function page(channelId = "ch_1", parentType: "text" | "forum" = "forum", threadId = "t_1", openerId = "m1", name = "thread", content = "root", preview?: string) {
+ return forumFeedScenarioFixture(channelId, { serverId: "s1", parentType, threads: [{ id: threadId, name, creatorId: "u1", parentMessageId: openerId, messageCount: 1, lastMessageAt: null, createdAt: "now" }],
+ included: { parentMessages: [{ id: openerId, channelId, content, seq: 1, authorId: "u1", authorName: "Alice", authorAvatar: null }],
+ firstMessages: preview === undefined ? [] : [{ channelId: threadId, content: preview }],
+ participants: [{ channelId: threadId, userId: "u1", userName: "Alice", userImage: null, userAvatarVersion: 0 }],
+ }, hasMore: false,
+ })
+}
+function pins(message = messageResourceFixture({ id: "m_1", channelId: "ch_1", authorId: "u1", content: "pin", createdAt: "now" })) {
+ return { pins: [{ id: message.id }], resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "ch_1" })], [message]) }
+}
+
describe("useThreads / threadsQueryFn", () => {
- it("carries batch participant numbers into canonical profiles without a DM read or erasing them on a legacy read", async () => {
+ it("publishes complete participant numbers without a DM read", async () => {
const { threadsQueryFn } = await import("./use-channel-panels")
- for (const discriminator of ["123456", undefined]) {
- apiFetchMock.mockReset()
- apiFetchMock
- .mockResolvedValueOnce({ serverId: "s1", parentType: "forum", threads: [{ id: "t_1", name: "thread", 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: "Alice", authorImage: null }], firstMessages: [] })
- .mockResolvedValueOnce({ tags: [] })
- .mockResolvedValueOnce({ participants: [{ channelId: "t_1", userId: "u1", userName: "Alice", userImage: null, userAvatarVersion: 0, ...(discriminator === undefined ? {} : { discriminator }) }] })
+ for (const discriminator of ["123456", "654321"]) {
+ const current = page()
+ current.included.profiles = current.included.profiles.map(profile => ({ ...profile, discriminator }))
+ apiFetchMock.mockReset(); apiFetchMock.mockResolvedValueOnce(current)
await threadsQueryFn("ch_1", qc)()
- expect(getCommunityDbRegistry(qc)!.collections.profiles.get("u1")).toMatchObject({ name: "Alice", discriminator: "123456" })
- expect(apiFetchMock).toHaveBeenCalledTimes(4)
+ expect(getCommunityDbRegistry(qc)!.collections.profiles.get("u1")).toMatchObject({ name: "Alice", discriminator })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
expect(apiFetchMock.mock.calls.some(([url]) => String(url).includes("/dm"))).toBe(false)
}
})
- 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: [{ channelId: "t_1", content: "identityless preview" }],
- })
- .mockResolvedValueOnce({ tags: [] })
- .mockResolvedValueOnce({ participants: [] })
+ it("rejects an incomplete raw current profile before publishing any thread", async () => {
+ const raw = page()
+ const { discriminator: _discriminator, ...partial } = raw.included.profiles[0]
+ raw.included.profiles[0] = partial as never
+ apiFetchMock.mockResolvedValueOnce(raw)
+ const { threadsQueryFn } = await import("./use-channel-panels")
+ await expect(threadsQueryFn("ch_1", qc)()).rejects.toThrow()
+ expect(getCommunityDbRegistry(qc)!.collections.channels.has("t_1")).toBe(false)
+ expect(getCommunityDbRegistry(qc)!.collections.profiles.has("u1")).toBe(false)
+ })
+
+ it("fetches one full threads page and returns its owned ID window", async () => {
+ apiFetchMock.mockResolvedValueOnce(page("ch_1", "forum", "t_1", "m1", "t", "root", "Full first message preview"))
const { threadsQueryFn } = await import("./use-channel-panels")
const data = await threadsQueryFn("ch_1", qc)()
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/threads?include=parentMessage,firstMessage,tags,participants&archived=false", expect.objectContaining({ authenticationAccount: "viewer", signal: undefined }))
expect(apiFetchMock).not.toHaveBeenCalledWith("/api/community/channels/ch_1/posts")
expect(data.threads).toHaveLength(1)
- expect(project(data)[0]?.parent.text).toBe("identityless preview")
+ expect(project(data)[0]?.parent.text).toBe("Full first message preview")
})
it("populates queryClient at communityKeys.threads(channelId)", async () => {
- 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: [] })
+ apiFetchMock.mockResolvedValueOnce(page("ch_1", "text", "t_1", "m_1"))
const { threadsQueryFn } = await import("./use-channel-panels")
const key = communityKeys.threads("ch_1")
await qc.query({ 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 () => {
+ it("uses full opener content only for forum parents with the original AbortSignal", async () => {
const signal = new AbortController().signal
- apiFetchMock
- .mockResolvedValueOnce({ serverId: "s1", parentType: "forum", threads: [{ id: "post_1", name: "derived", type: "thread", creatorId: "u1", parentMessageId: "opener_1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
- .mockResolvedValueOnce({ messages: [{ id: "opener_1", channelId: "forum_1", content: " Full opener content ", seq: 4, authorId: "u1", authorName: "A", authorImage: null }], firstMessages: [] })
- .mockResolvedValueOnce({ tags: [] })
- .mockResolvedValueOnce({ participants: [] })
+ apiFetchMock.mockResolvedValueOnce(page("forum_1", "forum", "post_1", "opener_1", "derived", " Full opener content "))
const { threadsQueryFn } = await import("./use-channel-panels")
const forum = await threadsQueryFn("forum_1", qc)({ signal })
- expect(project(forum)[0]).toMatchObject({
- name: " Full opener content ",
- openerMessageId: "opener_1",
- })
- expect(apiFetchMock.mock.calls).toHaveLength(4)
- for (const call of apiFetchMock.mock.calls) expect(call[1]).toEqual(expect.objectContaining({ signal }))
-
- apiFetchMock.mockReset()
- apiFetchMock
- .mockResolvedValueOnce({ serverId: "s1", parentType: "text", threads: [{ id: "thread_1", name: "Custom thread name", type: "thread", creatorId: "u1", parentMessageId: "root_1", messageCount: 1, lastMessageAt: null, createdAt: "now" }] })
- .mockResolvedValueOnce({ messages: [{ id: "root_1", channelId: "text_1", content: "Root message", seq: 1, authorId: "u1", authorName: "A", authorImage: null }], firstMessages: [] })
- .mockResolvedValueOnce({ tags: [] })
- .mockResolvedValueOnce({ participants: [] })
+ expect(project(forum)[0]).toMatchObject({ name: " Full opener content ", openerMessageId: "opener_1" })
+ expect(apiFetchMock.mock.calls).toHaveLength(1)
+ expect(apiFetchMock.mock.calls[0][1]).toEqual(expect.objectContaining({ signal }))
+ apiFetchMock.mockReset(); apiFetchMock.mockResolvedValueOnce(page("text_1", "text", "thread_1", "root_1", "Custom thread name", "Root message"))
const text = await threadsQueryFn("text_1", qc)()
expect(project(text)[0]?.name).toBe("Custom thread name")
})
- it("aborts all four loader requests when the exact base query is cancelled", async () => {
+ it("aborts the full resource loader when its exact base query is cancelled", async () => {
const signals: AbortSignal[] = []
- apiFetchMock.mockImplementation((url: string, init: RequestInit = {}) => {
- const requestSignal = init.signal as AbortSignal
- signals.push(requestSignal)
- if (new URL(url, "http://localhost").pathname.endsWith("/threads")) return Promise.resolve({ serverId: "s1", parentType: "forum", threads: [] })
- return new Promise((_resolve, reject) => {
- requestSignal.addEventListener("abort", () => reject(new Error("aborted")))
- })
+ apiFetchMock.mockImplementation((_url: string, init: RequestInit = {}) => {
+ const signal = init.signal as AbortSignal; signals.push(signal)
+ return new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError"))))
})
const { threadsQueryFn } = await import("./use-channel-panels")
const key = communityKeys.threads("forum_1")
const pending = qc.query({ queryKey: key, queryFn: threadsQueryFn("forum_1", qc) }).catch(() => undefined)
- await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(4))
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
await qc.cancelQueries({ queryKey: key, exact: true })
- expect(new Set(signals).size).toBe(1)
- expect(signals[0]?.aborted).toBe(true)
+ expect(new Set(signals).size).toBe(1); expect(signals[0].aborted).toBe(true)
await pending
})
})
describe("usePins / pinsQueryFn", () => {
- it("keeps known message fields absent from a pin summary", async () => {
- const rich = { id: "m_1", type: "system" as const, systemKind: "thread" as const,
+ it("publishes rich pin facts only from the supplied full resource", async () => {
+ const rich = messageResourceFixture({ id: "m_1", channelId: "ch_1", replyToId: "reply", type: "system" as const, systemKind: "thread" as const,
authorId: "u1", content: "full", clientNonce: "known-nonce",
- replyTo: { id: "reply", authorName: "Peer", text: "Prior" },
- attachments: [{ name: "known.txt", url: "/known", sizeBytes: 1024 }],
+ replyTo: { id: "reply", authorId: "peer", authorName: "Peer", text: "Prior" },
+ attachments: [{ id: "file", name: "known.txt", url: "/known", thumbnailUrl: null, contentType: "text/plain", sizeBytes: 1024, width: null, height: null }],
embeds: [{ title: "Known" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
- }
+ })
ingestMessages(getCommunityDbRegistry(qc)!, "ch_1", [rich])
- apiFetchMock.mockResolvedValueOnce({ pins: [{ id: rich.id, authorId: rich.authorId,
- authorName: "Peer", content: "summary", seq: 1, createdAt: "now" }] })
+ apiFetchMock.mockResolvedValueOnce(pins({ ...rich, content: "summary" }))
const { pinsQueryFn } = await import("./use-channel-panels")
await pinsQueryFn("ch_1", qc)()
expect(getCommunityDbRegistry(qc)!.collections.messages.get(rich.id)).toMatchObject({
...rich, content: "summary", replyToId: "reply",
})
})
+ it("rejects an incomplete raw pin resource without inventing a canonical body", async () => {
+ const raw = pins()
+ raw.resources.messages[0] = { id: "m_1", channelId: "ch_1", content: "partial" } as never
+ apiFetchMock.mockResolvedValueOnce(raw)
+ const { pinsQueryFn } = await import("./use-channel-panels")
+ await expect(pinsQueryFn("ch_1", qc)()).rejects.toThrow()
+ expect(getCommunityDbRegistry(qc)!.collections.messages.has("m_1")).toBe(false)
+ })
+
it("fetches from /channels/:id/pins and returns { pins }", async () => {
- apiFetchMock.mockResolvedValueOnce({ pins: [{ id: "m_1", type: "chat", channelId: "ch_1", authorId: "u1", content: "pin" }] })
+ apiFetchMock.mockResolvedValueOnce(pins())
const { pinsQueryFn } = await import("./use-channel-panels")
const data = await pinsQueryFn("ch_1", qc)()
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/pins", expect.objectContaining({ authenticationAccount: "viewer" }))
@@ -137,7 +138,7 @@ describe("usePins / pinsQueryFn", () => {
})
it("populates queryClient at communityKeys.pins(channelId)", async () => {
- apiFetchMock.mockResolvedValueOnce({ pins: [{ id: "m_1", type: "chat", authorId: "u1", authorName: "A", content: "pin", createdAt: "now" }] })
+ apiFetchMock.mockResolvedValueOnce(pins())
const { pinsQueryFn } = await import("./use-channel-panels")
const key = communityKeys.pins("ch_1")
await qc.query({ queryKey: key, queryFn: pinsQueryFn("ch_1", qc) })
@@ -148,7 +149,7 @@ describe("usePins / pinsQueryFn", () => {
describe("materializeThreadsResponse", () => {
it("retains full forum previews, text-panel limits, created-time fallback and optional opener fields", () => {
const preview = "preview".repeat(30), content = "content".repeat(30)
- const base = { type: "thread", position: 0, archived: false, muted: false, unread: false, pending: false, tags: [] }
+ const base = { ...channelResourceFixture({ id: "base", serverId: "s1", type: "thread", parentChannelId: "forum" }), muted: false, pending: false, tags: [] }
const channels = new Map([
["post", channelSchema.parse({ ...base, id: "post", name: "Fallback", createdAt: "created", preview, parentMessageId: "opener" })],
["empty", channelSchema.parse({ ...base, id: "empty", name: "", preview, createdAt: "created" })],
@@ -179,7 +180,7 @@ describe("materializeThreadsResponse", () => {
}
const canonical = new Map([["opener", { id: "opener", type: "chat" as const, authorId: "u1", authorName: "A", content: "Canonical title", createdAt: "now" }]])
- const channels = new Map(base.threads.map((thread) => [thread.id, channelSchema.parse({ id: thread.id, name: thread.id === "identityless" ? "Post" : thread.name, type: "thread", position: 0, archived: false, muted: false, unread: false, pending: false, tags: [], serverId: "s1", parentChannelId: "forum_1", parentMessageId: thread.openerMessageId, preview: thread.parent.text, messageCount: thread.messageCount, lastMessageAt: thread.lastMessageAt })]))
+ const channels = new Map(base.threads.map((thread) => [thread.id, channelSchema.parse({ ...channelResourceFixture({ id: thread.id, serverId: "s1", type: "thread", parentChannelId: "forum_1" }), id: thread.id, name: thread.id === "identityless" ? "Post" : thread.name, type: "thread", position: 0, archived: false, muted: false, pending: false, tags: [], serverId: "s1", parentChannelId: "forum_1", parentMessageId: thread.openerMessageId ?? null, preview: thread.parent.text, messageCount: thread.messageCount, lastMessageAt: thread.lastMessageAt })]))
expect(materializeThreadsResponse(base, canonical, channels).map(({ name }) => name))
.toEqual(["Canonical title", "Post"])
expect(materializeThreadsResponse({ ...base, parentType: "text" }, canonical, channels)[0]?.parent.text)
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index 777336313..000ecb8a0 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -17,13 +17,13 @@ import {
} from "@/lib/community-db/projections"
import {
captureCommunityLiveSnapshotToken,
- publishCommunityEmbeddedMessages,
+ publishCommunityResourceBundle,
publishCommunityForumFeed,
assertCommunityLiveSnapshotTokenCurrent,
} from "@/lib/community-db/sync"
import type { CommunityFreshQueryProof } from "@/lib/community-db/sync"
-import { normalizeThreadResources, projectThread, type ForumFeedTransportPage } from "./forum-feed-window"
-import { CommunityMessagePreviewSchema, type CommunityLegacyThreadsRead, type CommunityThreadsRead, type CommunityChannelResource, type CommunityMessageResource } from "@alook/shared"
+import { normalizeThreadResources, projectThread } from "./forum-feed-window"
+import { type CommunityThreadsRead, type CommunityChannelResource, type CommunityMessageResource } from "@alook/shared"
import type { ChannelRow } from "@/lib/community-db/schema"
/**
@@ -44,17 +44,9 @@ export type ThreadsResponse = {
async function loadThreadResources(queryClient: QueryClient, channelId: string, proof: CommunityFreshQueryProof) {
const options = qualifiedCommunityRequestOptions(queryClient, proof.token, proof.signal)
- const response = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/api/community/channels/${channelId}/threads?include=parentMessage,firstMessage,tags,participants&archived=false`, options)
+ const response = await apiFetch<CommunityThreadsRead>(`/api/community/channels/${channelId}/threads?include=parentMessage,firstMessage,tags,participants&archived=false`, options)
assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
- if ("contractVersion" in response || response.included) return normalizeThreadResources(channelId, response)
- const openerIds = response.threads.flatMap((thread) => thread.parentMessageId ? [thread.parentMessageId] : [])
- const threadIds = response.threads.map((thread) => thread.id)
- const [messages, tags, participants] = await Promise.all([
- apiFetch<Pick<ForumFeedTransportPage["included"], "parentMessages" | "firstMessages"> & { messages: ForumFeedTransportPage["included"]["parentMessages"] }>("/api/community/messages/batch", { method: "POST", body: JSON.stringify({ channelId, ids: openerIds, firstInChannelIds: threadIds }), ...options }),
- apiFetch<Pick<ForumFeedTransportPage["included"], "tags">>("/api/community/messages/tags/batch", { method: "POST", body: JSON.stringify({ channelId, messageIds: openerIds }), ...options }),
- apiFetch<Pick<ForumFeedTransportPage["included"], "participants">>("/api/community/channels/participants/batch", { method: "POST", body: JSON.stringify({ parentChannelId: channelId, channelIds: threadIds }), ...options }),
- ])
- return normalizeThreadResources(channelId, { ...response, hasMore: false, included: { parentMessages: messages.messages, firstMessages: messages.firstMessages, tags: tags.tags, participants: participants.participants } })
+ return normalizeThreadResources(channelId, response)
}
export const threadsQueryFn = (channelId: string, queryClient: QueryClient) => async ({ signal }: { signal?: AbortSignal } = {}) => {
@@ -114,7 +106,7 @@ export function useForumTags(channelId: string | null, enabled: boolean) {
* Fetches the pinned-message list for a channel. Server-side hydrates the
* author + content so no follow-up fetch is needed.
*/
-export type PinsResponse = { pins: Array<Pick<Msg, "id" | "seq" | "authorId" | "authorName" | "authorAvatar" | "authorAvatarVersion" | "content" | "createdAt">> }
+export type PinsResponse = { pins: Array<Pick<CommunityMessageResource, "id">>; resources: import("@alook/shared").CommunityResourceBundle }
export type PinsWindowResponse = { pins: Array<Pick<CommunityMessageResource, "id">> }
export const pinsQueryFn = (channelId: string, queryClient: QueryClient) =>
@@ -124,12 +116,7 @@ export const pinsQueryFn = (channelId: string, queryClient: QueryClient) =>
`/api/community/channels/${channelId}/pins`,
signal ? { signal } : undefined, publicationToken,
)
- {
- publishCommunityEmbeddedMessages(queryClient, {
- entries: data.pins.map((message) => ({ channelId, message: { ...CommunityMessagePreviewSchema.partial({ type: true }).parse({ ...message, channelId }), resourceComplete: false } })),
- proof: { token: publicationToken, signal },
- })
- }
+ publishCommunityResourceBundle(queryClient, data.resources, { token: publicationToken, signal }, data.pins.map(row => ({ id: row.id, channelId })))
return { pins: data.pins.map((message) => ({ id: message.id })) }
}
diff --git a/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts
index f0217b847..d5cd3a0b2 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
@@ -1,3 +1,4 @@
+import { fullResourceBundleFixture, serverResourceFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
import { useLayoutEffect } from "react"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient } from "@tanstack/react-query"
@@ -5,27 +6,33 @@ import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { communityKeys } from "@/lib/query-keys"
-import { serverSchema, channelSchema } from "@/lib/community-db/schema"
+import { channelSchema } from "@/lib/community-db/schema"
import { channelRefDirectoryQueryFn, useChannelRefDirectory } from "./use-channel-ref-directory"
const api = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: api }))
const directory = [{ id: "srv", name: "Studio", discriminator: "0001", channels: [{ id: "ch", name: "general", type: "text" as const }] }]
+function directoryResponse(rows = directory) {
+ return { directory: rows, resources: fullResourceBundleFixture("viewer",
+ rows.map(server => serverResourceFixture({ id: server.id, name: server.name, discriminator: server.discriminator })),
+ rows.flatMap(server => server.channels.map(channel => channelResourceFixture({ ...channel, serverId: server.id }))),
+ ) }
+}
const clients: QueryClient[] = []
function client() { const qc = new QueryClient({ defaultOptions: { queries: { retry: 2 } } }); clients.push(qc); return qc }
function wrapper(qc: QueryClient) { return function Owner({ children }: PropsWithChildren) { return createElement(CommunityTestProvider, { client: qc }, children) } }
function mount(qc = client(), enabled = true) { return renderHook(({ active }: { active: boolean }) => useChannelRefDirectory(active), { initialProps: { active: enabled }, wrapper: wrapper(qc) }) }
-function deferred() { let resolve!: (value: { directory: typeof directory }) => void; const promise = new Promise<{ directory: typeof directory }>((done) => { resolve = done }); return { promise, resolve } }
+function deferred() { let resolve!: (value: ReturnType<typeof directoryResponse>) => void; const promise = new Promise<ReturnType<typeof directoryResponse>>((done) => { resolve = done }); return { promise, resolve } }
function seed(qc: QueryClient, channels = true) {
- qc.setQueryData(communityKeys.communityDbCollection("viewer", "servers"), [serverSchema.parse({ id: "srv", name: "Studio", discriminator: "0001", description: "", ownerId: "viewer", icon: null, official: false, isOwner: true, unread: false, mentions: 0 })])
- qc.setQueryData(communityKeys.communityDbCollection("viewer", "channels"), channels ? [channelSchema.parse({ id: "ch", serverId: "srv", name: "general", type: "text", position: 0, archived: false, muted: false, unread: false, tags: [], pending: false })] : [])
+ qc.setQueryData(communityKeys.communityDbCollection("viewer", "servers"), [serverResourceFixture({ id: "srv", name: "Studio", discriminator: "0001", ownerId: "viewer" })])
+ qc.setQueryData(communityKeys.communityDbCollection("viewer", "channels"), channels ? [channelSchema.parse({ ...channelResourceFixture({ id: "ch", serverId: "srv", name: "general" }), muted: false, tags: [], pending: false })] : [])
}
beforeEach(() => { api.mockReset() })
beforeEach(() => () => { act(() => { clients.splice(0).forEach((qc) => qc.clear()) }) })
describe("native canonical channel directory", () => {
it("uses the qualified lightweight API helper", async () => {
- api.mockResolvedValue({ directory }); const options = { authenticationAccount: "viewer" }
- await expect(channelRefDirectoryQueryFn(options)).resolves.toEqual(directory)
+ api.mockResolvedValue(directoryResponse()); const options = { authenticationAccount: "viewer" }
+ await expect(channelRefDirectoryQueryFn(options)).resolves.toEqual(directoryResponse())
expect(api).toHaveBeenCalledWith("/api/community/users/me/channel-directory", options)
})
it("stays dormant until enabled then publishes DB rows and transport IDs", async () => {
@@ -33,15 +40,15 @@ describe("native canonical channel directory", () => {
expect(api).not.toHaveBeenCalled(); expect(view.result.current).toMatchObject({ directory: [], isResolved: false, isLoading: false })
view.rerender({ active: true }); await waitFor(() => expect(api).toHaveBeenCalledOnce())
expect(view.result.current.isLoading).toBe(true)
- await act(async () => held.resolve({ directory })); await waitFor(() => expect(view.result.current.directory).toEqual(directory))
+ await act(async () => held.resolve(directoryResponse())); await waitFor(() => expect(view.result.current.directory).toEqual(directory))
expect(qc.getQueryData(communityKeys.channelRefDirectory())).toEqual(["srv"])
})
it("treats a successful empty response as resolved", async () => {
- api.mockResolvedValue({ directory: [] }); const view = mount()
+ api.mockResolvedValue(directoryResponse([])); const view = mount()
await waitFor(() => expect(view.result.current).toMatchObject({ directory: [], isResolved: true, isLoading: false, isError: false }))
})
it("does not retry ordinary failure and refetches once on demand", async () => {
- api.mockRejectedValueOnce(new Error("unavailable")).mockResolvedValueOnce({ directory }); const view = mount()
+ api.mockRejectedValueOnce(new Error("unavailable")).mockResolvedValueOnce(directoryResponse()); const view = mount()
await waitFor(() => expect(view.result.current.isError).toBe(true)); expect(api).toHaveBeenCalledOnce()
await act(async () => { await view.result.current.refetch() }); await waitFor(() => expect(view.result.current.directory).toEqual(directory)); expect(api).toHaveBeenCalledTimes(2)
})
@@ -58,7 +65,7 @@ describe("native canonical channel directory", () => {
const signal = api.mock.calls[0][1].signal as AbortSignal
view.rerender(tree(false)); expect(signal.aborted).toBe(false)
expect(qc.getQueryCache().find({ queryKey: communityKeys.channelRefDirectory() })!.getObserversCount()).toBe(1)
- await act(async () => held.resolve({ directory })); await waitFor(() => expect(qc.getQueryData(communityKeys.channelRefDirectory())).toEqual(["srv"]))
+ await act(async () => held.resolve(directoryResponse())); await waitFor(() => expect(qc.getQueryData(communityKeys.channelRefDirectory())).toEqual(["srv"]))
expect(qc.getQueryCache().find({ queryKey: communityKeys.channelRefDirectory() })!.getObserversCount()).toBe(0)
view.rerender(tree(true)); await waitFor(() => expect(result.directory).toEqual(directory)); expect(api).toHaveBeenCalledOnce()
})
@@ -88,6 +95,6 @@ describe("native canonical channel directory", () => {
const held = deferred(); api.mockReturnValue(held.promise); const qc = client(), view = mount(qc)
await waitFor(() => expect(api).toHaveBeenCalledOnce()); const signal = api.mock.calls[0][1].signal as AbortSignal
view.unmount(); qc.clear(); expect(signal.aborted).toBe(true)
- await act(async () => held.resolve({ directory })); expect(qc.getQueryData(communityKeys.channelRefDirectory())).toBeUndefined()
+ await act(async () => held.resolve(directoryResponse())); expect(qc.getQueryData(communityKeys.channelRefDirectory())).toBeUndefined()
})
})
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 a2f97c9cb..4beb55d7f 100644
--- a/src/web/src/hooks/community/use-channel-ref-directory.ts
+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts
@@ -1,4 +1,5 @@
"use client"
+import type { CommunityResourceBundle } from "@alook/shared"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import {
@@ -19,11 +20,11 @@ import {
const EMPTY_DIRECTORY = Object.freeze([]) as unknown as ChannelRefDirectory
-export const channelRefDirectoryQueryFn = async (options: ApiRequestOptions): Promise<ChannelRefDirectory> => {
- const data = await apiFetch<{ directory: ChannelRefDirectory }>(
+export const channelRefDirectoryQueryFn = async (options: ApiRequestOptions): Promise<{ directory: ChannelRefDirectory; resources: CommunityResourceBundle }> => {
+ const data = await apiFetch<{ directory: ChannelRefDirectory; resources: CommunityResourceBundle }>(
"/api/community/users/me/channel-directory", options,
)
- return data.directory
+ return data
}
export function useChannelRefDirectory(enabled = true): {
@@ -47,9 +48,9 @@ export function useChannelRefDirectory(enabled = true): {
})
signal.addEventListener("abort", release, { once: true })
const token = captureCommunityLiveSnapshotToken(queryClient)
- const directory = await channelRefDirectoryQueryFn(communityRequestOptions(queryClient, token, signal))
+ const { directory, resources } = await channelRefDirectoryQueryFn(communityRequestOptions(queryClient, token, signal))
publishCommunityChannelDirectory(queryClient, {
- directory,
+ directory, resources,
proof: { token, signal },
})
return directory.map((server) => server.id)
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 e1e8f04b4..6c463e0a0 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
@@ -1,3 +1,5 @@
+import { channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
+import { writeCommunityCollectionRows } from "@/lib/community-db/write"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
@@ -64,11 +66,11 @@ function deferred() {
return { promise, resolve, reject }
}
function payload(id = "post-1") {
- return conversationEntryFromChannel({
+ return { ...conversationEntryFromChannel({
categoryId: null, topic: "", position: 0, messageCount: 0, id, serverId: "server-1", name: "post", type: "thread", parentChannelId: "parent-1",
parentMessageId: "opener-1", creatorId: "viewer-1", archived: false,
lastMessageAt: "2026-08-09T00:00:00.000Z", createdAt: "2026-08-08T00:00:00.000Z",
- }, "viewer-1")
+ }, "viewer-1"), parent: channelResourceFixture({ id: "parent-1", serverId: "server-1", type: "text" }) }
}
beforeEach(async () => {
@@ -300,10 +302,13 @@ describe("unresolved metadata terminal error and retry", () => {
expect(mocks.replace).not.toHaveBeenCalled()
})
- it("keeps a legacy tag-derived archive bit pending without purging or revoking access", async () => {
+ it("rejects obsolete cache fields and keeps a valid local archive tag pending without purging or revoking access", async () => {
const owner = getCommunityDbRegistry(client)!
- owner.collections.channels.utils.writeUpsert([{ ...payload().channel, type: "thread", archived: true, tags: ["archived"], position: 0, muted: false, unread: false, pending: false }])
- owner.collections.messages.utils.writeUpsert([{ id: "reply-1", channelId: "post-1", type: "chat", content: "kept" }])
+ const legacy = { ...payload().channel, archived: true, tags: ["archived"], muted: false, unread: false, pending: false }
+ await expect(async () => writeCommunityCollectionRows(owner, "channels", [legacy], row => row.id)).rejects.toThrow()
+ expect(owner.collections.channels.size).toBe(0)
+ await writeCommunityCollectionRows(owner, "channels", [{ ...payload().channel, tags: ["archived"], muted: false, pending: false }], row => row.id)
+ await writeCommunityCollectionRows(owner, "messages", [messageResourceFixture({ id: "reply-1", channelId: "post-1", content: "kept" })], row => row.id)
const held = deferred()
mocks.apiFetch.mockReturnValue(held.promise)
await mount()
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 5df8bb199..b4526cd32 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
@@ -4,9 +4,11 @@ import { getCommunityRuntime } from "@/stores/community/runtime"
import React from "react"
import { type QueryClient } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { act, render as renderDom } from "@/test/react-dom-harness"
+import { act, waitFor, render as renderDom } from "@/test/react-dom-harness"
const mocks = vi.hoisted(() => ({
+ useRealMetadata: false,
+ load: vi.fn(),
subscribe: vi.fn(),
unsubscribe: vi.fn(),
replace: vi.fn(),
@@ -17,7 +19,7 @@ const mocks = vi.hoisted(() => ({
metaQuery: {
data: undefined as undefined | Record<string, unknown>,
error: null as unknown,
- canRead: false, isArchived: false,
+ canRead: false, windowReady: false, isArchived: false,
isError: false,
},
dbChannel: undefined as undefined | Record<string, unknown>,
@@ -37,14 +39,15 @@ vi.mock("next/navigation", () => ({
vi.mock("./use-servers", () => ({
useServer: () => ({ server: mocks.server }),
}))
-vi.mock("./use-channel-metadata", () => ({
- useChannelMetadata: () => ({ ...mocks.metaQuery, canonical: mocks.dbChannel, denied: mocks.metaQuery.isArchived, status: mocks.metaQuery.isError ? "retryable-error" : mocks.metaQuery.canRead ? "readable" : "pending", retrying: false, retry: async () => {} }),
-}))
+vi.mock("./use-channel-metadata", async original => {
+ const actual = await original<typeof import("./use-channel-metadata")>()
+ return { ...actual, useChannelMetadata: (...args: Parameters<typeof actual.useChannelMetadata>) => mocks.useRealMetadata ? actual.useChannelMetadata(...args) : ({ ...mocks.metaQuery, canonical: mocks.dbChannel, denied: mocks.metaQuery.isArchived, status: mocks.metaQuery.isError ? "retryable-error" : mocks.metaQuery.canRead ? "readable" : "pending", retrying: false, retry: async () => {} }) }
+})
vi.mock("./use-community-ws", () => ({
communityWsSubscribe: (...args: unknown[]) => mocks.subscribe(...args),
communityWsUnsubscribe: (...args: unknown[]) => mocks.unsubscribe(...args),
}))
-vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))
+vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn(), apiFetch: (...args: unknown[]) => mocks.load(...args) }))
vi.mock("@/lib/community/last-channel", () => ({
getLastChannel: () => mocks.lastChannel,
clearLastChannel: (...args: unknown[]) => mocks.clearLastChannel(...args),
@@ -69,6 +72,7 @@ function Harness({ channelId = "post-1" }: { channelId?: string }) {
const result = useChannelRouteModel("server-1", "server-1", channelId, "viewer")
return React.createElement("span", {
"data-lifecycle": result.routeLifecycle,
+ "data-window-ready": String(result.windowReady),
"data-skeleton-subtype": result.skeletonSubtype,
"data-layout-hint": JSON.stringify(result.layoutHint),
"data-parent-channel": result.currentChannelMeta?.parentChannelId ?? "",
@@ -82,6 +86,8 @@ function lifecycle(renderer: ReturnType<typeof render>) {
}
beforeEach(async () => {
+ mocks.useRealMetadata = false
+ mocks.load.mockReset()
window.history.replaceState(null, "", "/c/channels/server-1/post-1")
const owner = await createCommunityQueryOwner()
queryClient = owner.client
@@ -101,13 +107,32 @@ beforeEach(async () => {
channels: [{ id: "forum-1", name: "Forum", type: "forum" }],
}],
}
- mocks.metaQuery = { data: undefined, error: null, canRead: false, isArchived: false, isError: false }
+ mocks.metaQuery = { data: undefined, error: null, canRead: false, windowReady: false, isArchived: false, isError: false }
mocks.dbChannel = undefined
mocks.dbParent = undefined
})
describe("useChannelRouteModel subscription ownership", () => {
+ it("mounts a permitted metadata surface while its window is pending and preserves window error exits", () => {
+ mocks.dbChannel = { id: "post-1", serverId: "server-1", type: "text", name: "Target", archived: false }
+ mocks.metaQuery = { data: mocks.dbChannel, error: null, canRead: true, windowReady: false, isArchived: false, isError: false }
+ const renderer = render(React.createElement(Harness))
+ expect(lifecycle(renderer)).toBe("ready")
+ expect(renderer.container.querySelector("span")).toHaveAttribute("data-window-ready", "false")
+ expect(renderer.container.querySelector("span")).toHaveAttribute("data-skeleton-subtype", "text")
+ mocks.metaQuery.windowReady = true
+ renderer.rerender(React.createElement(Harness))
+ expect(lifecycle(renderer)).toBe("ready")
+ expect(renderer.container.querySelector("span")).toHaveAttribute("data-window-ready", "true")
+ mocks.metaQuery.windowReady = false
+ mocks.metaQuery.error = new Error("entry window unavailable")
+ mocks.metaQuery.isError = true
+ renderer.rerender(React.createElement(Harness))
+ expect(lifecycle(renderer)).toBe("terminal-error")
+ renderer.unmount()
+ })
+
it("releases primary focus in the background and restores it on foreground return", () => {
const node = (active: boolean) => React.createElement(ConversationActivityContext, { value: active }, React.createElement(Harness))
const renderer = render(node(true))
@@ -167,6 +192,7 @@ describe("useChannelRouteModel subscription ownership", () => {
expect(lifecycle(renderer!)).toBe("pending")
mocks.metaQuery.canRead = true
+ mocks.metaQuery.windowReady = true
act(() => renderer!.rerender(React.createElement(Harness, { channelId: "forum-1" })))
expect(lifecycle(renderer!)).toBe("ready")
act(() => renderer!.unmount())
@@ -182,6 +208,7 @@ describe("useChannelRouteModel subscription ownership", () => {
}
mocks.metaQuery.canRead = true
+ mocks.metaQuery.windowReady = true
const renderer = render(React.createElement(Harness, { channelId: "text-1" }))
const node = renderer.container.querySelector("span")
@@ -275,7 +302,7 @@ describe("useChannelRouteModel subscription ownership", () => {
expect(renderer.container.querySelector("span")).toHaveAttribute("data-lifecycle", "pending")
expect(renderer.container.querySelector("span")).toHaveAttribute("data-parent-channel", "")
mocks.metaQuery = { data: { ...mocks.dbChannel, creatorId: null, lastMessageAt: null, createdAt: "", archived: false },
- error: null, canRead: true, isArchived: false, isError: false }
+ error: null, canRead: true, windowReady: true, isArchived: false, isError: false }
act(() => renderer.rerender(React.createElement(Harness)))
expect(renderer.container.querySelector("span")).toHaveAttribute("data-lifecycle", "ready")
expect(renderer.container.querySelector("span")).toHaveAttribute("data-creator-id", "")
@@ -328,7 +355,7 @@ describe("useChannelRouteModel subscription ownership", () => {
verifiedEpoch: 0,
},
error: null,
- canRead: true, isArchived: false,
+ canRead: true, windowReady: true, isArchived: false,
isError: false,
}
act(() => {
@@ -357,7 +384,7 @@ describe("useChannelRouteModel subscription ownership", () => {
activityAt: "2026-08-09T00:00:00.000Z",
verifiedEpoch: 0,
}
- mocks.metaQuery = { data: meta, error: null, canRead: true, isArchived: false, isError: false }
+ mocks.metaQuery = { data: meta, error: null, canRead: true, windowReady: true, isArchived: false, isError: false }
const storeListener = vi.fn()
const subscription = getCommunityRuntime(queryClient).ui.subscribe(storeListener)
const renderer = render(React.createElement(Harness))
@@ -366,7 +393,7 @@ describe("useChannelRouteModel subscription ownership", () => {
mocks.metaQuery = {
data: { ...meta },
error: null,
- canRead: true, isArchived: false,
+ canRead: true, windowReady: true, isArchived: false,
isError: false,
}
act(() => renderer.rerender(React.createElement(Harness)))
@@ -380,7 +407,7 @@ describe("useChannelRouteModel subscription ownership", () => {
mocks.metaQuery = {
data: undefined,
error: new Error("metadata unavailable"),
- canRead: false, isArchived: false,
+ canRead: false, windowReady: false, isArchived: false,
isError: true,
}
let renderer: ReturnType<typeof render>
@@ -407,7 +434,7 @@ describe("useChannelRouteModel subscription ownership", () => {
verifiedEpoch: 0,
},
error: null,
- canRead: false, isArchived: true,
+ canRead: false, windowReady: false, isArchived: true,
isError: false,
}
let renderer: ReturnType<typeof render>
@@ -442,7 +469,7 @@ describe("useChannelRouteModel subscription ownership", () => {
verifiedEpoch: 0,
},
error: null,
- canRead: false, isArchived: true,
+ canRead: false, windowReady: false, isArchived: true,
isError: false,
}
@@ -459,3 +486,206 @@ describe("useChannelRouteModel subscription ownership", () => {
act(() => renderer.unmount())
})
})
+
+
+it("retains the actual message deadline exit after a qualified route loses its native body, then releases on revoke", async () => {
+ const { conversationEntryFixture, seedConversationEntry } = await import("@/test/conversation-entry-fixtures")
+ const { getCommunityDbRegistry } = await import("@/lib/community-db/collections")
+ const { useMessages } = await import("./use-messages")
+ const value = conversationEntryFixture()
+ value.channelId = "post-1"
+ value.channel = { ...value.channel, id: "post-1", serverId: "server-1" }
+ value.messages = value.messages.map(message => ({ ...message, channelId: "post-1" }))
+ value.access.channelId = value.readState.channelId = value.surfaceReceipt.channelId = "post-1"
+ await seedConversationEntry(queryClient, value)
+ mocks.useRealMetadata = true
+ mocks.load.mockResolvedValue(value)
+ const registry = getCommunityDbRegistry(queryClient)!
+ let feed!: ReturnType<typeof useMessages>, mounts = 0, releases = 0
+ function Body() {
+ const current = useMessages("post-1", { serverId: "server-1" })
+ React.useLayoutEffect(() => { feed = current }, [current])
+ React.useEffect(() => { mounts++; return () => { releases++ } }, [])
+ return React.createElement("span", { "data-testid": "owned-body" }, current.positionDataState)
+ }
+ function Route() {
+ const model = useChannelRouteModel("server-1", "server-1", "post-1", "viewer")
+ return model.routeLifecycle === "ready" ? React.createElement(Body) : React.createElement("span", { "data-testid": "route-pending" }, model.routeLifecycle)
+ }
+ const view = render(React.createElement(Route))
+ await waitFor(() => expect(view.getByTestId("owned-body").textContent).toBe("ready"))
+ vi.useFakeTimers()
+ try {
+ await act(async () => { await registry.collections.messages.utils.writeDelete("m1") })
+ expect(view.getByTestId("owned-body").textContent).toBe("pending")
+ await act(async () => vi.advanceTimersByTimeAsync(14999))
+ expect(view.getByTestId("owned-body").textContent).toBe("pending")
+ await act(async () => vi.advanceTimersByTimeAsync(1))
+ expect(view.getByTestId("owned-body").textContent).toBe("error")
+ expect(feed.initialLoadError).toBeTruthy()
+ expect(feed.readSnapshot?.lastReadMessageId).toBe("m1")
+ expect(mounts).toBe(1)
+ expect(releases).toBe(0)
+ expect(mocks.load).not.toHaveBeenCalled()
+ await act(async () => registry.runtime.ws.actions.revokeChannelAccess("server-1", "post-1"))
+ expect(view.queryByTestId("owned-body")).toBeNull()
+ expect(releases).toBe(1)
+ } finally { view.unmount(); vi.useRealTimers() }
+})
+
+
+it("mounts the qualified native child surface while its entry window is held and keeps actions pending", async () => {
+ const { conversationEntryFixture } = await import("@/test/conversation-entry-fixtures")
+ const { channelResourceFixture, fullResourceBundleFixture, serverResourceFixture } = await import("@/test/community-resource-fixtures")
+ const { publishCommunityResourceBundle, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
+ const { useMessages } = await import("./use-messages")
+ const parent = channelResourceFixture({ id: "forum-1", serverId: "server-1", type: "forum" })
+ const child = channelResourceFixture({ id: "post-1", serverId: "server-1", type: "thread", parentChannelId: parent.id, parentMessageId: "opener-1" })
+ const value = conversationEntryFixture()
+ value.channelId = child.id
+ value.channel = child
+ value.messages = value.messages.map(message => ({ ...message, channelId: child.id }))
+ value.access.channelId = value.readState.channelId = value.surfaceReceipt.channelId = child.id
+ value.surfaceReceipt.surfaceKind = "thread"
+ value.parent = parent
+ publishCommunityResourceBundle(queryClient, fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server-1", ownerId: "viewer" })], [parent, child]), { token: captureCommunityLiveSnapshotToken(queryClient) })
+ mocks.dbParent = parent
+ mocks.useRealMetadata = true
+ let release!: (entry: typeof value) => void
+ mocks.load.mockReturnValue(new Promise(resolve => { release = resolve }))
+ let feed!: ReturnType<typeof useMessages>, ready: boolean | undefined, mounts = 0
+ function Surface() {
+ const current = useMessages(child.id, { serverId: "server-1" })
+ React.useLayoutEffect(() => { feed = current }, [current])
+ React.useEffect(() => { mounts++ }, [])
+ return React.createElement("span", { "data-testid": "native-child-surface" }, current.positionDataState)
+ }
+ function Route() {
+ const model = useChannelRouteModel("server-1", "server-1", child.id, "viewer")
+ React.useLayoutEffect(() => { ready = model.windowReady }, [model])
+ return model.routeHydrated && model.routeLifecycle === "ready" ? React.createElement(Surface) : React.createElement("span", null, model.routeLifecycle)
+ }
+ const view = render(React.createElement(Route))
+ try {
+ await waitFor(() => expect(view.getByTestId("native-child-surface").textContent).toBe("pending"))
+ expect(ready).toBe(false)
+ expect(feed.navigationBlocked).toBe(true)
+ expect(feed.messages).toEqual([])
+ expect(feed.fetchOlder()).toEqual({ accepted: false })
+ expect(feed.fetchNewer()).toEqual({ accepted: false })
+ expect(feed.jumpToPresent()).toEqual({ accepted: false })
+ expect(mocks.load).toHaveBeenCalledOnce()
+ await act(async () => { release(value) })
+ await waitFor(() => expect(view.getByTestId("native-child-surface").textContent).toBe("ready"))
+ expect(ready).toBe(true)
+ expect(feed.navigationBlocked).toBe(false)
+ expect(mounts).toBe(1)
+ expect(mocks.load).toHaveBeenCalledOnce()
+ } finally { view.unmount() }
+})
+
+
+it.each(["older", "newer", "jump"] as const)("rejects %s admission from a retained window after its native message readiness is lost", async action => {
+ const { conversationEntryFixture, seedConversationEntry } = await import("@/test/conversation-entry-fixtures")
+ const { getCommunityDbRegistry } = await import("@/lib/community-db/collections")
+ const { useMessages } = await import("./use-messages")
+ const value = conversationEntryFixture()
+ value.channelId = "post-1"
+ value.channel = { ...value.channel, id: "post-1", serverId: "server-1" }
+ value.messages = value.messages.map(message => ({ ...message, channelId: "post-1" }))
+ value.access.channelId = value.readState.channelId = value.surfaceReceipt.channelId = "post-1"
+ value.page.newerCursor = "newer"
+ value.page.hasMoreNewer = true
+ await seedConversationEntry(queryClient, value)
+ mocks.useRealMetadata = true
+ mocks.load.mockResolvedValue({ messages: value.messages, profiles: value.profiles, ...value.page })
+ const registry = getCommunityDbRegistry(queryClient)!
+ let feed!: ReturnType<typeof useMessages>
+ function Surface() {
+ const current = useMessages("post-1", { serverId: "server-1" })
+ React.useLayoutEffect(() => { feed = current }, [current])
+ return React.createElement("span", { "data-testid": "retained-action-window" }, current.positionDataState)
+ }
+ function Route() {
+ const model = useChannelRouteModel("server-1", "server-1", "post-1", "viewer")
+ return model.routeLifecycle === "ready" ? React.createElement(Surface) : null
+ }
+ const view = render(React.createElement(Route))
+ try {
+ await waitFor(() => expect(view.getByTestId("retained-action-window").textContent).toBe("ready"))
+ expect(feed.hasMoreOlder).toBe(true)
+ expect(feed.hasMoreNewer).toBe(true)
+ const earlier = action === "older" ? feed.fetchOlder : action === "newer" ? feed.fetchNewer : feed.jumpToPresent
+ const snapshot = feed.readSnapshot
+ await act(async () => { await registry.collections.messages.utils.writeDelete("m1") })
+ expect(feed.navigationBlocked).toBe(true)
+ expect(view.getByTestId("retained-action-window").textContent).toBe("pending")
+ let admitted!: ReturnType<typeof earlier>
+ act(() => { admitted = earlier() })
+ expect(admitted).toEqual({ accepted: false })
+ expect(mocks.load).not.toHaveBeenCalled()
+ expect(feed.readSnapshot).toEqual(snapshot)
+ const { publishCommunityMessages, captureCommunityLiveSnapshotToken } = await import("@/lib/community-db/sync")
+ await act(async () => { publishCommunityMessages(queryClient, { channelId: "post-1", messages: value.messages, profiles: value.profiles, proof: { token: captureCommunityLiveSnapshotToken(queryClient, "post-1") } }) })
+ await waitFor(() => expect(feed.navigationBlocked).toBe(false))
+ act(() => { admitted = earlier() })
+ expect(admitted.accepted).toBe(true)
+ if (admitted.accepted) {
+ const pending = admitted.completed
+ let completed!: Awaited<typeof pending>
+ await act(async () => { completed = await pending })
+ expect(completed.status).toBe("success")
+ }
+ expect(feed.readSnapshot).toEqual(snapshot)
+ expect(mocks.load).toHaveBeenCalledOnce()
+ } finally { view.unmount(); await queryClient.cancelQueries() }
+})
+
+
+it("keeps already accepted paging under its original owner when native readiness is lost in flight", async () => {
+ const { conversationEntryFixture, seedConversationEntry } = await import("@/test/conversation-entry-fixtures")
+ const { getCommunityDbRegistry } = await import("@/lib/community-db/collections")
+ const { useMessages } = await import("./use-messages")
+ const value = conversationEntryFixture()
+ value.channelId = "post-1"
+ value.channel = { ...value.channel, id: "post-1", serverId: "server-1" }
+ value.messages = value.messages.map(message => ({ ...message, channelId: "post-1" }))
+ value.access.channelId = value.readState.channelId = value.surfaceReceipt.channelId = "post-1"
+ await seedConversationEntry(queryClient, value)
+ mocks.useRealMetadata = true
+ const page = { messages: value.messages, profiles: value.profiles, ...value.page, hasMoreOlder: false, olderCursor: null }
+ let release!: (result: typeof page) => void
+ mocks.load.mockReturnValue(new Promise(resolve => { release = resolve }))
+ const registry = getCommunityDbRegistry(queryClient)!
+ let feed!: ReturnType<typeof useMessages>
+ function Surface() {
+ const current = useMessages("post-1", { serverId: "server-1" })
+ React.useLayoutEffect(() => { feed = current }, [current])
+ return React.createElement("span", { "data-testid": "accepted-page-window" }, current.positionDataState)
+ }
+ function Route() {
+ const model = useChannelRouteModel("server-1", "server-1", "post-1", "viewer")
+ return model.routeLifecycle === "ready" ? React.createElement(Surface) : null
+ }
+ const view = render(React.createElement(Route))
+ try {
+ await waitFor(() => expect(view.getByTestId("accepted-page-window").textContent).toBe("ready"))
+ const snapshot = feed.readSnapshot
+ let accepted!: ReturnType<typeof feed.fetchOlder>
+ act(() => { accepted = feed.fetchOlder() })
+ expect(accepted.accepted).toBe(true)
+ if (!accepted.accepted) throw new Error("Complete window did not accept paging")
+ await waitFor(() => expect(mocks.load).toHaveBeenCalledOnce())
+ await act(async () => { await registry.collections.messages.utils.writeDelete("m1") })
+ expect(feed.navigationBlocked).toBe(true)
+ expect(feed.jumpToPresent()).toEqual({ accepted: false })
+ const pending = accepted.completed
+ let completion!: Awaited<typeof pending>
+ await act(async () => { release(page); completion = await pending })
+ expect(completion.status).toBe("success")
+ await waitFor(() => expect(view.getByTestId("accepted-page-window").textContent).toBe("ready"))
+ expect(feed.navigationBlocked).toBe(false)
+ expect(feed.readSnapshot).toEqual(snapshot)
+ expect(mocks.load).toHaveBeenCalledOnce()
+ } finally { view.unmount(); await queryClient.cancelQueries() }
+})
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 f2720fc80..94d2a5222 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -95,7 +95,8 @@ export function useChannelRouteModel(
const model = useMemo(() => buildChannelRouteModel(server, renderableChannelMeta, channelId,
{ channelId, settled: metaQuery.canRead }, identity, canonicalParent),
[server, renderableChannelMeta, channelId, metaQuery.canRead, identity, canonicalParent])
- const routeLifecycle = metaQuery.canRead && !metadataExit ? "ready" as const
+ const surfaceReady = model.routeHydrated && metaQuery.canRead && !metadataExit && !metadataError
+ const routeLifecycle = surfaceReady ? "ready" as const
: metadataExit || metadataError ? "terminal-error" as const : "pending" as const
const skeletonSubtype = routeLifecycle === "ready"
? model.isChild ? "thread" as const : model.isForum ? "forum" as const : "text" as const
@@ -144,7 +145,8 @@ export function useChannelRouteModel(
return {
...model,
- routeHydrated: model.routeHydrated && metaQuery.canRead && !metadataExit,
+ routeHydrated: surfaceReady,
+ windowReady: metaQuery.windowReady,
routeLifecycle,
skeletonSubtype,
layoutHint,
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 0e5080d86..75fb5debf 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
@@ -1,3 +1,4 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { channelMetadataOptions } from "./channel-metadata"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
@@ -17,11 +18,11 @@ vi.mock("@/lib/api/client", () => ({
import { useChannelMetadata } from "./use-channel-metadata"
-const meta = (overrides: Partial<ReturnType<typeof channelSchema.parse>> = {}) => channelSchema.parse({ categoryId: null, topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
+const meta = (overrides: Partial<ReturnType<typeof channelResourceFixture>> = {}) => channelResourceFixture({ categoryId: null, topic: "", messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "post-1", serverId: "server-1", name: "post", type: "thread",
parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: "user-1",
archived: false, lastMessageAt: "2026-08-09T00:00:00.000Z",
- position: 0, muted: false, unread: false, tags: [], pending: false, ...overrides,
+ position: 0, ...overrides,
})
async function fixture() {
@@ -133,7 +134,7 @@ describe("child channel metadata stale rendering", () => {
)
const cached = meta()
createCommunityDbRegistry(queryClient, "viewer").collections.channels.utils.writeUpsert(channelSchema.parse({
- ...cached, position: 0, muted: false, unread: false, tags: [], pending: false,
+ ...cached, position: 0, muted: false, tags: [], pending: false,
lastMessageAt: cached.lastMessageAt,
}))
const rendered = renderHook(
@@ -163,8 +164,8 @@ describe("child channel metadata stale rendering", () => {
parentMessageId: "opener-1",
creatorId: null,
archived: false,
- lastMessageAt: undefined,
- position: 0, muted: false, unread: false, tags: [], pending: false,
+ lastMessageAt: null,
+ position: 0, muted: false, tags: [], pending: false,
}))
const wrapper = ({ children }: PropsWithChildren) => createElement(
QueryClientProvider,
diff --git a/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts b/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
index 655abbec5..4867ffc6f 100644
--- a/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
@@ -1,3 +1,5 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture, currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { getCapturedRuntime } from "./community-ws/test-harness"
import { act } from "@/test/react-dom-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -23,19 +25,20 @@ import {
} from "./community-ws/test-harness"
const subscriptions: Array<() => void> = []
-const message = (id: string, seq = 1) => ({
+const message = (channelId: string, id: string, seq = 1) => messageResourceFixture({
+ channelId,
id, seq, type: "chat" as const, content: id, authorId: "author",
createdAt: `2026-08-15T00:00:0${seq}.000Z`,
})
-const page = (id: string) => ({ messages: [message(id)], latestSeq: 1, hasMore: false })
+const page = (channelId: string, id: string) => (messageReadPageFixture({ messages: [message(channelId, id)], latestSeq: 1, hasMore: false }))
function seed(id: string, kind: "channel" | "dm" = "channel") {
const key = kind === "channel" ? communityKeys.channelMessages(id) : communityKeys.dmMessages(id)
- seedCanonicalMessages(id, [message(`old-${id}`)])
- capturedQueryClient.setQueryData(key, { pages: [messageWindowPage(page(`old-${id}`))], pageParams: [{ mode: "newest" }] })
+ seedCanonicalMessages(id, [message(id, `old-${id}`)])
+ capturedQueryClient.setQueryData(key, { pages: [messageWindowPage(page(id, `old-${id}`))], pageParams: [{ mode: "newest" }] })
const observer = new QueryObserver(capturedQueryClient, {
queryKey: key,
- queryFn: async () => ({ pages: [messageWindowPage(page(`query-${id}`))], pageParams: [{ mode: "newest" }] }),
+ queryFn: async () => ({ pages: [messageWindowPage(page(id, `query-${id}`))], pageParams: [{ mode: "newest" }] }),
staleTime: Infinity,
})
subscriptions.push(observer.subscribe(() => undefined))
@@ -65,7 +68,7 @@ describe("community foreground message reconciliation", () => {
await mountHook()
flushEffects()
await act(async () => { getCapturedRuntime().ws.actions.markAccessDisconnected() })
- getCommunityApiFetchMock().mockImplementation(async (path) => page(String(path)))
+ getCommunityApiFetchMock().mockImplementation(async (path) => page(String(path).split("/")[4]!, String(path)))
const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
await act(async () => { await capturedUseUserWsOptions!.onForeground!() })
const paths = getCommunityApiFetchMock().mock.calls.map(([path]) => path)
@@ -96,9 +99,9 @@ describe("community foreground message reconciliation", () => {
if (release) throw new Error(`unexpected duplicate snapshot: ${JSON.stringify(getCommunityApiFetchMock().mock.calls.map(([url]) => url))}`)
return new Promise((resolve) => { release = resolve })
}
- if (String(path).includes("/messages?since=")) return {
- messages: [message("missed", 2), message("live", 3)], latestSeq: 3, hasMoreNewer: false,
- }
+ if (String(path).includes("/messages?since=")) return messageReadPageFixture({
+ messages: [message("focused", "missed", 2), message("focused", "live", 3)], latestSeq: 3, hasMoreNewer: false,
+ })
if (path === "/api/community/users/me/read-state") return { revision: 0, readStates: [] }
throw new Error(`unexpected fetch: ${String(path)}`)
})
@@ -110,11 +113,11 @@ describe("community foreground message reconciliation", () => {
expect(capturedQueryClient.getQueryState([...key, "reconcile"])?.fetchStatus).toBe("fetching")
const event = messageCreate("focused", "live")
event.message.seq = 3
- await act(async () => { capturedOnMessage!(event) })
+ await act(async () => { capturedOnMessage!(currentCommunityEventFixture(event)) })
await Promise.resolve()
expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/channels/focused/messages")).toHaveLength(1)
expect(cancel.mock.calls.filter(([filters]) => JSON.stringify(filters.queryKey) === JSON.stringify(key))).toHaveLength(1)
- await act(async () => { release(page("snapshot-before-gap")) })
+ await act(async () => { release(page("focused", "snapshot-before-gap")) })
await act(async () => { await Promise.all([foreground, duplicate, reconnect]) })
expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => String(path).includes("/channels/focused/messages"))).toHaveLength(2)
expect(cancel.mock.calls.filter(([filters]) => JSON.stringify(filters.queryKey) === JSON.stringify(key))).toHaveLength(1)
@@ -129,14 +132,14 @@ describe("community foreground message reconciliation", () => {
let releaseOld!: (value: unknown) => void
getCommunityApiFetchMock().mockImplementation(async (path) => {
if (path === "/api/community/channels/a/messages") return new Promise((resolve) => { releaseOld = resolve })
- if (path === "/api/community/channels/b/messages") return page("current-b")
+ if (path === "/api/community/channels/b/messages") return page("b", "current-b")
throw new Error(`unexpected fetch: ${String(path)}`)
})
let old!: void | Promise<void>; act(() => { old = capturedUseUserWsOptions!.onForeground!() })
await vi.waitFor(() => expect(releaseOld).toBeTypeOf("function"))
await act(async () => { getCapturedRuntime().ui.actions.subscribe({ channelId: "b" }) })
await act(async () => { await capturedUseUserWsOptions!.onForeground!() })
- await act(async () => { releaseOld(page("late-a")) })
+ await act(async () => { releaseOld(page("a", "late-a")) })
await act(async () => { await old })
expect(capturedQueryClient.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(currentKey)?.pages.flatMap((entry) => entry.messages.map((row) => row.id))).toEqual(["old-b", "current-b"])
})
@@ -155,7 +158,7 @@ describe("community foreground message reconciliation", () => {
await mountHook({ viewerUserId: "b" })
await old()
expect(getCommunityApiFetchMock()).not.toHaveBeenCalled()
- getCommunityApiFetchMock().mockResolvedValue(page("current-account"))
+ getCommunityApiFetchMock().mockResolvedValue(page("account-target", "current-account"))
await act(async () => { await capturedUseUserWsOptions!.onForeground!() })
expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce()
})
diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
index c66d883ea..2f4ea42fb 100644
--- a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
@@ -1,3 +1,4 @@
+import { currentCommunityEventFixture, messageResourceFixture, resourceBundleFixture } from "@/test/community-resource-fixtures"
import { getCapturedRuntime } from "./community-ws/test-harness"
import { act } from "@/test/react-dom-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -17,7 +18,7 @@ import {
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { registerReadSurface, releaseReadSurface, submitReadIntent } from "./read-coordinator"
-const emptyAttention = { scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+const emptyAttention = { resources: resourceBundleFixture({ viewerId: "u_me" }), scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
const attentionCalls = () => getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/attention")
beforeEach(async () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")
@@ -29,7 +30,7 @@ describe("community read-state lifecycle reconciliation", () => {
it("settles admitted reading through its account owner after the WS hook unmounts without old structural fallback", async () => {
vi.useFakeTimers()
getCapturedRuntime().ui.actions.subscribe({ channelId: "ch-1" })
- await mountHook({ viewerUserId: "viewer-1" })
+ await mountHook({ viewerUserId: "u_me" })
flushEffects()
seedCommunityAttentionScope(capturedQueryClient, { channelId: "ch-1", serverId: "s1", seq: 1 })
let releaseRead!: () => void
@@ -44,9 +45,9 @@ describe("community read-state lifecycle reconciliation", () => {
throw new Error(`unexpected API fetch: ${String(url)}`)
})
const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const lease = registerReadSurface(capturedQueryClient, "viewer-1", { kind: "timeline", channelId: "ch-1" })
+ const lease = registerReadSurface(capturedQueryClient, "u_me", { kind: "timeline", channelId: "ch-1" })
try {
- await act(async () => { await capturedOnMessage!({ type: "community:message.create", channelId: "ch-1", message: { id: "message-1", seq: 1, authorId: "author-1", authorName: "Alice", authorAvatarVersion: 0, content: "hello", type: "chat", createdAt: "2026-08-27T00:00:00.000Z" } }) })
+ await act(async () => { await capturedOnMessage!(currentCommunityEventFixture({ type: "community:message.create", profiles: [{ id: "author-1", name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 }], channelId: "ch-1", message: messageResourceFixture({ id: "message-1", channelId: "ch-1", seq: 1, authorId: "author-1", authorName: "Alice", authorAvatarVersion: 0, content: "hello", createdAt: "2026-08-27T00:00:00.000Z" }) })) })
expect(canonicalRegistry!.collections.messages.get("message-1")?.createdAt).toBe("2026-08-27T00:00:00.000Z")
await act(async () => {
expect(submitReadIntent(lease, { kind: "timeline", channelId: "ch-1", messageId: "message-1", seq: 1 })).toBe(true)
@@ -60,20 +61,20 @@ describe("community read-state lifecycle reconciliation", () => {
expect(canonicalRegistry!.collections.attentionScopes.get("ch-1")).toBeUndefined()
expect(capturedQueryClient.getQueryData(communityKeys.accountReadStateSnapshot())).toEqual({ revision: 1 })
expect(invalidate.mock.calls.some(([filters]) => [communityKeys.inbox(), communityKeys.dms()].some(key => JSON.stringify(filters.queryKey) === JSON.stringify(key)))).toBe(false)
- } finally { releaseRead(); releaseReadSurface(lease); await vi.runAllTimersAsync() }
+ } finally { releaseRead(); releaseReadSurface(lease); await vi.advanceTimersByTimeAsync(0) }
})
it("schedules the first-auth attention owner before read-state reconciliation completes", async () => {
vi.useFakeTimers()
- await mountHook({ viewerUserId: "viewer-1" })
- act(() => getCapturedRuntime().ws.actions.setPresence("viewer-1", "offline"))
+ await mountHook({ viewerUserId: "u_me" })
+ act(() => getCapturedRuntime().ws.actions.setPresence("u_me", "offline"))
let releaseSnapshot!: (value: unknown) => void
getCommunityApiFetchMock().mockImplementationOnce(() => new Promise(resolve => { releaseSnapshot = resolve }))
let outcome!: Promise<unknown>
act(() => { outcome = Promise.resolve(capturedUseUserWsOptions!.onAuthenticated!()).then(() => null, error => error) })
try {
expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
- expect(getCapturedRuntime().ws.get().presenceByUserId.get("viewer-1")).toBe("online")
+ expect(getCapturedRuntime().ws.get().presenceByUserId.get("u_me")).toBe("online")
await vi.waitFor(() => expect(attentionCalls()).toHaveLength(1))
expect(capturedQueryClient.getQueryState(communityKeys.accountReadStateSnapshot())?.fetchStatus).toBe("fetching")
} finally {
diff --git a/src/web/src/hooks/community/use-community-ws.dom.test.ts b/src/web/src/hooks/community/use-community-ws.dom.test.ts
index 4eb75622a..80921a921 100644
--- a/src/web/src/hooks/community/use-community-ws.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.dom.test.ts
@@ -29,14 +29,14 @@ import {
import {
COMMUNITY_WS_FAILED_AFTER_MS,
} from "./community-ws/connection-status"
-import { deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatch, prepareCommunityDeliveryEvents } from "@alook/shared"
+import { communityBrowserEventBatchType, deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatch, prepareCommunityDeliveryEvents } from "@alook/shared"
import * as analytics from "@/lib/analytics"
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — non-community events bail", () => {
- it("drops a v3 batch on a v2 connection while retaining legacy admission", async () => {
+ it("rejects an old v3 batch and admits a current encoded batch", async () => {
await mountHook()
const dropped = vi.spyOn(analytics, "trackCommunityWsFrameDropped")
const setSpy = vi.spyOn(capturedQueryClient, "setQueryData")
@@ -47,10 +47,10 @@ describe("useCommunityWs — non-community events bail", () => {
const events = [{ type: "community:presence.update", userId: "peer", online: true }]
const prepared = await prepareCommunityDeliveryEvents(events)
if (!prepared.ok) throw new Error("invalid presence fixture")
- const encoded = await encodeCommunityBrowserEventBatch({ operationDigest: prepared.prepared.digest, operationId: await deriveCommunityDeliveryOperationId("legacy-presence"),
+ const encoded = await encodeCommunityBrowserEventBatch({ operationDigest: prepared.prepared.digest, operationId: await deriveCommunityDeliveryOperationId("current-presence"),
events })
- if (!encoded.ok) throw new Error("invalid legacy fixture")
- expect(encoded.batch.type).toBe("community:events.batch")
+ if (!encoded.ok) throw new Error("invalid current fixture")
+ expect(encoded.batch.type).toBe(communityBrowserEventBatchType())
await capturedOnMessage!(encoded.batch)
await vi.waitFor(() => expect(getCapturedRuntime().ws.get().presenceByUserId.get("peer")).toBe("online"))
expect(dropped).toHaveBeenCalledOnce()
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 6aac56787..df6907bed 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -1,4 +1,5 @@
"use client"
+import { requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
import { bindCommunityTransport, useCommunityRuntime, type CommunityRuntime } from "@/stores/community/runtime"
@@ -26,6 +27,7 @@ import type {
UseCommunityWsOptions,
} from "@/hooks/community/community-ws/handler-context"
import {
+ COMMUNITY_CONTRACT_VERSION,
decodeCommunityBrowserEvent,
communityBrowserEventBatchType,
admitCommunityBrowserEventBatch,
@@ -185,7 +187,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}, [runtime.ws.actions, viewerUserId])
const handleMessage = useCallback(
- async (msg: { type: string;[key: string]: unknown }, assertAdmissionCurrent?: () => void, contract: CommunityContract = 2) => {
+ async (msg: { type: string;[key: string]: unknown }, assertAdmissionCurrent?: () => void, contract: CommunityContract = COMMUNITY_CONTRACT_VERSION) => {
if (!msg.type.startsWith("community:")) return
if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active) return
const communityStore = runtime.ui
@@ -230,8 +232,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}
if (isCommunityBrowserEventBatchCandidate(msg)) {
- if (msg.type !== communityBrowserEventBatchType(contract)
- && !(contract === 2 && msg.type === communityBrowserEventBatchType(1))) {
+ if (msg.type !== communityBrowserEventBatchType(contract)) {
trackCommunityWsFrameDropped({ reason: "invalid-payload", type: msg.type })
return
}
@@ -241,6 +242,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
try { assertAdmissionCurrent?.(); assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined) } catch { return }
if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active) return
if (!decoded.ok) {
+ requestBusinessSchemaUpdate()
const reason = decoded.reason === "oversized" ? "oversized" : "invalid-payload"
const metadata = {
reason,
@@ -307,6 +309,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
const decoded = decodeCommunityBrowserEvent(msg, contract)
if (!decoded.ok) {
+ requestBusinessSchemaUpdate()
const metadata = {
reason: decoded.reason,
type: isCommunityEventType(msg.type) ? msg.type : "unknown",
diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
index 17a11aef6..f1e74bc24 100644
--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
@@ -1,17 +1,19 @@
+import { resourceBundleFixture, fullResourceBundleFixture, serverResourceFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createElement, type PropsWithChildren } from "react"
-import { QueryClientProvider } from "@tanstack/react-query"
+import { QueryClientProvider, QueryObserver } from "@tanstack/react-query"
import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { conversationEntryFixture as fixture, dmConversationEntryFixture, forumConversationEntryFixture, conversationEntryTarget as target } from "@/test/conversation-entry-fixtures"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { registerCommunityDbRegistry } from "@/lib/community-db/collections"
-import { captureCommunityLiveSnapshotToken, ingestMessages, ingestReadStateSnapshot, publishAccountAttentionSnapshot } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishCommunityResourceBundle, publishCommunityMessages, ingestMessages, ingestReadStateSnapshot, publishAccountAttentionSnapshot } from "@/lib/community-db/sync"
import { conversationEntryOptions, currentConversationReadState, publishConversationEntry } from "@/lib/community/conversation-entry"
import { communityKeys } from "@/lib/query-keys"
import { ConversationReadTimeoutError } from "@/lib/community/conversation-read"
import { CommunityRouteContext } from "@/contexts/community/route-frame"
import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
+import { reconcileWindow } from "./community-ws/reconnect-messages"
import { useConversationEntry } from "./use-conversation-entry"
import { useChannelMetadata } from "./use-channel-metadata"
import { useDmMessages, useMessages } from "./use-messages"
@@ -49,6 +51,149 @@ async function setup() {
}
describe("conversation entry selection", () => {
+ it("ignores actual reconnect helper cache keys when the original entry hook consumes a complete warm window", async () => {
+ const { client, wrapper, publish } = await setup()
+ const value = fixture()
+ const resource = publish(value)
+ const observer = new QueryObserver(client, { queryKey: resource.windowKey, queryFn: async () => client.getQueryData(resource.windowKey), staleTime: Infinity })
+ const stop = observer.subscribe(() => undefined)
+ const repairPage = { profiles: value.profiles, messages: value.messages, ...value.page }
+ const held = deferred<typeof repairPage>()
+ load.mockReturnValue(held.promise)
+ const repair = reconcileWindow(client, { kind: "channel", scopeId: "c1", serverId: "s1" }, resource.windowKey, 1)
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(client.getQueryData([...resource.windowKey, "reconcile-target"])).toBe(1)
+ const reads = load.mock.calls.length
+ const hook = renderHook(() => ({ entry: useConversationEntry(target), surface: useMessages("c1", { serverId: "s1" }) }), { wrapper })
+ await waitFor(() => expect(hook.result.current.surface.messages.map(message => message.id)).toEqual(["m1"]))
+ expect(hook.result.current.surface.navigationBlocked).toBe(false)
+ expect(hook.result.current.entry.window).not.toBeNull()
+ expect(load).toHaveBeenCalledTimes(reads)
+ await act(async () => { held.resolve(repairPage); await repair })
+ expect(client.getQueryData([...resource.windowKey, "reconcile"])).toEqual({ latestSeq: 1 })
+ expect(hook.result.current.surface.navigationBlocked).toBe(false)
+ expect(load).toHaveBeenCalledTimes(reads)
+ hook.unmount()
+ stop()
+ })
+
+ it("keeps a complete current window usable when an unselected old anchor has no author", async () => {
+ const { client, wrapper, registry, publish } = await setup()
+ const value = fixture()
+ value.selection = { reason: "tail", anchorMessageId: null }
+ const current = publish(value)
+ const old = { ...value.messages[0], id: "old-message", authorId: "old-author", seq: 0 }
+ publishCommunityMessages(client, { channelId: "c1", messages: [old], profiles: [profileResourceFixture({ id: "old-author", name: "Old Author" })], proof: { token: captureCommunityLiveSnapshotToken(client, "c1") } })
+ const oldKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: old.id })
+ const oldWindow = { pages: [{ ...value.page, messages: [{ id: old.id, seq: old.seq }] }], pageParams: [{ mode: "anchor", anchor: old.id }] }
+ client.setQueryData(oldKey, oldWindow)
+ registry.collections.profiles.utils.writeDelete("old-author")
+ load.mockReturnValue(new Promise(() => {}))
+ const hook = renderHook(() => ({ metadata: useChannelMetadata("s1", "c1"), surface: useMessages("c1", { serverId: "s1" }) }), { wrapper })
+ await waitFor(() => expect(hook.result.current.metadata.windowReady).toBe(true))
+ expect(hook.result.current.surface.navigationBlocked).toBe(false)
+ expect(hook.result.current.surface.messages.map(message => message.id)).toEqual(["m1"])
+ expect(client.getQueryData(oldKey)).toBe(oldWindow)
+ expect(client.getQueryData(current.windowKey)).toBeDefined()
+ expect(registry.collections.messages.get(old.id)).toMatchObject({ authorId: "old-author" })
+ expect(registry.collections.profiles.has("old-author")).toBe(false)
+ expect(load).not.toHaveBeenCalled()
+ hook.unmount()
+ })
+
+ it("repairs the current missing author even when an unselected old anchor has no body", async () => {
+ const { client, wrapper, registry, publish } = await setup()
+ const value = fixture()
+ value.selection = { reason: "tail", anchorMessageId: null }
+ publish(value)
+ const oldKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "missing-old-body" })
+ const oldWindow = { pages: [{ ...value.page, messages: [{ id: "missing-old-body", seq: 0 }] }], pageParams: [{ mode: "anchor", anchor: "missing-old-body" }] }
+ client.setQueryData(oldKey, oldWindow)
+ const held = deferred<typeof value>()
+ load.mockReturnValue(held.promise)
+ const hook = renderHook(() => ({ metadata: useChannelMetadata("s1", "c1"), surface: useMessages("c1", { serverId: "s1" }) }), { wrapper })
+ await waitFor(() => expect(hook.result.current.metadata.windowReady).toBe(true))
+ expect(load).not.toHaveBeenCalled()
+ await act(async () => { registry.collections.profiles.utils.writeDelete("peer") })
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(hook.result.current.metadata.windowReady).toBe(false)
+ expect(hook.result.current.surface.navigationBlocked).toBe(true)
+ await act(async () => held.resolve(value))
+ await waitFor(() => expect(hook.result.current.metadata.windowReady).toBe(true))
+ expect(hook.result.current.surface.navigationBlocked).toBe(false)
+ expect(client.getQueryData(oldKey)).toBe(oldWindow)
+ expect(load).toHaveBeenCalledOnce()
+ hook.unmount()
+ })
+
+ it.each(["messages-shape", "missing-author", "forum-shape"])("rereads an incomplete cached dependency through ordinary entry ($0)", async defect => {
+ const { client, wrapper, registry, publish } = await setup()
+ const value = defect === "forum-shape" ? forumConversationEntryFixture() : fixture()
+ const destination = { channelId: "c1", serverId: value.channel.serverId }
+ const resource = defect === "forum-shape" ? publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") }) : publish(value)
+ client.setQueryData(conversationEntryOptions(client, destination).queryKey, resource)
+ if (defect === "messages-shape") client.setQueryData(resource.windowKey, { pages: [{ messages: 42 }], pageParams: [{ mode: "newest" }] })
+ if (defect === "forum-shape") client.setQueryData(communityKeys.forumFeed("c1", null), { pages: [{ threads: 42 }], pageParams: [null] })
+ if (defect === "missing-author") registry.collections.profiles.utils.writeDelete(value.messages[0].authorId)
+ const held = deferred<typeof value>()
+ load.mockReturnValue(held.promise)
+ const hook = renderHook(() => useChannelMetadata(destination.serverId, "c1"), { wrapper })
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(hook.result.current.canRead).toBe(true)
+ expect(hook.result.current.windowReady).toBe(false)
+ await act(async () => held.resolve(value))
+ await waitFor(() => expect(hook.result.current.windowReady).toBe(true))
+ expect(load).toHaveBeenCalledOnce()
+ hook.unmount()
+ })
+
+ it.each([
+ { kind: "text", useSurface: function useText() { return useMessages("c1", { serverId: "s1" }) } },
+ { kind: "dm", useSurface: function useDm() { return useDmMessages("c1") } },
+ ])("keeps current $kind permission separate from a missing owned entry window", async ({ kind, useSurface }) => {
+ const { client, wrapper } = await setup()
+ const value = kind === "dm" ? dmConversationEntryFixture() : fixture()
+ publishCommunityResourceBundle(client, fullResourceBundleFixture(value.viewerId,
+ value.channel.serverId ? [serverResourceFixture({ id: value.channel.serverId, ownerId: value.viewerId })] : [],
+ [value.channel], [], value.peer ? [value.peer] : []), { token: captureCommunityLiveSnapshotToken(client) })
+ const held = deferred<typeof value>()
+ load.mockReturnValue(held.promise)
+ const hook = renderHook(() => ({ metadata: useChannelMetadata(value.channel.serverId, "c1"),
+ messages: useSurface() }), { wrapper })
+ await waitFor(() => expect(hook.result.current.metadata.canRead).toBe(true))
+ expect(hook.result.current.metadata.data?.id).toBe("c1")
+ expect(hook.result.current.metadata.windowReady).toBe(false)
+ expect(hook.result.current.messages.navigationBlocked).toBe(true)
+ expect(hook.result.current.messages.messages).toEqual([])
+ expect(load).toHaveBeenCalledOnce()
+ await act(async () => held.resolve(value))
+ await waitFor(() => expect(hook.result.current.metadata.windowReady).toBe(true))
+ await waitFor(() => expect(hook.result.current.messages.navigationBlocked).toBe(false))
+ await waitFor(() => expect(hook.result.current.messages.messages[0]?.id).toBe("m1"))
+ expect(load).toHaveBeenCalledOnce()
+ hook.unmount()
+ })
+
+ it("offers the existing retry after a scope-only entry window fails, while retaining identity", async () => {
+ const { client, wrapper } = await setup()
+ const value = dmConversationEntryFixture()
+ publishCommunityResourceBundle(client, fullResourceBundleFixture(value.viewerId, [], [value.channel], [], [value.peer!]),
+ { token: captureCommunityLiveSnapshotToken(client) })
+ load.mockRejectedValue(new ConversationReadTimeoutError())
+ const hook = renderHook(() => ({ metadata: useChannelMetadata(null, "c1"), messages: useDmMessages("c1") }), { wrapper })
+ await waitFor(() => expect(hook.result.current.metadata.status).toBe("retryable-error"))
+ expect(hook.result.current.metadata.canRead).toBe(true)
+ expect(hook.result.current.metadata.data?.id).toBe("c1")
+ expect(hook.result.current.metadata.windowReady).toBe(false)
+ expect(hook.result.current.messages.navigationBlocked).toBe(true)
+ load.mockResolvedValue(value)
+ await act(async () => { await hook.result.current.metadata.retry() })
+ await waitFor(() => expect(hook.result.current.metadata.windowReady).toBe(true))
+ expect(hook.result.current.metadata.status).toBe("readable")
+ expect(load).toHaveBeenCalledTimes(2)
+ hook.unmount()
+ })
+
it.each([
{ kind: "text", useSurface: function useText() { return useMessages("c1", { serverId: "s1" }) } },
{ kind: "dm", useSurface: function useDm() { return useDmMessages("c1") } },
@@ -75,6 +220,7 @@ describe("conversation entry selection", () => {
}, { wrapper })
await waitFor(() => expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true))
expect(hook.result.current.metadata.canRead).toBe(true)
+ expect(hook.result.current.metadata.windowReady).toBe(true)
expect(hook.result.current.metadata.data?.id).toBe("c1")
expect(hook.result.current.metadata.isFetching).toBe(true)
if ("messages" in hook.result.current.surface) {
@@ -101,6 +247,7 @@ describe("conversation entry selection", () => {
expect(hook.result.current.messages).toEqual([])
expect(hook.result.current.initialPositionKnown).toBe(true)
expect(hook.result.current.positionDataState).toBe("empty")
+ expect(hook.result.current.navigationBlocked).toBe(false)
expect(hook.result.current.isFetching).toBe(true)
hook.unmount()
})
@@ -461,7 +608,7 @@ describe("conversation entry return during accepted reading", () => {
await act(async () => {
ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [readState] })
publishAccountAttentionSnapshot(owner.client, {
- snapshot: { scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1",
+ snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1",
ordinaryUnread: true, lastUnreadSeq: 45, lastAttentionSeq: null, attentionCount: 0 }], items: [], limit: 100, truncated: false,
included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined },
@@ -887,7 +1034,7 @@ describe("conversation entry return during accepted reading", () => {
fresh.page = { olderCursor: "older", newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 80 }
await act(async () => {
ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [read60] })
- ingestMessages(owner.registry, "c1", [{ ...fresh.messages.at(-1)!, resourceComplete: true }])
+ ingestMessages(owner.registry, "c1", [fresh.messages.at(-1)!])
owner.runtime.messageStream.actions.dispatch({ kind: "channel", id: "c1", serverId: "s1" }, {
type: "wsMessage", message: fresh.messages.at(-1)!,
})
@@ -937,7 +1084,7 @@ describe("native entry freshness with authoritative newer attention", () => {
expect(client.getQueryCache().find({ queryKey: original.windowKey, exact: true })?.isActive()).toBe(false)
load.mockClear()
publishAccountAttentionSnapshot(client, {
- snapshot: { scopes: [{ scopeId: packet.channelId, channelId: packet.channelId, serverId: packet.channel.serverId,
+ snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: packet.channelId, channelId: packet.channelId, serverId: packet.channel.serverId,
ordinaryUnread: newer, lastUnreadSeq: newer ? 2 : 1, lastAttentionSeq: null, attentionCount: 0 }], items: [], limit: 100, truncated: false,
included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
index 1ef24558b..a164ee13c 100644
--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
@@ -1,3 +1,5 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { resourceBundleFixture } from "@/test/community-resource-fixtures"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { StrictMode, useLayoutEffect } from "react"
import { useChannelMessageFeed } from "./use-channel-message-feed"
@@ -90,6 +92,7 @@ function entry(kind: Kind, channelId = "c1", ownTail = false) {
id: `${prefix}${index + 1}`, seq: index + 1, authorId: ownTail && index === 41 ? viewer.id : "peer",
createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString(),
}))
+ value.profiles = messageProfilesFixture(value.messages)
value.readState = { channelId, lastReadMessageId: `${prefix}30`, lastReadSeq: 30, lastReadAt: value.messages[29].createdAt }
value.selection = { reason: "read_pointer", anchorMessageId: `${prefix}30` }
value.surfaceReceipt = { channelId, surfaceKind: kind === "channel" ? "channel" : "thread" }
@@ -110,7 +113,7 @@ async function setup(kind: Kind, ownTail = false, strict = false, options: {
await seedConversationEntry(owner.client, entry("channel", "c2"))
if (options.readPointer) ingestReadStateSnapshot(owner.registry, { revision: 2, readStates: [options.readPointer] })
if (options.latestAttentionSeq) publishAccountAttentionSnapshot(owner.client, {
- snapshot: { scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1", ordinaryUnread: true,
+ snapshot: { resources: resourceBundleFixture(), scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1", ordinaryUnread: true,
lastUnreadSeq: options.latestAttentionSeq, lastAttentionSeq: null, attentionCount: 0 }],
items: [], limit: 100, truncated: false,
included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
@@ -124,10 +127,10 @@ async function setup(kind: Kind, ownTail = false, strict = false, options: {
load.mockImplementation((url: string) => {
if (url === "/api/community/channels/c1/messages?entry=1" && options.refresh) return options.refresh
if (url === "/api/community/channels/c1/messages" && options.refreshWindow) return options.refreshWindow.then(value => ({
- ...value.page, messages: value.messages,
+ ...value.page, profiles: value.profiles, messages: value.messages,
}))
if (url.startsWith("/api/community/channels/c1/messages?since=") && options.refresh) return options.refresh.then(value => ({
- ...value.page, messages: value.messages.filter(message => message.seq > 1),
+ ...value.page, profiles: value.profiles, messages: value.messages.filter(message => message.seq > 1),
}))
if (url.endsWith("/read")) return put
if (url === "/api/community/users/me/read-state") return canonicalTransport
@@ -338,17 +341,13 @@ describe("conversation entry positioning through real reading owners", () => {
}
})
- it("preserves600px of real cached message-owner layout on a stale-entry remount", async () => {
+ it("uses the normal unread entry after a stale cached message-owner remount", async () => {
const view = await setup("channel", true)
await view.tail()
const oldRoot = view.root()
fireEvent.wheel(oldRoot, { deltaY: -600 })
act(() => oldRoot.scrollTo({ top: oldRoot.scrollHeight - oldRoot.clientHeight - 600 }))
resize()
- const bodies = Array.from(oldRoot.querySelectorAll<HTMLElement>("[data-msg-id]"))
- const original = bodies.find(body => body.getBoundingClientRect().bottom > 0)!
- const id = original.dataset.msgId!
- const before = original.getBoundingClientRect().top
const offset = oldRoot.scrollTop
expect(oldRoot.scrollHeight - oldRoot.clientHeight - offset).toBe(600)
await view.navigate("/c/channels/s1/c2")
@@ -358,8 +357,10 @@ describe("conversation entry positioning through real reading owners", () => {
load.mockImplementation((url: string, options: unknown) => url === "/api/community/channels/c1/messages?entry=1" ? new Promise(() => {}) : previousLoad(url, options))
await view.navigate("/c/channels/s1/c1")
expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true)
- expect(view.root().scrollTop).toBeCloseTo(offset, 0)
- expect(view.root().querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(before, 0)
+ expect(view.root().scrollTop).not.toBeCloseTo(offset, 0)
+ expect(view.visible("m31")).toBe(true)
+ expect(latest.feed.newDividerBefore).toBe("m31")
+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)
expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)
})
@@ -480,7 +481,7 @@ describe("conversation entry positioning through real reading owners", () => {
expect(load.mock.calls.some(([url]) => String(url).includes("messages"))).toBe(false)
})
- it("restores layout without promoting a retired observation to a reading cursor and freezes late publication", async () => {
+ it("uses normal entry without promoting a retired observation and freezes late publication", async () => {
const view = await setup("channel")
await view.tail()
const row = view.root().querySelector('[data-msg-id="m42"]')!, observer = boundObserver(row), record = intersection(row)
@@ -489,8 +490,8 @@ describe("conversation entry positioning through real reading owners", () => {
act(() => observer.callback([record], {} as IntersectionObserver))
expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
await view.navigate("/c/channels/s1/c1")
- expect(view.visible("m42")).toBe(true)
- expect(view.visible("m31")).toBe(false)
+ expect(view.visible("m42")).toBe(false)
+ expect(view.visible("m31")).toBe(true)
expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
const offset = view.root().scrollTop
await view.canonical(42)
@@ -499,7 +500,7 @@ describe("conversation entry positioning through real reading owners", () => {
expect(messageOrReadRequests()).toEqual([])
})
- it.each(["threshold", "inert", "document-hidden", "own-author"] as const)("restores layout without turning a rejected %s observation into a reading cursor", async control => {
+ it.each(["threshold", "inert", "document-hidden", "own-author"] as const)("uses normal entry without turning a rejected %s observation into a reading cursor", async control => {
const view = await setup("channel", control === "own-author")
await view.tail()
const row = view.root().querySelector('[data-msg-id="m42"]')!, observer = boundObserver(row)
@@ -510,7 +511,8 @@ describe("conversation entry positioning through real reading owners", () => {
visibility = "visible"
await view.navigate("/c/channels/s1/c2")
await view.navigate("/c/channels/s1/c1")
- expect(view.visible("m42")).toBe(true)
+ expect(view.visible("m42")).toBe(false)
+ expect(view.visible("m31")).toBe(true)
expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)
expect(messageOrReadRequests()).toEqual([])
diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.ts
index a5179575b..c812468b2 100644
--- a/src/web/src/hooks/community/use-conversation-entry.ts
+++ b/src/web/src/hooks/community/use-conversation-entry.ts
@@ -6,8 +6,9 @@ import { hashKey, useQuery, useQueryClient } from "@tanstack/react-query"
import { useConversationActivity, useConversationPresentation } from "@/contexts/community/conversation-activity"
import { CommunityRouteContext } from "@/contexts/community/route-frame"
import { channelHref, normalizeCommunityHref } from "@/lib/community/community-route"
-import type { CommunityReadStateResource } from "@alook/shared"
-import { useChannelReadStateProjection, useChannelRosterRows, useRouteChannelProjection } from "@/lib/community-db/projections"
+import { communityMessageProfileIds, CommunityMessageResourceSchema, CommunityResourceProfileSchema, type CommunityReadStateResource } from "@alook/shared"
+import { useCanonicalMessagesById, useCanonicalProfilesProjection, useChannelReadStateProjection, useChannelRosterRows, useRouteChannelProjection } from "@/lib/community-db/projections"
+import { getCanonicalCommunityMessageResources } from "@/lib/community-db/sync"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useCommunityRuntime } from "@/stores/community/runtime"
import { isChannelMetadataTokenCurrent } from "@/lib/community/conversation-qualification"
@@ -112,13 +113,58 @@ export function useConversationResource(target: ConversationEntryTarget | null,
if (pointer && !findConversationEntryWindow(client, input, query.data, pointer)) void client.query({ ...options, select: undefined }).catch(() => undefined)
}, [client, channelId, intent, input, options, query.data, query.isFetching, query.isError, revoked, target, presented])
const currentPointer = read.readState ?? (read.hasSnapshot ? currentConversationReadState(client, channelId) : undefined)
- const cachedWindow = scope ? findConversationDisplayWindow(client, baseInput, scope) : undefined
+ const retainedIds = client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages(channelId) }).flatMap(query => {
+ const identity = messageWindowIdentity(query.queryKey)
+ if (!identity || identity.tag !== tag || identity.initial.mode === "since") return []
+ const value = query.state.data as MessageWindowData | undefined
+ if (!Array.isArray(value?.pages) || !Array.isArray(value.pageParams) || !value.pages.length || value.pages.length !== value.pageParams.length
+ || value.pages.some(page => !Array.isArray(page?.messages) || page.messages.some(message => typeof message?.id !== "string" || !message.id))) return []
+ return value.pages.flatMap(page => page.messages.map(message => message.id))
+ })
+ const forumMessageIds: string[] = []
+ const forum = client.getQueryData<{ pages: import("./forum-feed-window").ForumFeedPage[] }>(communityKeys.forumFeed(channelId, tag))
+ if (Array.isArray(forum?.pages)) for (const page of forum.pages) if (Array.isArray(page?.threads)) for (const thread of page.threads) {
+ if (!thread || typeof thread.id !== "string") continue
+ if (typeof thread.openerMessageId === "string") forumMessageIds.push(thread.openerMessageId)
+ const child = getCommunityDbRegistry(client)?.collections.channels.get(thread.id)
+ if (child?.firstMessageId) forumMessageIds.push(child.firstMessageId)
+ }
+ retainedIds.push(...forumMessageIds)
+ const retainedMessages = useCanonicalMessagesById([...new Set(retainedIds)])
+ const retainedResources = [...(retainedMessages?.keys() ?? [])].flatMap(id => {
+ const parsed = CommunityMessageResourceSchema.strip().safeParse(getCommunityDbRegistry(client)?.collections.messages.get(id))
+ return parsed.success ? [parsed.data] : []
+ })
+ const retainedProfileIds = communityMessageProfileIds(retainedResources)
+ const retainedProfiles = useCanonicalProfilesProjection(retainedProfileIds)
+ const availableWindow = readableScope ? findConversationDisplayWindow(client, baseInput, readableScope) : undefined
+ const availableMessageIds = availableWindow && messageWindowIdentity(availableWindow.key)
+ ? client.getQueryData<MessageWindowData>(availableWindow.key)!.pages.flatMap(page => page.messages.map(message => message.id))
+ : forumMessageIds
+ const availableGraph = availableWindow ? getCanonicalCommunityMessageResources(client,
+ availableMessageIds.map(id => getCommunityDbRegistry(client)?.collections.messages.get(id))) : undefined
+ const requiredProfileIds = availableGraph?.profiles.map(profile => profile.id) ?? retainedProfileIds
+ const profilesReady = requiredProfileIds.length === 0 || retainedProfiles.isReady && !retainedProfiles.isError
+ && requiredProfileIds.every(id => CommunityResourceProfileSchema.strip().safeParse(retainedProfiles.resourceProfiles.get(id)).success)
+ const cachedWindow = profilesReady ? availableWindow : undefined
+ const dependencyWindowKey = availableWindow?.key ?? resource?.windowKey
+ const dependencyWindow = dependencyWindowKey && messageWindowIdentity(dependencyWindowKey)
+ ? client.getQueryData<MessageWindowData>(dependencyWindowKey) : undefined
+ const dependencyIds = dependencyWindow && Array.isArray(dependencyWindow.pages) && dependencyWindow.pages.every(page => Array.isArray(page?.messages) && page.messages.every(message => typeof message?.id === "string" && message.id))
+ ? dependencyWindow.pages.flatMap(page => page.messages.map(message => message.id)) : canonical?.type === "forum" ? forumMessageIds : undefined
+ const retainedBodiesReady = dependencyIds === undefined || dependencyIds.every(id => getCommunityDbRegistry(client)?.collections.messages.get(id)?.channelId === channelId)
const cachedData = cachedWindow ? client.getQueryData<{ pages: Array<{ messages?: unknown[]; threads?: unknown[] }> }>(cachedWindow.key) : undefined
const rawWindowExists = canonical?.type === "forum" && !anchorMessageId ? client.getQueryData(communityKeys.forumFeed(channelId, tag)) !== undefined
: client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages(channelId) }).some(query => {
const identity = messageWindowIdentity(query.queryKey)
return !!identity && identity.tag === tag && identity.initial.mode !== "since" && query.state.data !== undefined
})
+ useEffect(() => {
+ if (presented && enabled && qualified && rawWindowExists && retainedProfiles.isReady && !retainedProfiles.isError && retainedBodiesReady && !availableWindow && query.isSuccess && !query.isFetching) {
+ void refetch({ cancelRefetch: false })
+ }
+ }, [presented, enabled, qualified, rawWindowExists, retainedProfiles.isReady, retainedProfiles.isError, retainedBodiesReady, availableWindow, query.isSuccess, query.isFetching, refetch])
+ const windowReady = qualified && currentPointer !== undefined && cachedWindow !== undefined
const cacheWindow = !cachedWindow ? rawWindowExists ? "incomplete" : "missing" : cachedData?.pages.some(page => (page.messages ?? page.threads ?? []).length > 0) ? "ready" : "empty"
const targetCoverage = scope && findConversationEntryWindow(client, baseInput, resource ?? scope, currentPointer) ? "covered" : "uncovered"
const entryStatus = resource ? "current" : client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries(channelId) }).some(candidate => candidate.state.data !== undefined) ? "stale" : "missing"
@@ -132,7 +178,7 @@ export function useConversationResource(target: ConversationEntryTarget | null,
emitTelemetry("conversation.cache", { ...actionAttributes(action), cache_consumer: consumer, cache_reason: assessment.reason,
cache_window: cacheWindow, entry_status: entryStatus, target_coverage: targetCoverage, eligibility: scopeAvailable ? "eligible" : "rejected" })
}, [active, assessment.reason, cacheWindow, channelId, consumer, enabled, entryStatus, intent, scopeAvailable, serverId, targetCoverage, telemetryOwner])
- return { client, cachedResource, scope: readableScope, currentPointer, input: anchorMissing && landing.position ? baseInput : input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,
+ return { client, cachedResource, scope: readableScope, currentPointer, windowReady, displayWindow: cachedWindow, input: anchorMissing && landing.position ? baseInput : input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,
localPosition: anchorMissing ? null : landing.position,
denied: serverRevoked || revoked && (!verification.needed || generation !== verification.generation) || isConversationAccessError(query.error) && Number((query.error as { status?: unknown } | null)?.status) !== 401, anchorMissing,
verificationError: (!qualified && anchorMissing ? fallback.error : query.error)?.name === "AbortError" ? null : !qualified && anchorMissing ? fallback.error : query.error,
@@ -156,7 +202,7 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {
? current : { path: expectedPath, intent: incomingIntent })
}, [active, expectedPath, incomingIntent, resuming])
const intent = (active && !resuming) || retainedIntent.path !== expectedPath ? incomingIntent : retainedIntent.intent
- const { client, cachedResource, scope, currentPointer, input, options: entryOptions, query, canonical, resource, canRead, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true, "messages")
+ const { client, cachedResource, scope, currentPointer, input, options: entryOptions, query, canonical, resource, canRead, windowReady, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true, "messages")
const canonicalInput = useMemo(() => localPosition ? { ...input, anchorMessageId: null } : input, [input, localPosition])
const entry = useMemo(() => {
const pointer = scope ? currentConversationReadState(client, input.channelId) : undefined
@@ -209,7 +255,7 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {
const activeQuery = needsCanonicalWindow ? canonicalQuery : query
const refetch = activeQuery.refetch
const retry = useCallback(() => refetch({ cancelRefetch: false }), [refetch])
- return { ...activeQuery, intent, resource, scope, canonical, canRead, window, snapshot, targetCovered, revoked, denied, anchorMissing,
+ return { ...activeQuery, intent, resource, scope, canonical, canRead, windowReady, window, snapshot, targetCovered, revoked, denied, anchorMissing,
initialPositionPending: !targetCovered,
initialPositionMessageId: targetCovered && localPosition && snapshot && snapshot.lastReadSeq < localPosition.seq ? localPosition.messageId : null,
isPending: !!target && !window && !denied && !anchorMissing && !activeQuery.isError && activeQuery.errorUpdatedAt === 0,
diff --git a/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts b/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts
index 213b8e59e..de9d8edf5 100644
--- a/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts
+++ b/src/web/src/hooks/community/use-dm-message-sender.dom.test.ts
@@ -1,3 +1,5 @@
+import { profileResourceFixture, messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { canonicalMessageReader } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -25,7 +27,7 @@ beforeEach(() => {
const scope = { kind: "dm" as const, id: "dm_1" }
const author = { id: "u_me", name: "Me", avatar: "M" }
function posted(id = "server_1", seq = 7, content = "hello") {
- return { message: { id, seq, content, type: "chat", createdAt: "2026-08-07T10:00:00.000Z", authorId: author.id, authorName: author.name, authorImage: null, authorAvatarVersion: 0, embeds: [] } }
+ return { profiles: messageProfilesFixture([messageResourceFixture({ id, seq, content, channelId: scope.id, clientNonce: "fresh_nonce", createdAt: "2026-08-07T10:00:00.000Z", authorId: author.id, authorName: author.name, authorAvatar: null, authorAvatarVersion: 0, embeds: [] })]), message: messageResourceFixture({ id, seq, content, channelId: scope.id, clientNonce: "fresh_nonce", createdAt: "2026-08-07T10:00:00.000Z", authorId: author.id, authorName: author.name, authorAvatar: null, authorAvatarVersion: 0, embeds: [] }) }
}
async function setup() {
const owner = await createCommunityQueryOwner("u_me")
@@ -56,15 +58,14 @@ describe("Native DM sender", () => {
let resolve!: (value: ReturnType<typeof posted>) => void
mocks.post.mockReturnValueOnce(new Promise((done) => { resolve = done }))
const owner = await setup()
- const receipt = owner.accept({ content: "@Peer\nhello", replyTo: { id: "prior", authorName: "Peer", text: "quoted" } })
- expect(owner.overlay().outboxByNonce.get("fresh_nonce")?.message).toMatchObject({ authorId: "u_me", authorName: "Me", content: "@Peer\nhello", replyTo: { id: "prior", authorName: "Peer", text: "quoted" } })
+ const receipt = owner.accept({ content: "@Peer\nhello", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "quoted" } })
+ expect(owner.overlay().outboxByNonce.get("fresh_nonce")?.message).toMatchObject({ authorId: "u_me", authorName: "Me", content: "@Peer\nhello", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "quoted" } })
await waitFor(() => expect(mocks.post).toHaveBeenCalledExactlyOnceWith({ content: "@Peer\nhello", replyToId: "prior", nonce: "fresh_nonce" }))
- resolve({ message: Object.assign({}, posted().message, { channelId: scope.id, type: "default", replyToId: "prior",
- authorEmail: "[email protected]", storageMetadata: { legacy: true } }) })
+ resolve({ ...posted(), profiles: [...posted().profiles, profileResourceFixture({ id: "peer", name: "Peer" })], message: { ...posted().message, replyToId: "prior" } })
expect(await owner.settle(receipt)).toMatchObject({ ok: true, message: { id: "server_1", seq: 7 } })
const canonical = owner.registry.collections.messages.get("server_1")
expect(canonical).toMatchObject({ id: "server_1", seq: 7, channelId: scope.id, clientNonce: "fresh_nonce",
- type: "chat", content: "hello", replyToId: "prior", replyTo: { id: "prior", authorName: "Peer", text: "quoted" } })
+ type: "chat", content: "hello", replyToId: "prior", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "quoted" } })
expect(canonical).not.toHaveProperty("authorEmail")
expect(canonical).not.toHaveProperty("storageMetadata")
const { awaitCommittedInvite } = await import("@/components/community/social/invite-dialog")
@@ -73,6 +74,14 @@ describe("Native DM sender", () => {
expect(onCommitted).toHaveBeenCalledOnce()
})
+ it.each([{ type: "default" }, { authorEmail: "[email protected]" }, { attachments: undefined }])("rejects raw obsolete or incomplete POST resource %j", async (fields) => {
+ mocks.post.mockResolvedValueOnce({ message: Object.assign({}, posted().message, fields) })
+ const owner = await setup()
+ expect(await owner.settle(owner.accept({ content: "hello" }))).toMatchObject({ ok: false, error: expect.any(Error) })
+ expect(owner.registry.collections.messages.has("server_1")).toBe(false)
+ expect(owner.overlay().outboxByNonce.get("fresh_nonce")?.status).toBe("failed")
+ })
+
it("normalizes upload failure, marks the intent failed and never POSTs", async () => {
mocks.upload.mockRejectedValueOnce(new Error("upload failed"))
const owner = await setup(), file = new File(["x"], "x.txt", { type: "text/plain" })
@@ -115,7 +124,7 @@ describe("Native DM sender", () => {
it("bounds the optimistic reply and preserves its exact preview through retry", async () => {
mocks.post.mockRejectedValueOnce(new Error("offline")).mockRejectedValueOnce(new Error("still offline"))
const owner = await setup()
- const receipt = owner.accept({ content: "replying", replyTo: { id: "prior", authorName: "Peer", text: "x".repeat(MESSAGE_PREVIEW_LENGTH + 1) } })
+ const receipt = owner.accept({ content: "replying", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "x".repeat(MESSAGE_PREVIEW_LENGTH + 1) } })
expect(await owner.settle(receipt)).toEqual({ ok: false, error: expect.any(Error) })
const expected = `${"x".repeat(MESSAGE_PREVIEW_LENGTH - 1)}…`
expect(owner.overlay().outboxByNonce.get("fresh_nonce")?.message).toMatchObject({ content: "replying", replyTo: { text: expected } })
@@ -128,7 +137,7 @@ describe("Native DM sender", () => {
mocks.upload.mockResolvedValueOnce({ id: "att_x", filename: "x.txt", contentType: "text/plain", size: 1 })
mocks.post.mockResolvedValueOnce(posted("server_file", 9, ""))
const owner = await setup(), file = new File(["x"], "x.txt", { type: "text/plain" })
- const receipt = owner.accept({ content: "", replyTo: { id: "prior", authorName: "Peer Name", text: "quoted" }, attachments: [{ file, previewObjectUrl: "blob:x" }] })
+ const receipt = owner.accept({ content: "", replyTo: { id: "prior", authorId: "peer", authorName: "Peer Name", text: "quoted" }, attachments: [{ file, previewObjectUrl: "blob:x" }] })
expect(await owner.settle(receipt)).toMatchObject({ ok: true, message: { id: "server_file", seq: 9 } })
expect(materializeMessageStream([], owner.overlay(), canonicalMessageReader(owner.client)).find(({ id }) => id === "server_file")?.content).toBe("")
expect(mocks.post).toHaveBeenCalledExactlyOnceWith({ content: "", replyToId: "prior", attachments: ["att_x"], nonce: "fresh_nonce" })
@@ -153,7 +162,7 @@ describe("Native DM sender", () => {
const receipt = owner.accept({ content: "out of view" })
expect(await owner.settle(receipt)).toMatchObject({ ok: true, message: { id: "server_1", seq: 11 } })
expect(materializeMessageStream([], owner.overlay(), canonicalMessageReader(owner.client)).map(({ id }) => id)).toEqual(["server_1"])
- const base = [{ id: "server_1", seq: 11, clientNonce: "fresh_nonce", type: "chat" as const, authorId: "u_me", authorName: "Me", content: "out of view" }]
+ const base = [posted("server_1", 11, "out of view").message]
act(() => owner.runtime.messageStream.actions.dispatch(scope, { type: "baseChanged", messages: base }))
expect(materializeMessageStream(base, owner.overlay(), canonicalMessageReader(owner.client)).map(({ id }) => id)).toEqual(["server_1"])
})
@@ -161,7 +170,7 @@ describe("Native DM sender", () => {
describe("confirmed native DM receipt", () => {
- const confirmed = { id: "server_confirmed", seq: 17, type: "chat" as const, content: "hello", authorId: "u_me", clientNonce: "fresh_nonce" }
+ const confirmed = messageResourceFixture({ id: "server_confirmed", channelId: scope.id, seq: 17, content: "hello", authorId: "u_me", clientNonce: "fresh_nonce" })
it.each(["ordinary", 0, 500, 503])("returns the canonical receipt after a late %s while Native POST stays rejected", async (status) => {
const owner = await setup()
mocks.post.mockImplementationOnce(async () => { ingestMessages(owner.registry, scope.id, [confirmed]); throw status === "ordinary" ? new Error("late failure") : new ApiError("late failure", Number(status)) })
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 eb7b0e631..371fca708 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
@@ -11,6 +11,9 @@ import { channelMetadataOptions } from "./channel-metadata"
import { startChannelRouteVerification } from "./channel-route-verification"
import { useChannelMetadata } from "./use-channel-metadata"
+import { CommunityApiError } from "@/lib/errors"
+import { CommunityReadErrorSchema, BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+
const apiFetch = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
@@ -147,3 +150,44 @@ describe("DM route uses the shared Channel metadata owner", () => {
client.clear()
})
})
+
+it.each(["blocked","not_allowed","not_found"] as const)("projects the current %s cause after the original query error disappears",async code=>{
+ const {client,registry,wrapper}=await fixture()
+ apiFetch.mockRejectedValue(new CommunityApiError(CommunityReadErrorSchema.parse({contractVersion:BUSINESS_SCHEMA_VERSION,error:{code,message:code,retryable:false}}).error,code==="not_found"?404:403))
+ const route=renderHook(()=>useChannelMetadata(null,dm.id),{wrapper})
+ try {
+ await waitFor(()=>expect(route.result.current.status).toBe("denied"))
+ expect(route.result.current).toMatchObject({denialCode:code,revoked:true,canRead:false,identityKnown:false})
+ expect(route.result.current.error).toBeNull()
+ expect(registry.collections.messages.size).toBe(0)
+ apiFetch.mockResolvedValue(metadata)
+ await act(async()=>{await route.result.current.retry()})
+ await waitFor(()=>expect(route.result.current.status).toBe("readable"))
+ expect(route.result.current.denialCode).toBeUndefined()
+ expect(registry.runtime.ws.get().channelAccessScopes.get(dm.id)).not.toHaveProperty("denialCode")
+ } finally {route.unmount();client.clear()}
+})
+
+it("keeps the actual WS block cause through directory eviction and rejects the older held HTTP entry",async()=>{
+ const {client,registry,wrapper}=await fixture()
+ const {ingestDms,applyCommunityDmBlockAccess}=await import("@/lib/community-db/sync")
+ const {dmListRowFixture}=await import("@/test/community-resource-fixtures")
+ ingestDms(registry,{conversations:[dmListRowFixture({id:dm.id,userId:"peer",name:"Peer",discriminator:"0042",avatar:null,avatarVersion:0,status:"offline",preview:"private"})]})
+ const pending=deferred<typeof metadata>()
+ apiFetch.mockReturnValue(pending.promise)
+ const route=renderHook(()=>useChannelMetadata(null,dm.id),{wrapper})
+ try {
+ await waitFor(()=>expect(apiFetch).toHaveBeenCalledOnce())
+ await act(async()=>{applyCommunityDmBlockAccess(registry,"peer",true)})
+ await waitFor(()=>expect(route.result.current).toMatchObject({status:"denied",denialCode:"blocked",canRead:false}))
+ const generation=registry.runtime.ws.get().channelAccessScopes.get(dm.id)!.generation
+ await act(async()=>{ingestDms(registry,{conversations:[]})})
+ expect(registry.collections.channels.has(dm.id)).toBe(false)
+ expect(registry.runtime.ws.get().channelAccessScopes.get(dm.id)).toMatchObject({generation,revoked:true,denialCode:"blocked"})
+ await act(async()=>{pending.resolve(metadata)})
+ expect(route.result.current).toMatchObject({status:"denied",denialCode:"blocked",canRead:false})
+ expect(registry.collections.channels.has(dm.id)).toBe(false)
+ expect(registry.collections.messages.size).toBe(0)
+ expect(client.getQueryData(channelMetadataOptions(client,null,dm.id).queryKey)).toBeUndefined()
+ } finally {route.unmount();await client.cancelQueries();client.clear()}
+})
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 2bb37c12b..ab3c5714e 100644
--- a/src/web/src/hooks/community/use-dms.dom.test.ts
+++ b/src/web/src/hooks/community/use-dms.dom.test.ts
@@ -1,3 +1,4 @@
+import { dmListRowFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { act, render } from "@/test/react-dom-harness"
@@ -7,6 +8,7 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { dmsProjectedQueryFn } from "./use-dms"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
+import type { CommunityDmsRead } from "@alook/shared"
import type { DM } from "@/lib/community/models/people"
import { inboxDmRowTarget } from "./inbox-read-reservation"
import {
@@ -16,8 +18,9 @@ import {
} from "@/lib/community-db/collections"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { ingestDms } from "@/lib/community-db/sync"
+import { beginCommunityProfileSeed } from "@/lib/community/profile-seed"
-function seedDms(client: QueryClient, data: { conversations: DM[] }) {
+function seedDms(client: QueryClient, data: CommunityDmsRead) {
ingestDms(getCommunityDbRegistry(client)!, data)
client.setQueryData(communityKeys.dms(), { ids: data.conversations.map((dm) => dm.id) })
}
@@ -33,16 +36,12 @@ function deferred<T>() {
return { promise, resolve }
}
-function dm(id: string): DM {
- return {
- id,
- userId: `${id}-peer`,
- name: id,
- discriminator: "0001",
- avatar: id,
- status: "offline",
- preview: "",
- }
+function dmFacts(fields: { id: string; userId: string; [field: string]: unknown }) {
+ const full = dmListRowFixture(fields as DM, "viewer")
+ return { ...full, profile: { ...full.profile, avatar: typeof fields.avatar === "string" ? fields.avatar : null } }
+}
+function dm(id: string) {
+ return dmFacts({ id, userId: id + "-peer", name: id, discriminator: "0001", avatar: id, status: "offline", preview: "" })
}
beforeEach(() => {
@@ -53,9 +52,9 @@ beforeEach(() => {
describe("useDms / dmsQueryFn", () => {
it("returns the DM conversations from GET /api/community/users/me/dms", async () => {
- const conversations = [
+ const conversations = ([
{ id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0000", avatar: "A", status: "offline", preview: "" },
- ]
+ ]).map(dmFacts)
apiFetchMock.mockResolvedValueOnce({ conversations })
const { client: qc, registry } = await createCommunityQueryOwner()
const data = await qc.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(qc) })
@@ -128,7 +127,7 @@ describe("useDms / dmsQueryFn", () => {
})
it("reuses a projected DM across layout mounts without refetching the canonical list", async () => {
- const conversations = [{
+ const conversations = ([{
id: "dm_projected",
userId: "u_1",
name: "Alice",
@@ -136,7 +135,7 @@ describe("useDms / dmsQueryFn", () => {
avatar: "a",
status: "offline",
preview: "projected from inbox",
- }]
+ }]).map(dmFacts)
apiFetchMock.mockResolvedValue({ conversations })
const { useDms } = await import("./use-dms")
const { client: qc } = await createCommunityQueryOwner()
@@ -158,7 +157,7 @@ describe("useDms / dmsQueryFn", () => {
})
it("ignores legacy transport conversations without a canonical provider", async () => {
- const conversations = [dm("dm-providerless")]
+ const conversations = ([dm("dm-providerless")]).map(dmFacts)
const { useDms } = await import("./use-dms")
const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } })
qc.setQueryData(communityKeys.dms(), { conversations })
@@ -218,7 +217,7 @@ describe("useDms / dmsQueryFn", () => {
preview: "hello",
}],
}
- seedDms(qc, raw)
+ seedDms(qc, { conversations: raw.conversations.map(dmFacts) })
createCommunityDbRegistry(qc, "viewer").runtime.ws.actions.setPresence("u_1", "online")
let projected!: ReturnType<typeof useDms>
function Probe() {
@@ -256,7 +255,7 @@ describe("useDms / dmsQueryFn", () => {
avatarVersion: 7,
status: "online",
preview: "cached preview",
- }],
+ }].map(dmFacts),
})
let projected!: ReturnType<typeof useDms>
function Probe() {
@@ -281,7 +280,7 @@ describe("useDms / dmsQueryFn", () => {
})
it("keeps legacy unread flags subordinate to canonical attention", async () => {
- const conversations = [
+ const conversations = ([
{
id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0001",
avatar: "a", avatarVersion: 1, status: "offline", preview: "one", unread: false,
@@ -293,9 +292,9 @@ describe("useDms / dmsQueryFn", () => {
},
{
id: "dm_legacy", userId: "u_3", name: "Carol", discriminator: "0003",
- avatar: "c", avatarVersion: 1, status: "offline", preview: "three", unread: true,
+ avatar: "c", avatarVersion: 1, status: "offline", preview: "three", unread: true, lastUnreadSeq: 7,
},
- ] as DM[]
+ ]).map(dmFacts)
apiFetchMock.mockResolvedValue({ conversations })
const { useDms } = await import("./use-dms")
const { client: qc } = await createCommunityQueryOwner()
@@ -320,7 +319,7 @@ describe("useDms / dmsQueryFn", () => {
})
it("does not let a legacy Inbox reservation mutate canonical DM attention", async () => {
- const conversations = [
+ const conversations = ([
{
id: "dm_1", userId: "u_1", name: "Alice", discriminator: "0001",
avatar: "a", avatarVersion: 1, status: "offline", preview: "one",
@@ -331,7 +330,7 @@ describe("useDms / dmsQueryFn", () => {
avatar: "b", avatarVersion: 1, status: "offline", preview: "two",
unread: true, lastUnreadSeq: 3,
},
- ] as DM[]
+ ]).map(dmFacts)
const inboxDm = {
channelId: "dm_1",
otherUserId: "u_1",
@@ -402,3 +401,36 @@ describe("useDms / dmsQueryFn", () => {
await act(async () => renderer.unmount())
})
})
+
+
+describe("complete DM read prepublication refusal", () => {
+ it.each(["missing-core", "wrong-peer", "wrong-channel", "wrong-viewer", "duplicate-identity", "missing-unread-seq", "foreign-parent", "foreign-category", "foreign-opener"])("keeps every canonical collection unchanged for a later %s row", async defect => {
+ const { client, registry } = await createCommunityQueryOwner("viewer");
+ const initial = [dm("first"), dm("second")];
+ await act(async () => { ingestDms(registry, { conversations: initial }); });
+ const snapshot = () => Object.fromEntries(Object.entries(registry.collections).map(([name, collection]) => [name, JSON.parse(JSON.stringify([...collection.base.values()]))]));
+ const before = snapshot();
+ const beforeRevision = beginCommunityProfileSeed(registry).revision;
+ const first = structuredClone(initial[0]!);
+ const second = structuredClone(initial[1]!);
+ first.profile.name = "Must not publish first";
+ second.profile.name = "Must not publish second";
+ if (defect === "missing-core") delete (second.profile as Partial<typeof second.profile>).avatarVersion;
+ if (defect === "wrong-peer") second.profile.id = first.profile.id;
+ if (defect === "wrong-channel") second.channel.id = "foreign-channel";
+ if (defect === "wrong-viewer") second.memberships[0]!.userId = "foreign-viewer";
+ if (defect === "duplicate-identity") Object.assign(second, { name: "Second identity source" });
+ if (defect === "foreign-parent") second.channel.parentChannelId = "foreign"
+ if (defect === "foreign-category") second.channel.categoryId = "foreign"
+ if (defect === "foreign-opener") second.channel.parentMessageId = "foreign"
+ if (defect === "missing-unread-seq") Object.assign(second, { unread: true, lastUnreadSeq: undefined });
+ apiFetchMock.mockResolvedValueOnce({ conversations: [first, second] });
+
+ await expect(client.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(client) })).rejects.toThrow();
+
+ expect(snapshot()).toEqual(before);
+ expect(beginCommunityProfileSeed(registry).revision).toBe(beforeRevision);
+ expect(registry.collections.profiles.get(first.profile.id)?.name).not.toBe("Must not publish first");
+ expect(registry.collections.profiles.get(initial[1]!.profile.id)?.name).not.toBe("Must not publish second");
+ });
+});
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index 9c17eb85e..c1410cd6e 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -10,10 +10,12 @@ import {
type UseQueryResult,
} from "@tanstack/react-query"
import {
- apiFetchProfiles,
+ loadAndSeedProfiles,
communityUserProfilePatch,
} from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
+import { parseCommunityDmsRead, type CommunityDmsRead } from "@alook/shared"
+import { apiFetch } from "@/lib/api/client"
import type { DM } from "@/lib/community/models/people"
import { useMemo } from "react"
import {
@@ -36,26 +38,32 @@ import { sortDmsByActivity } from "@/lib/community/dm-order"
* The WS handler invalidates this key on `community:message.create` events
* (a DM is a channel now) so previews and unread flags stay live.
*/
-export type DmsResponse = { conversations: DM[] }
+export type DmsResponse = CommunityDmsRead
// Frozen empty fallback — see `use-servers.ts` for the rationale.
const EMPTY_DMS: readonly DM[] = Object.freeze([])
-const loadDms = (
- context: QueryFunctionContext,
-) =>
- apiFetchProfiles<DmsResponse>(
- "/api/community/users/me/dms",
- (data) => data.conversations.map((dm) => communityUserProfilePatch(dm.userId, dm, { legacyPresentation: true })),
- context.signal ? { signal: context.signal } : undefined, getCommunityDbRegistry(context.client),
+const loadDms = (context: QueryFunctionContext, token: ReturnType<typeof captureCommunityLiveSnapshotToken>) => {
+ const registry = getCommunityDbRegistry(context.client)
+ return loadAndSeedProfiles(
+ async origin => {
+ const data = await apiFetch<unknown>("/api/community/users/me/dms", { ...origin, signal: context.signal })
+ if (!registry?.accountId) throw new DOMException("Missing DM viewer", "AbortError")
+ return parseCommunityDmsRead(data, registry.accountId)
+ },
+ data => data.conversations.map(dm => communityUserProfilePatch(dm.profile.id, dm.profile)),
+ registry,
+ context.signal,
+ token,
)
+}
export const dmsProjectedQueryFn = (
queryClient: QueryClient,
) => async (context: QueryFunctionContext) => {
const publicationToken = captureCommunityLiveSnapshotToken(queryClient)
try {
- const data = await loadDms(context)
+ const data = await loadDms(context, publicationToken)
assertCommunityLiveSnapshotTokenCurrent(queryClient, publicationToken, context.signal)
publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "dms", data },
diff --git a/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts
index 2b8a1f725..cf5c0a7f0 100644
--- a/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts
@@ -1,3 +1,4 @@
+import { forumFeedScenarioFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { createElement, type PropsWithChildren } from "react"
import { type QueryClient } from "@tanstack/react-query"
@@ -40,14 +41,14 @@ describe("useForumFeed", () => {
client.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } })
const target = { channelId: "forum_one", serverId: "server_one", tag }
client.setQueryData(conversationEntryOptions(client, target).queryKey, publishConversationEntry(client, target, forumConversationEntryFixture("forum_one", "server_one", true), { token: captureCommunityLiveSnapshotToken(client, "forum_one") }))
- const page = (ids: string[]): ForumFeedTransportPage => ({
+ const page = (ids: string[]): ForumFeedTransportPage => (forumFeedScenarioFixture("forum_one", {
serverId: "server_one", parentType: "forum", hasMore: false,
threads: ids.map((id) => ({ id, name: id, creatorId: "author", messageCount: 1, parentMessageId: `opener_${id}`, createdAt: "2026-10-26T00:00:00Z", activityAt: "2026-10-26T00:00:00Z", lastMessageAt: null })),
included: { ...emptyIncluded,
parentMessages: ids.map((id) => ({ id: `opener_${id}`, channelId: "forum_one", seq: 1, content: id, authorId: "author", authorName: "Author", authorImage: null, authorAvatarVersion: 0 })),
tags: ids.map((id) => ({ messageId: `opener_${id}`, tag: "bug" })),
},
- })
+ }))
client.removeQueries({ queryKey: communityKeys.threads("forum_one") })
let release!: (value: ForumFeedTransportPage) => void
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve })).mockResolvedValue(page(["old", "new"]))
@@ -81,7 +82,7 @@ describe("useForumFeed", () => {
runCommunityWsProjectionTransaction(client, (projection) => handleChildChannelCreate({ type: "community:channel.child_create", parentChannelId: "forum_one", channel: { id: "new", name: "new", type: "thread", createdAt: "2026-10-26T00:00:00Z" }, parentMessageId: "opener_new" }, { queryClient: client, projection }))
rendered.unmount()
client.removeQueries({ queryKey: communityKeys.threads("forum_one") })
- release({ serverId: "server_one", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false })
+ release(forumFeedScenarioFixture("forum_one", { serverId: "server_one", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false }))
})
expect(apiFetchMock).toHaveBeenCalledTimes(1)
expect(client.getQueryCache().findAll({ queryKey: communityKeys.threads("forum_one") })).toEqual([])
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 04b3b256e..5eb899ce2 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
@@ -1,3 +1,4 @@
+import { messageResourceFixture, forumFeedScenarioFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { createElement, type PropsWithChildren } from "react"
import { type QueryClient } from "@tanstack/react-query"
@@ -65,12 +66,12 @@ describe("forumFeedPageQueryFn", () => {
else controller.abort(new DOMException("Retired", "AbortError"))
await rejected
expect(apiFetchMock.mock.calls[0]![1].signal.aborted).toBe(true)
- release({ serverId: "server_1", parentType: "forum", threads: [], included: { ...emptyIncluded, parentMessages: [{ id: "late-opener", channelId: "forum_1", seq: 1, content: "late", authorId: "late-author", authorName: "Late", authorImage: null, authorAvatarVersion: 1 }] }, hasMore: false })
+ release(forumFeedScenarioFixture("forum_1", { serverId: "server_1", parentType: "forum", threads: [], included: { ...emptyIncluded, parentMessages: [{ id: "late-opener", channelId: "forum_1", seq: 1, content: "late", authorId: "late-author", authorName: "Late", authorImage: null, authorAvatarVersion: 1 }] }, hasMore: false }))
await Promise.resolve()
await Promise.resolve()
expect(getCanonicalCommunityMessages(client)).toEqual([])
expect(getCommunityDbRegistry(client)!.collections.profiles.get("late-author")).toBeUndefined()
- apiFetchMock.mockResolvedValueOnce({ serverId: "server_1", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(forumFeedScenarioFixture("forum_1", { serverId: "server_1", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false }))
await expect(forumFeedPageQueryFn("forum_1", null, client)({ pageParam: null })).resolves.toMatchObject({ threads: [], hasMore: false })
} finally { vi.useRealTimers() }
})
@@ -97,7 +98,7 @@ describe("forumFeedPageQueryFn", () => {
})
it("requests the canonical created-order collection with includes, tag, and cursor", async () => {
- apiFetchMock.mockResolvedValue({ serverId: "server_1", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false })
+ apiFetchMock.mockResolvedValue(forumFeedScenarioFixture("forum_one", { serverId: "server_1", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false }))
await forumFeedPageQueryFn("forum_one", "bug", client)({ pageParam: "opaque cursor" })
const url = apiFetchMock.mock.calls[0]![0] as string
@@ -110,7 +111,7 @@ describe("forumFeedPageQueryFn", () => {
})
it("uses the archive tag as its own feed query", async () => {
- apiFetchMock.mockResolvedValue({ serverId: "server_1", parentType: "forum", threads: [{ id: "archived-post", name: "Post", creatorId: "author", messageCount: 1, parentMessageId: "opener", lastMessageAt: null, createdAt: "2026-10-04T00:00:00Z", activityAt: "2026-10-04T00:00:00Z" }], included: { ...emptyIncluded, tags: [{ messageId: "opener", tag: "archived" }] }, hasMore: false })
+ apiFetchMock.mockResolvedValue(forumFeedScenarioFixture("forum_one", { serverId: "server_1", parentType: "forum", threads: [{ id: "archived-post", name: "Post", creatorId: "author", messageCount: 1, parentMessageId: "opener", lastMessageAt: null, createdAt: "2026-10-04T00:00:00Z", activityAt: "2026-10-04T00:00:00Z" }], included: { ...emptyIncluded, tags: [{ messageId: "opener", tag: "archived" }] }, hasMore: false }))
await forumFeedPageQueryFn("forum_one", "archived", client)({ pageParam: null })
const url = apiFetchMock.mock.calls[0]![0] as string
@@ -119,7 +120,7 @@ describe("forumFeedPageQueryFn", () => {
})
it("passes the query abort signal through to the request", async () => {
- apiFetchMock.mockResolvedValue({ serverId: "server_1", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false })
+ apiFetchMock.mockResolvedValue(forumFeedScenarioFixture("forum_one", { serverId: "server_1", parentType: "forum", threads: [], included: emptyIncluded, hasMore: false }))
const controller = new AbortController()
await forumFeedPageQueryFn("forum_one", null, client)({
@@ -133,8 +134,18 @@ describe("forumFeedPageQueryFn", () => {
)
})
+ it("publishes included full profiles for fresh opener and first-message reply authors without participants", async () => {
+ const feed = forumConversationEntryFixture("forum_one", "server_1").forumFeed!
+ const profiles = ["opener-author", "first-author", "reply-author"].map(id => ({ id, name: id, discriminator: "0042", avatar: null, avatarVersion: 1 }))
+ const messages = [messageResourceFixture({ id: "m1", channelId: "forum_one", authorId: "opener-author" }),
+ messageResourceFixture({ id: "first-t1", channelId: "t1", authorId: "first-author", replyToId: "previous", replyTo: { id: "previous", authorId: "reply-author", authorName: "reply-author", text: "Earlier" } })]
+ apiFetchMock.mockResolvedValue({ ...feed, included: { ...feed.included, profiles, messages } })
+ await forumFeedPageQueryFn("forum_one", null, client)({ pageParam: null })
+ for (const profile of profiles) expect(getCommunityDbRegistry(client)!.collections.profiles.get(profile.id)).toMatchObject(profile)
+ })
+
it("seeds opener and participant profiles while returning only the ID window", async () => {
- const page = {
+ const page = forumFeedScenarioFixture("forum_one", {
serverId: "server_1", parentType: "forum",
threads: [{ id: "thread_1", name: "post", creatorId: "author_1", messageCount: 1, parentMessageId: "m1", lastMessageAt: null, createdAt: "", activityAt: "" }],
included: {
@@ -156,7 +167,7 @@ describe("forumFeedPageQueryFn", () => {
],
},
hasMore: false,
- }
+ })
apiFetchMock.mockResolvedValue(page)
const result = await forumFeedPageQueryFn("forum_one", null, client)({ pageParam: null })
@@ -172,11 +183,11 @@ describe("forumFeedPageQueryFn", () => {
describe("mapForumFeedPages", () => {
it("retains full forum preview, empty activity and zero opener sequence", async () => {
const preview = "preview".repeat(30)
- const result = await projectPages([{
+ const result = await projectPages([forumFeedScenarioFixture("forum_1", {
serverId: "server_1", parentType: "forum", hasMore: false,
- threads: [{ id: "post", name: "Fallback", creatorId: "u1", messageCount: null, parentMessageId: "opener", lastMessageAt: null, createdAt: "created", activityAt: "created" }],
+ threads: [{ id: "post", name: "Fallback", creatorId: "u1", messageCount: 0, parentMessageId: "opener", lastMessageAt: null, createdAt: "created", activityAt: "created" }],
included: { ...emptyIncluded, parentMessages: [{ id: "opener", channelId: "forum_1", seq: 0, content: " ", authorId: "u1", authorName: "A", authorImage: null, authorAvatarVersion: 0 }], firstMessages: [{ channelId: "post", content: preview }] },
- }])
+ })])
expect(result).toHaveLength(1)
expect(result[0]).toMatchObject({ name: "Fallback", messageCount: 0, lastMessageAt: "", parent: { authorId: "u1", authorName: "A", text: preview }, parentSeq: 0, openerMessageId: "opener", preview })
const updatedPreview = "updated preview".repeat(30)
@@ -187,18 +198,20 @@ describe("mapForumFeedPages", () => {
})
it("keeps one operation baseline across pages and excludes duplicate profile publications", async () => {
const registry = getCommunityDbRegistry(client)!
- const page = (id: string, name: string, more: boolean): ForumFeedTransportPage => ({
+ const page = (id: string, name: string, more: boolean): ForumFeedTransportPage => (forumFeedScenarioFixture("forum_1", {
serverId: "server_1", parentType: "forum", hasMore: more, ...(more ? { nextCursor: "next" } : {}),
threads: [{ id, name: id, creatorId: "author", messageCount: 1, parentMessageId: `opener_${id}`, createdAt: "2026-08-08T00:00:00.000Z", lastMessageAt: null, activityAt: "2026-08-08T00:00:00.000Z" }],
included: { parentMessages: [{ id: `opener_${id}`, channelId: "forum_1", seq: 1, content: id, authorId: "author", authorName: name, authorImage: null, authorAvatarVersion: 0 }], firstMessages: [], tags: [], participants: [{ channelId: id, userId: "author", userName: name, userImage: null, userAvatarVersion: 0 }] },
- })
+ }))
let release!: (value: ForumFeedTransportPage) => void
apiFetchMock.mockResolvedValueOnce(page("first", "Initial", true)).mockReturnValueOnce(new Promise((resolve) => { release = resolve }))
const request = client.infiniteQuery({ queryKey: communityKeys.forumFeed("forum_1", null), queryFn: forumFeedPageQueryFn("forum_1", null, client), initialPageParam: null as string | null, getNextPageParam: (last) => last.hasMore ? last.nextCursor : undefined, pages: 2 })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
writeCommunityProfilePatches([{ id: "author", identityAbout: { name: "Newer WS" } }], registry, { event: true })
const next = page("second", "Old later page", false), duplicate = page("first", "Old duplicate", false)
- release({ ...next, threads: [...next.threads, ...duplicate.threads], included: { ...next.included, parentMessages: [...next.included.parentMessages, ...duplicate.included.parentMessages], participants: [...next.included.participants, ...duplicate.included.participants] } })
+ release({ ...next, threads: [...next.threads, ...duplicate.threads], included: { messages: [...next.included.messages, ...duplicate.included.messages], members: [...next.included.members, ...duplicate.included.members],
+ profiles: [...new Map([...next.included.profiles, ...duplicate.included.profiles].map(profile => [profile.id, profile])).values()],
+ tags: [...next.included.tags, ...duplicate.included.tags], participantCounts: [...next.included.participantCounts, ...duplicate.included.participantCounts] } })
const result = await request
expect(registry.collections.profiles.get("author")?.name).toBe("Newer WS")
expect(result.pages).toHaveLength(2)
@@ -217,7 +230,7 @@ describe("mapForumFeedPages", () => {
activityAt: "2026-08-23T00:00:00.000Z",
})
const data = {
- pages: [{
+ pages: [forumFeedScenarioFixture("forum_1", {
serverId: "server_1",
parentType: "forum",
threads: [thread("delete", "m_delete"), thread("keep", "m_keep")],
@@ -234,7 +247,7 @@ describe("mapForumFeedPages", () => {
],
},
hasMore: false,
- }],
+ })],
pageParams: [null],
}
@@ -249,7 +262,7 @@ describe("mapForumFeedPages", () => {
it("joins included resources, deduplicates pages, and keeps newest-created first", async () => {
const pages: ForumFeedTransportPage[] = [
- {
+ forumFeedScenarioFixture("forum_1", {
serverId: "server_1",
parentType: "forum",
threads: [
@@ -288,8 +301,8 @@ describe("mapForumFeedPages", () => {
},
hasMore: true,
nextCursor: "next",
- },
- {
+ }),
+ forumFeedScenarioFixture("forum_1", {
serverId: "server_1",
parentType: "forum",
threads: [
@@ -309,7 +322,7 @@ describe("mapForumFeedPages", () => {
participants: [{ channelId: "t2", userId: "u3", userName: "Duplicate Bob", userImage: "duplicate.png", userAvatarVersion: 0 }],
},
hasMore: false,
- },
+ }),
]
const result = await projectPages(pages)
@@ -339,7 +352,7 @@ describe("mapForumFeedPages", () => {
})
it("projects a canonical opener without reviving transport message fields", async () => {
- const pages: ForumFeedTransportPage[] = [{
+ const pages: ForumFeedTransportPage[] = [forumFeedScenarioFixture("forum_1", {
serverId: "server_1",
parentType: "forum",
threads: [{
@@ -369,7 +382,7 @@ describe("mapForumFeedPages", () => {
participants: [],
},
hasMore: false,
- }]
+ })]
const canonical = new Map([[
"opener-1",
{
@@ -417,20 +430,20 @@ describe("mapForumFeedPages", () => {
activityAt: "2026-08-17T06:35:00.000Z",
}))
const pages: ForumFeedTransportPage[] = [
- {
+ forumFeedScenarioFixture("forum_1", {
serverId: "server_1",
parentType: "forum",
threads: threads.slice(2),
included: { ...emptyIncluded, parentMessages: threads.slice(2).map((thread) => ({ id: thread.parentMessageId, channelId: "forum_1", seq: 1, content: "", authorId: "creator", authorName: "Creator", authorImage: null, authorAvatarVersion: 0 })) },
hasMore: true, nextCursor: "next",
- },
- {
+ }),
+ forumFeedScenarioFixture("forum_1", {
serverId: "server_1",
parentType: "forum",
threads: threads.slice(0, 2),
included: { ...emptyIncluded, parentMessages: threads.slice(0, 2).map((thread) => ({ id: thread.parentMessageId, channelId: "forum_1", seq: 1, content: "", authorId: "creator", authorName: "Creator", authorImage: null, authorAvatarVersion: 0 })) },
hasMore: false,
- },
+ }),
]
expect((await projectPages(pages)).map((thread) => thread.id)).toEqual(expectedIds)
@@ -442,13 +455,13 @@ describe("useForumFeed", () => {
const queryClient = client
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } })
queryClient.setQueryData(communityKeys.forumFeed("forum_one", null), {
- pages: [{
+ pages: [forumFeedScenarioFixture("forum_1", {
serverId: "server_one",
parentType: "forum",
threads: [],
included: emptyIncluded,
hasMore: false,
- }],
+ })],
pageParams: [null],
})
const target = { channelId: "forum_one", serverId: "server_one" }
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 6812c7982..fec957d90 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -4,7 +4,7 @@ import { useConversationPresentation } from "@/contexts/community/conversation-a
import { useCallback, useEffect, useMemo } from "react"
import { createStore, useAtom, useCreateAtom } from "@tanstack/react-store"
import { useInfiniteQuery, useIsMutating, useQueryClient, type Query } from "@tanstack/react-query"
-import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityLegacyThreadsRead, type CommunityThreadsRead } from "@alook/shared"
+import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityThreadsRead } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"
@@ -14,7 +14,7 @@ import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useCanonicalChannelsById, useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityForumFeed } from "@/lib/community-db/sync"
import { forumTagFromUrl, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"
-import type { ForumThread, Msg } from "@/lib/community/models/message"
+import { messageProfileIds, type ForumThread, type Msg } from "@/lib/community/models/message"
import type { ChannelRow } from "@/lib/community-db/schema"
import { readCommunityProfile } from "@/lib/community/profile-read"
import { channelHref } from "@/lib/community/community-route"
@@ -22,7 +22,7 @@ import { currentPageObservation, navigationForHref } from "@/lib/observability/c
import { useForumTags } from "./use-channel-panels"
import { useStoredForumTag } from "./use-stored-forum-tag"
import { useConversationResource } from "./use-conversation-entry"
-import { forumFeedMatchesTags, forumFeedWindow, normalizeThreadResources, projectThread, type ForumFeedPage, type ForumFeedTransportPage } from "./forum-feed-window"
+import { forumFeedMatchesTags, forumFeedWindow, normalizeThreadResources, projectThread, type ForumFeedPage } from "./forum-feed-window"
export { removeForumPostFromFeed } from "./forum-feed-window"
export type { ForumFeedPage } from "./forum-feed-window"
@@ -64,16 +64,17 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null, quer
const observation = request.observation ?? (action && !action.done ? { action, reason: "foreground" as const }
: typeof window !== "undefined" && window.location.pathname === path ? { page: currentPageObservation(), reason: "background" as const }
: { page: undefined, reason: "unknown" as const })
- const transport = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/api/community/channels/${channelId}/threads?${params}`, {
+ const transport = await apiFetch<CommunityThreadsRead>(`/api/community/channels/${channelId}/threads?${params}`, {
...request, observation: { ...observation, ...(pageParam ? { reason: "pagination" as const } : {}), role: pageParam ? "pagination" : "window", windowMode: pageParam ? "older" : "newest" },
})
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, readSignal)
const page = normalizeThreadResources(channelId, transport)
const freshThreads = page.threads.filter((thread) => !protocol.get().publishedIds.has(thread.id))
const ids = new Set(freshThreads.map((thread) => thread.id)), openerIds = new Set(freshThreads.map((thread) => thread.parentMessageId))
- const users = new Set(page.included.members.filter((member) => ids.has(member.channelId)).map((member) => member.userId))
+ const messages = page.included.messages.filter((message) => openerIds.has(message.id) || ids.has(message.channelId))
+ const users = new Set([...page.included.members.filter((member) => ids.has(member.channelId)).map((member) => member.userId), ...messages.flatMap(messageProfileIds)])
publishCommunityForumFeed(queryClient, channelId, { ...page, threads: freshThreads, included: {
- messages: page.included.messages.filter((message) => openerIds.has(message.id) || ids.has(message.channelId)),
+ messages,
previews: page.included.previews.filter((message) => ids.has(message.channelId)),
tags: page.included.tags.filter((row) => openerIds.has(row.messageId)),
members: page.included.members.filter((row) => ids.has(row.channelId)),
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 65bd1504e..4e863b3a0 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,4 +1,6 @@
+import { singleMessageReadFixture, messageProfilesFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -53,7 +55,7 @@ describe("useForumOpenerHint", () => {
it("times out a cold opener, rejects its late publication, and recovers through refetch", async () => {
const { queryClient, wrapper } = await canonicalSetup()
let release!: (value: unknown) => void
- const payload = { id: "opener-1", content: "Recovered title", seq: 7, channelId: "forum-1", type: "chat" }
+ const payload = messageResourceFixture({ id: "opener-1", content: "Recovered title", seq: 7, channelId: "forum-1" })
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
vi.useFakeTimers()
let rendered!: ReturnType<typeof renderHook<ReturnType<typeof useForumOpenerHint>, unknown>>
@@ -66,9 +68,9 @@ describe("useForumOpenerHint", () => {
} finally { vi.useRealTimers() }
await waitFor(() => expect(rendered.result.current.isError).toBe(true))
expect(rendered.result.current.isLoading).toBe(false)
- await act(async () => { release(payload) })
+ await act(async () => { release(singleMessageReadFixture(payload)) })
expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
- apiFetchMock.mockResolvedValueOnce(payload)
+ apiFetchMock.mockResolvedValueOnce(singleMessageReadFixture(payload))
await act(async () => { await rendered.result.current.refetch() })
await waitFor(() => expect(rendered.result.current.data?.content).toBe("Recovered title"))
rendered.unmount()
@@ -76,7 +78,7 @@ describe("useForumOpenerHint", () => {
it("keeps a readable canonical opener after a transient background failure", 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 } })
+ publishCommunityMessages(queryClient, { profiles: messageProfilesFixture([messageResourceFixture({ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7 })]), channelId: "forum-1", messages: [messageResourceFixture({ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7 })], proof: { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined } })
apiFetchMock.mockRejectedValue(new Error("offline"))
const rendered = renderHook(() => useForumOpenerHint("server-1", "opener-1", true), { wrapper })
await waitFor(() => expect(rendered.result.current.isError).toBe(true))
@@ -96,14 +98,11 @@ describe("useForumOpenerHint", () => {
expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
})
- it("refetches a legacy seeded hint that lacks the opener seq", async () => {
+ it("reads the complete opener independently of an unrelated presentation hint", async () => {
const { queryClient, wrapper } = await canonicalSetup()
- apiFetchMock.mockResolvedValue({
- id: "opener-1",
- content: "Seeded",
- seq: 7,
- channelId: "forum-1",
- })
+ apiFetchMock.mockResolvedValue(singleMessageReadFixture(messageResourceFixture({
+ id: "opener-1", content: "Seeded", seq: 7, channelId: "forum-1",
+ })))
queryClient.setQueryData(
communityKeys.forumOpenerHint("server-1", "opener-1"),
{ id: "opener-1", content: "Seeded" },
@@ -127,15 +126,13 @@ describe("useForumOpenerHint", () => {
it("exposes a warm canonical opener without waiting for its background transport", async () => {
const { queryClient, wrapper } = await canonicalSetup()
- publishCommunityMessages(queryClient, {
+ publishCommunityMessages(queryClient, { profiles: messageProfilesFixture([messageResourceFixture({
+ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7,
+ })]),
channelId: "forum-1",
- messages: [{
- id: "opener-1",
- channelId: "forum-1",
- type: "chat",
- content: "Warm title",
- seq: 7,
- }],
+ messages: [messageResourceFixture({
+ id: "opener-1", channelId: "forum-1", content: "Warm title", seq: 7,
+ })],
proof: {
token: captureCommunityLiveSnapshotToken(queryClient),
signal: undefined,
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 d0ba2a05e..6cb957a7e 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,3 +1,7 @@
+import { BUSINESS_SCHEMA_VERSION, CommunityChannelResourceSchema, CommunityForumSidebarChannelSummarySchema } from "@alook/shared"
+import { messageSeedFixture } from "@/test/community-resource-fixtures"
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
+import { channelResourceFixture, messageResourceFixture, serverResourceFixture, fullResourceBundleFixture, serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { conversationEntryOptions } from "@/lib/community/conversation-entry"
@@ -26,6 +30,7 @@ import {
publishCommunityLiveSnapshot,
purgeCommunityChannel,
publishCommunityForumSidebar,
+ publishCommunityCreatedChannel,
publishCommunityChannelMetadata,
removeCanonicalCommunityChannelMembership,
setCanonicalCommunityChannelMembership,
@@ -76,9 +81,9 @@ beforeEach(() => async () => {
await act(async () => { await Promise.all(cleanups.splice(0).map((dispose) => dispose())) })
})
-function envelope(overrides: Partial<SidebarThreadEnvelope> = {}): SidebarThreadEnvelope {
+function envelope(overrides: { channels?: Array<Record<string, unknown> & { id: string }>; included?: { parentMessages: Array<Record<string, unknown> & { id: string }> } } = {}): SidebarThreadEnvelope {
const activityAt = new Date(Date.now() - 60_000).toISOString()
- return {
+ const scenario = {
channels: [{ categoryId: null, topic: "", position: 0, messageCount: 0, createdAt: "2026-10-01T00:00:00Z",
id: "post-1",
name: "fallback",
@@ -105,6 +110,14 @@ function envelope(overrides: Partial<SidebarThreadEnvelope> = {}): SidebarThread
serverNow: new Date().toISOString(),
...overrides,
}
+ const server = serverResourceFixture({ id: "server-1", ownerId: "viewer" })
+ const parents = [...new Set(scenario.channels.map(row => String(row.parentChannelId)))].map(id => channelResourceFixture({ id, serverId: server.id, type: "forum" }))
+ const channels = scenario.channels.map(row => channelResourceFixture({ ...Object.fromEntries(Object.entries(row).filter(([key]) => key in CommunityChannelResourceSchema.shape)), id: row.id, serverId: server.id, type: "thread" }))
+ const openers = scenario.included.parentMessages.map(row => messageResourceFixture({ ...row, id: row.id, channelId: String(row.channelId) }))
+ const summaries = scenario.channels.map(row => CommunityForumSidebarChannelSummarySchema.parse(Object.fromEntries(Object.entries(row).filter(([key]) => key in CommunityForumSidebarChannelSummarySchema.shape))))
+ return { schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: server.id, channels: summaries, canonicalChannels: summaries,
+ retainedChannel: null, retainedDisposition: null, serverNow: scenario.serverNow, resources: fullResourceBundleFixture("viewer", [server], [...parents, ...channels], openers) }
+
}
function envelopeFor(ids: string[]): SidebarThreadEnvelope {
@@ -141,7 +154,7 @@ async function setup() {
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
cleanups.push(unregister, registry.cleanup.bind(registry))
- ingestServers(registry, {
+ ingestServers(registry, serverRailResponseFixture({
servers: [{
id: "server-1",
name: "Server",
@@ -151,8 +164,8 @@ async function setup() {
mentions: 0,
ownerId: "viewer",
}],
- })
- ingestServerDetail(registry, {
+ }, (registry)!.accountId))
+ ingestServerDetail(registry, serverDirectoryFixture({
id: "server-1",
name: "Server",
discriminator: "0001",
@@ -170,7 +183,7 @@ async function setup() {
type: "forum",
}],
}],
- })
+ }))
const wrapper = ({ children }: PropsWithChildren) => createElement(
QueryClientProvider,
{ client: queryClient },
@@ -183,8 +196,9 @@ function publish(queryClient: QueryClient, data = envelope(), completeWindow = f
const normalized = normalizeForumSidebarEnvelope(data, null)
publishCommunityForumSidebar(queryClient, {
serverId,
- channels: data.channels,
- openers: data.included.parentMessages,
+ resources: data.resources,
+ channels: data.resources.channels.filter(row => row.type === "thread").map(row => ({ ...row, activityAt: data.channels.find(summary => summary.id === row.id)?.activityAt ?? data.serverNow, unread: data.channels.find(summary => summary.id === row.id)?.unread ?? false, participating: true })),
+ openers: data.resources.messages,
proof: {
token: captureCommunityLiveSnapshotToken(queryClient),
signal: undefined,
@@ -192,7 +206,7 @@ function publish(queryClient: QueryClient, data = envelope(), completeWindow = f
})
if (completeWindow) queryClient.setQueryData(communityKeys.forumSidebarThreads(serverId), {
...normalized.base, threads: [], window: {
- version: 1, accountId: "viewer", serverId,
+ version: BUSINESS_SCHEMA_VERSION, accountId: "viewer", serverId,
parents: getCanonicalCommunityChannels(queryClient).filter(row => row.serverId === serverId && row.type === "forum").map(row => row.id),
base: normalized.base.threads.map(({ id, parentChannelId, parentMessageId }) => ({ id, parentChannelId, parentMessageId })), retained: null,
},
@@ -200,6 +214,18 @@ function publish(queryClient: QueryClient, data = envelope(), completeWindow = f
return normalized
}
+function publishResourceSet(queryClient: QueryClient, resources: SidebarThreadEnvelope["resources"]) {
+ publishCommunityForumSidebar(queryClient, { serverId: resources.servers[0]!.id, resources,
+ channels: [], openers: resources.messages, proof: { token: captureCommunityLiveSnapshotToken(queryClient) } })
+}
+
+function setActivity(data: SidebarThreadEnvelope, index: number, activityAt: string) {
+ const summary = data.channels[index]!
+ summary.activityAt = activityAt
+ if (Number.isFinite(Date.parse(activityAt))) summary.expiresAt = new Date(Date.parse(activityAt) + 72 * 3600_000).toISOString()
+ data.resources.channels.find(row => row.id === summary.id)!.lastMessageAt = activityAt
+}
+
async function restorePersistedSidebar(queryClient: QueryClient) {
await clearPersistedCache("viewer")
const persister = createIdbPersister("viewer")
@@ -233,6 +259,69 @@ function ProjectedSidebar() {
}
describe("forum sidebar canonical projection", () => {
+ it("renders a new zero-reply thread above five older replies without replacing its null activity", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-10-28T00:00:00.000Z"))
+ const { queryClient, registry, wrapper } = await setup()
+ const previous = envelopeFor(["older-1", "older-2", "older-3", "older-4", "older-5"])
+ previous.channels.forEach((_, index) => setActivity(previous, index, new Date(Date.now() - (index + 2) * 60_000).toISOString()))
+ publishResourceSet(queryClient, previous.resources)
+ const response = envelopeFor(["new", "older-1", "older-2", "older-3", "older-4"])
+ response.channels.forEach((_, index) => setActivity(response, index, new Date(Date.now() - (index + 1) * 60_000).toISOString()))
+ const zeroReply = response.resources.channels.find(row => row.id === "new")!
+ zeroReply.createdAt = response.channels[0]!.activityAt
+ zeroReply.lastMessageAt = null
+ zeroReply.messageCount = 0
+ apiFetchMock.mockResolvedValue(response)
+ const view = render(createElement(ProjectedSidebar), { wrapper })
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ const rows = () => Array.from(view.container.querySelectorAll(`[data-testid^="${tid.forumSidebarThread("")}"]`)).map(row => row.getAttribute("data-testid"))
+ expect(rows()).toEqual(["new", "older-1", "older-2", "older-3", "older-4"].map(tid.forumSidebarThread))
+ expect(registry.collections.channels.get("new")?.lastMessageAt).toBeNull()
+ const project = (retainId: string | null, now: number) => projectForumSidebar(
+ getCanonicalCommunityChannels(queryClient), getCanonicalCommunityChannelMemberships(queryClient),
+ getCanonicalCommunityMessages(queryClient), "viewer", "server-1", retainId, now,
+ ).threads
+ const expiry = Date.parse(zeroReply.createdAt) + 72 * 3600_000
+ expect(project(null, expiry - 1)[0]).toMatchObject({ id: "new", activityAt: zeroReply.createdAt, expiresAt: new Date(expiry).toISOString() })
+ expect(project(null, expiry).some(row => row.id === "new")).toBe(false)
+ expect(project("new", expiry).map(row => row.id)).toEqual(["new"])
+ apiFetchMock.mockReturnValue(new Promise(() => {}))
+ await act(async () => { await vi.advanceTimersByTimeAsync(expiry - Date.now() + 50) })
+ expect(rows()).toEqual([])
+ expect(registry.collections.channels.get("new")?.lastMessageAt).toBeNull()
+ view.unmount()
+ queryClient.clear()
+ })
+
+ it("uses creation activity to reconcile a zero-reply miss above a fresh bounded cutoff", async () => {
+ const { queryClient, registry } = await setup()
+ const stale = envelopeFor(["new-miss", "old-miss"])
+ for (const [index, age] of [30_000, 180_000].entries()) {
+ setActivity(stale, index, new Date(Date.now() - age).toISOString())
+ const row = stale.resources.channels.find(row => row.id === stale.channels[index]!.id)!
+ row.createdAt = stale.channels[index]!.activityAt
+ row.lastMessageAt = null
+ }
+ publishResourceSet(queryClient, stale.resources)
+ const fresh = envelopeFor(["a", "b", "c", "d", "e"])
+ fresh.channels.forEach((_, index) => setActivity(fresh, index, new Date(Date.now() - 120_000).toISOString()))
+ apiFetchMock.mockResolvedValue(fresh)
+ const result = await reconcileForumSidebarNotifyMemberships(queryClient, "server-1")
+ expect(result.removedIds).toEqual(["new-miss"])
+ expect(registry.collections.channelMemberships.get("new-miss:viewer:notify")).toBeUndefined()
+ expect(registry.collections.channelMemberships.get("old-miss:viewer:notify")).toBeDefined()
+ expect(registry.collections.channelMemberships.get("new-miss:viewer:access")).toBeDefined()
+ expect(registry.collections.channels.get("new-miss")?.lastMessageAt).toBeNull()
+ })
+
+ it("admits repeated full current Sidebar resource bundles from live collection rows", async () => {
+ const { queryClient, registry } = await setup()
+ publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
+ publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
+ expect(registry.collections.channels.get("post-1")?.type).toBe("thread")
+ expect(registry.collections.serverMemberships.get("server-1:viewer")?.memberId).toBe("member-server-1")
+ })
it("keeps visible posts through unrelated metadata admission and a same-window post switch", async () => {
const { queryClient, wrapper } = await setup()
publish(queryClient, envelopeFor(["post-1", "post-2"]), true)
@@ -248,7 +337,7 @@ describe("forum sidebar canonical projection", () => {
await act(async () => {
publishCommunityChannelMetadata(queryClient, {
metadata: {
- ...envelopeFor(["unlisted"]).channels[0],
+ ...envelopeFor(["unlisted"]).resources.channels.find(row => row.id === "unlisted")!,
parentChannelId: "forum-1",
parentMessageId: "unlisted-opener",
},
@@ -292,9 +381,7 @@ describe("forum sidebar canonical projection", () => {
} else {
await act(async () => { resolveSidebar(negative) })
await waitFor(() => expect(rendered.result.current.sidebar.isSuccess).toBe(true))
- expect(registry.collections.channels.get("post-1")).toMatchObject({
- pending: true, tags: ["archived"], parentMessageId: null,
- })
+ expect(registry.collections.channels.get("post-1")).toBeUndefined()
expect(registry.collections.channelMemberships.get("post-1:viewer:access")).toBeUndefined()
await act(async () => { resolveMetadata(conversationEntryFromChannel(metadata)) })
}
@@ -302,7 +389,7 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(rendered.result.current.sidebar.isSuccess).toBe(true))
act(() => {
publishCommunityLiveSnapshot(queryClient, {
- snapshot: { kind: "server-detail", data: {
+ snapshot: { kind: "server-detail", data: serverDirectoryFixture({
id: "server-1", name: "Server", discriminator: "0001", description: "",
icon: null, ownerId: "viewer", categories: [{
id: "cat-1", name: "Forums", channels: [{
@@ -310,7 +397,7 @@ describe("forum sidebar canonical projection", () => {
}],
}],
forumUnreadState: { "forum-1": { baseUnread: false, childIds: ["post-1"] } },
- } },
+ }) },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined },
})
})
@@ -349,6 +436,40 @@ describe("forum sidebar canonical projection", () => {
rendered.unmount()
})
+ it.each(["pending", "failed"].flatMap(refresh => [false, true].map(existing => [refresh, existing] as const)))("keeps late metadata unarchived after WS unarchive with %s Sidebar refresh and existing=%s", async (refresh, existing) => {
+ const { queryClient, registry, wrapper } = await setup()
+ if (existing) publish(queryClient)
+ const negative = { ...envelopeFor([]), retainedChannel: null, retainedDisposition: "opener-archived" as const }
+ apiFetchMock.mockResolvedValueOnce(negative)
+ const sidebar = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
+ await waitFor(() => expect(sidebar.result.current.isSuccess).toBe(true))
+ expect(queryClient.getQueryData(communityKeys.forumSidebarThreads("server-1"))).toMatchObject({ window: { retained: { id: "post-1", disposition: "opener-archived" } } })
+ let resolveMetadata!: (value: ReturnType<typeof conversationEntryFromChannel>) => void
+ apiFetchMock.mockImplementation((path: string) => path.includes("/messages?entry=1")
+ ? new Promise(resolve => { resolveMetadata = resolve })
+ : refresh === "failed" ? Promise.reject(new Error("Sidebar unavailable")) : new Promise(() => {}))
+ const { dispatchCommunityWsEvent } = await import("./community-ws/registry")
+ await act(async () => {
+ dispatchCommunityWsEvent({ type: "community:channel.child_update", channelId: "post-1", parentChannelId: "forum-1", changes: { tags: ["bug"] } }, {
+ contract: BUSINESS_SCHEMA_VERSION, deliveryMode: "single", queryClient, communityStore: registry.runtime.ui, wsStore: registry.runtime.ws,
+ sub: { channelId: "post-1" }, viewerUserIdRef: { current: "viewer" }, matchesFocus: event => event.channelId === "post-1",
+ })
+ expect(queryClient.getQueryState(communityKeys.forumSidebarThreads("server-1"))?.isInvalidated).toBe(true)
+ })
+ await waitFor(() => expect(queryClient.getQueryState(communityKeys.forumSidebarThreads("server-1"))?.isInvalidated).toBe(true))
+ if (refresh === "failed") await waitFor(() => expect(sidebar.result.current.isError).toBe(true))
+ const metadata = renderHook(() => useChannelMetadata("server-1", "post-1"), { wrapper })
+ await waitFor(() => expect(resolveMetadata).toBeTypeOf("function"))
+ await act(async () => { resolveMetadata(conversationEntryFromChannel(channelResourceFixture({ id: "post-1", serverId: "server-1", type: "thread",
+ parentChannelId: "forum-1", parentMessageId: "opener-1", name: "After unarchive read" }))) })
+ await waitFor(() => expect(registry.collections.channels.get("post-1")?.name).toBe("After unarchive read"))
+ expect(registry.collections.channels.get("post-1")?.tags).not.toContain("archived")
+ expect(metadata.result.current.canRead).toBe(true)
+ expect(registry.collections.channelMemberships.get("post-1:viewer:notify")).toBeDefined()
+ expect(queryClient.getQueryData(communityKeys.forumSidebarThreads("server-1"))).toMatchObject({ window: { retained: { disposition: "opener-archived" } } })
+ metadata.unmount(); sidebar.unmount()
+ })
+
it("preserves a newer WS opener archive against an older positive response and permits current unarchive", async () => {
const { queryClient, registry, wrapper } = await setup()
publish(queryClient)
@@ -418,19 +539,20 @@ describe("forum sidebar canonical projection", () => {
it("includes a notified text reply in the shared sidebar after its message read", async () => {
const { queryClient, registry, wrapper } = await setup()
- act(() => ingestServerDetail(registry, {
+ act(() => ingestServerDetail(registry, serverDirectoryFixture({
id: "server-1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
categories: [{ id: "cat-1", name: "Channels", channels: [
{ id: "forum-1", name: "forum", active: false, unread: false, type: "forum" },
{ id: "text-1", name: "text", active: false, unread: false, type: "text" },
] }],
- }))
+ })))
apiFetchMock.mockResolvedValue(envelope())
const rendered = renderHook(() => useForumSidebarThreads("server-1", null), { wrapper })
await waitFor(() => expect(rendered.result.current.threads.map((row) => row.id)).toEqual(["post-1"]))
act(() => {
- ingestMessages(registry, "text-1", [{ id: "text-opener", type: "chat", content: "Text reply opener", seq: 1,
- thread: { id: "text-child", name: "Text reply", messageCount: 1, lastReplyAt: new Date().toISOString() } }])
+ publishCommunityCreatedChannel(queryClient, channelResourceFixture({ id: "text-child", serverId: "server-1", type: "thread", parentChannelId: "text-1", parentMessageId: "text-opener", name: "Text reply" }), { token: captureCommunityLiveSnapshotToken(queryClient) })
+ ingestMessages(registry, "text-1", messageSeedFixture("text-1", [{ id: "text-opener", type: "chat", content: "Text reply opener", seq: 1,
+ thread: { id: "text-child", name: "Text reply", messageCount: 1, lastReplyAt: new Date().toISOString() } }]))
setCanonicalCommunityChannelMembership(queryClient, "text-child", "notify", true)
})
await waitFor(() => expect(getCanonicalCommunityChannels(queryClient).some((row) => row.id === "text-child")).toBe(true))
@@ -440,7 +562,7 @@ describe("forum sidebar canonical projection", () => {
expect(registry.collections.channelMemberships.get("text-child:viewer:notify")).toBeDefined()
rendered.unmount()
})
- it("uses sidebar identity and opener while one protected metadata GET qualifies reading", async () => {
+ it("uses full current Sidebar access and opener while one protected metadata GET refreshes reading", async () => {
const { queryClient, wrapper } = await setup()
apiFetchMock.mockResolvedValueOnce(envelope())
let retainId: string | null = null
@@ -448,7 +570,7 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(sidebar.result.current.threads[0]?.title).toBe("Canonical title"))
let releaseRetained!: (value: SidebarThreadEnvelope) => void
const retained = new Promise<SidebarThreadEnvelope>((resolve) => { releaseRetained = resolve })
- apiFetchMock.mockImplementation((url) => url === "/api/community/channels/post-1/messages?entry=1" ? Promise.resolve(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: null, lastMessageAt: null, ...envelope().channels[0], id: "post-1", serverId: "server-1", type: "thread", name: "Canonical title", archived: false, createdAt: new Date().toISOString() })) : retained)
+ apiFetchMock.mockImplementation((url) => url === "/api/community/channels/post-1/messages?entry=1" ? Promise.resolve(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: null, lastMessageAt: null, id: "post-1", serverId: "server-1", type: "thread", name: "Canonical title", archived: false, createdAt: new Date().toISOString() })) : retained)
retainId = "post-1"
sidebar.rerender()
const route = renderHook(() => {
@@ -457,12 +579,13 @@ describe("forum sidebar canonical projection", () => {
return { metadata, opener }
}, { wrapper })
try {
- expect(route.result.current.metadata.identityKnown).toBe(false)
- expect(route.result.current.metadata.canRead).toBe(false)
+ expect(route.result.current.metadata.identityKnown).toBe(true)
+ expect(route.result.current.metadata.canRead).toBe(true)
await waitFor(() => expect(route.result.current.metadata.canRead).toBe(true))
expect(route.result.current.opener.data?.content).toBe("Canonical title")
await waitFor(() => expect(apiFetchMock.mock.calls.some(([url]) => new URL(url, "http://localhost").searchParams.get("retainId") === "post-1")).toBe(true))
expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/channels/post-1/messages?entry=1")).toHaveLength(1)
+ await waitFor(() => expect(queryClient.getQueryData(conversationEntryOptions(queryClient, { serverId: "server-1", channelId: "post-1" }).queryKey)).toBeDefined())
expect(isChannelMetadataTokenCurrent(queryClient.getQueryData(conversationEntryOptions(queryClient, { serverId: "server-1", channelId: "post-1" }).queryKey)!.proof)).toBe(true)
} finally {
route.unmount()
@@ -478,7 +601,7 @@ describe("forum sidebar canonical projection", () => {
if (race === "account") getCommunityDbRegistry(queryClient)!.runtime.ws.actions.activateProfileAccount("other")
else getCommunityDbRegistry(queryClient)!.runtime.ws.actions.revokeChannelAccess("server-1", "post-1")
expect(() => publishCommunityForumSidebar(queryClient, {
- serverId: "server-1", channels: envelope().channels, openers: envelope().included.parentMessages,
+ serverId: "server-1", resources: envelope().resources, channels: envelope().resources.channels.filter(row => row.type === "thread").map(row => ({ ...row, activityAt: envelope().serverNow, unread: false, participating: true })), openers: envelope().resources.messages,
proof: { token, signal: undefined },
})).toThrow()
expect(queryClient.getQueryData(communityKeys.channelMeta("server-1", "post-1"))).toBeUndefined()
@@ -488,7 +611,7 @@ describe("forum sidebar canonical projection", () => {
it("does not qualify an archived child carried in a sidebar response", async () => {
const { queryClient, registry } = await setup()
const response = envelope()
- response.channels[0]!.archived = true
+ response.resources.channels.find(row => row.id === "post-1")!.archived = true
publish(queryClient, response)
expect(registry.collections.channels.get("post-1")?.archived).toBe(true)
expect(queryClient.getQueryData(communityKeys.channelMeta("server-1", "post-1"))).toBeUndefined()
@@ -501,8 +624,8 @@ describe("forum sidebar canonical projection", () => {
const { queryClient, wrapper } = await setup()
const response = envelopeFor(["post-1", "post-2", "post-3", "post-4", "post-5", "post-6"])
const expired = new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString()
- Object.assign(response.channels[5]!, { activityAt: expired, lastMessageAt: expired, expiresAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(), unread: true })
- publish(queryClient, response)
+ setActivity(response, 5, expired)
+ publishResourceSet(queryClient, response.resources)
seedCommunityAttentionScope(queryClient, { channelId: "post-6", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(() => useForumSidebarProjection("server-1", "post-6", Date.now()), { wrapper })
await waitFor(() => expect(rendered.result.current?.threads).toHaveLength(5))
@@ -514,10 +637,10 @@ describe("forum sidebar canonical projection", () => {
rendered.unmount()
})
- it("ignores incomplete child metadata while normalizing", () => {
+ it("rejects incomplete child metadata while normalizing", () => {
const response = envelope()
response.channels[0] = { ...response.channels[0]!, serverId: undefined }
- expect(normalizeForumSidebarEnvelope(response, null, 0).channels).toEqual([])
+ expect(() => normalizeForumSidebarEnvelope(response, null, 0)).toThrow()
})
it("ignores another user's notify row in both Sidebar views and bounded negative reconciliation", async () => {
@@ -541,9 +664,8 @@ describe("forum sidebar canonical projection", () => {
const { queryClient, registry, wrapper } = await setup()
patchCanonicalCommunityChannel(queryClient, "forum-1", row => ({ ...row, type: parentType }))
const data = envelopeFor(["0", "9", "A", "Z", "a", "z", "expired"])
- const expired = data.channels.find((row) => row.id === "expired")!
- expired.lastMessageAt = expired.activityAt = new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString()
- publish(queryClient, data)
+ setActivity(data, 6, new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString())
+ publishResourceSet(queryClient, data.resources)
const rendered = renderHook(() => useForumSidebarProjection("server-1", retainId, Date.now()), { wrapper })
const expected = retainId === null ? ["z", "a", "Z", "A", "9"] : ["z", "a", "Z", "A", retainId]
await waitFor(() => expect(rendered.result.current?.threads.map((row) => row.id)).toEqual(expected))
@@ -565,24 +687,15 @@ describe("forum sidebar canonical projection", () => {
"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)
+ setActivity(stale, 0, new Date(now - 30_000).toISOString())
+ setActivity(stale, 1, new Date(now - 40_000).toISOString())
+ setActivity(stale, 2, new Date(now - 180_000).toISOString())
+ setActivity(stale, 3, new Date(now - 120_000).toISOString())
+ setActivity(stale, 4, new Date(now - (73 * 60 * 60 * 1000)).toISOString())
+ setActivity(stale, 5, "invalid")
+ publishResourceSet(queryClient, stale.resources)
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
- }
+ fresh.channels.forEach((_, index) => setActivity(fresh, index, new Date(now - 120_000).toISOString()))
apiFetchMock.mockResolvedValue({ ...fresh, canonicalChannels: fresh.channels })
const result = await reconcileForumSidebarNotifyMemberships(queryClient, "server-1")
@@ -677,16 +790,18 @@ describe("forum sidebar canonical projection", () => {
it("projects complete first frames for remounted A to B to A cached servers", async () => {
const { queryClient, registry, wrapper } = await setup()
publish(queryClient, envelope(), true)
- ingestServerDetail(registry, {
+ ingestServerDetail(registry, serverDirectoryFixture({
id: "server-2", name: "Second", discriminator: "0002", description: "", icon: null, ownerId: "viewer",
categories: [{ id: "cat-2", name: "Second forums", channels: [{ id: "forum-2", name: "Second forum", type: "forum", active: false, unread: false }] }],
- })
+ }))
const second = envelopeFor(["post-2"])
- publish(queryClient, {
- ...second,
- channels: second.channels.map(channel => ({ ...channel, serverId: "server-2", parentChannelId: "forum-2" })),
- included: { parentMessages: second.included.parentMessages.map(message => ({ ...message, channelId: "forum-2", type: "chat" as const })) },
- }, true, "server-2")
+ second.serverId = "server-2"
+ second.channels = second.channels.map(row => ({ ...row, serverId: "server-2", parentChannelId: "forum-2" }))
+ second.canonicalChannels = second.channels
+ second.resources = fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server-2" })],
+ second.resources.channels.map(row => ({ ...row, id: row.type === "forum" ? "forum-2" : row.id, serverId: "server-2", parentChannelId: row.type === "thread" ? "forum-2" : null })),
+ second.resources.messages.map(row => ({ ...row, channelId: "forum-2" })))
+ publish(queryClient, second, true, "server-2")
apiFetchMock.mockReturnValue(new Promise(() => {}))
const frames: Array<{ serverId: string; ids: string[]; ready: boolean }> = []
function Probe({ serverId }: { serverId: string }) {
@@ -740,7 +855,7 @@ describe("forum sidebar canonical projection", () => {
await act(async () => {
release()
await registry.preload()
- ingestServerDetail(registry, { id: "server-1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer", categories: [] })
+ ingestServerDetail(registry, serverDirectoryFixture({ id: "server-1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer", categories: [] }))
})
await waitFor(() => expect(view.result.current.projectionReady).toBe(true))
expect(view.result.current.threads).toEqual([])
@@ -795,10 +910,7 @@ describe("forum sidebar canonical projection", () => {
"post-2",
"post-1",
])
- for (const channel of fresh.channels) {
- channel.activityAt = restored.channels[0]!.activityAt
- channel.lastMessageAt = channel.activityAt
- }
+ fresh.channels.forEach((_, index) => setActivity(fresh, index, restored.channels[0]!.activityAt))
apiFetchMock.mockResolvedValue({ ...fresh, canonicalChannels: fresh.channels })
const rendered = renderHook(
@@ -853,21 +965,15 @@ describe("forum sidebar canonical projection", () => {
})
- it("normalizes a persisted default opener before one successful canonical publish", async () => {
+ it("rejects a legacy default opener before canonical publication", async () => {
const { queryClient, wrapper } = await setup()
const response = envelope()
- response.included.parentMessages[0]!.type = "default" as never
+ response.resources.messages[0]!.type = "default" as never
apiFetchMock.mockResolvedValue(response)
- const rendered = renderHook(
- () => useForumSidebarThreads("server-1", "post-1"),
- { wrapper },
- )
-
- await waitFor(() => expect(rendered.result.current.isSuccess).toBe(true))
+ const rendered = renderHook(() => useForumSidebarThreads("server-1", "post-1"), { wrapper })
+ await waitFor(() => expect(rendered.result.current.isError).toBe(true))
expect(apiFetchMock).toHaveBeenCalledOnce()
- expect(getCanonicalCommunityMessages(queryClient)).toContainEqual(
- expect.objectContaining({ id: "opener-1", type: "chat" }),
- )
+ expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
rendered.unmount()
})
@@ -907,7 +1013,7 @@ describe("forum sidebar canonical projection", () => {
threads: unknown[]
serverNow: string
}>(communityKeys.forumSidebarThreads("server-1")))
- .toMatchObject({ threads: [], serverNow: expect.any(String), window: { version: 1, base: [{ id: "post-1", parentChannelId: "forum-1", parentMessageId: "opener-1" }] } }))
+ .toMatchObject({ threads: [], serverNow: expect.any(String), window: { version: BUSINESS_SCHEMA_VERSION, base: [{ id: "post-1", parentChannelId: "forum-1", parentMessageId: "opener-1" }] } }))
rendered.unmount()
})
@@ -925,7 +1031,7 @@ describe("forum sidebar canonical projection", () => {
it("preserves system opener types at the canonical ingress boundary", () => {
const response = envelope()
- response.included.parentMessages[0]!.type = "system"
+ response.resources.messages[0]!.type = "system"
expect(normalizeForumSidebarEnvelope(response, null, 0).openers.find((message) => message.id === "opener-1"))
.toEqual(expect.objectContaining({ type: "system" }))
@@ -963,7 +1069,7 @@ describe("forum sidebar canonical projection", () => {
canonicalChannels: [],
retainedChannel: envelopeFor(["post-1"]).channels[0],
retainedDisposition: "eligible",
- included: envelopeFor(["post-1"]).included,
+ resources: envelopeFor(["post-1"]).resources,
}))
await waitFor(() => expect(second.result.current.threads[0]?.id).toBe("post-1"))
second.unmount()
@@ -987,7 +1093,7 @@ describe("forum sidebar canonical projection", () => {
canonicalChannels: [],
retainedChannel: retained.channels[0],
retainedDisposition: "eligible",
- included: retained.included,
+ resources: retained.resources,
}))
await waitFor(() => expect(rendered.result.current.threads[0]?.id).toBe("post-b"))
expect(apiFetchMock.mock.calls[1]?.[0]).toContain("retainId=post-b")
@@ -1058,7 +1164,7 @@ describe("forum sidebar canonical projection", () => {
canonicalChannels: [],
retainedChannel: retained.channels[0],
retainedDisposition: "eligible",
- included: retained.included,
+ resources: retained.resources,
}))
await waitFor(() => expect(rendered.result.current.threads[0]?.activityAt)
.toBe(activityAt))
@@ -1071,9 +1177,9 @@ describe("forum sidebar canonical projection", () => {
apiFetchMock.mockResolvedValue({
...envelopeFor([]),
canonicalChannels: [],
- retainedChannel: retained.channels[0],
+ retainedChannel: null,
retainedDisposition: "opener-archived",
- included: retained.included,
+ resources: retained.resources,
})
const rendered = renderHook(
() => useForumSidebarThreads("server-1", "post-1"),
@@ -1158,13 +1264,10 @@ describe("forum sidebar canonical projection", () => {
canonicalChannels: [],
retainedChannel: retained.channels[0],
retainedDisposition: "eligible",
- included: retained.included,
+ resources: retained.resources,
}))
await act(async () => Promise.resolve())
- expect(registry.collections.channels.get("post-1")).toMatchObject({
- serverId: "server-1", type: "thread", name: null, pending: true, tags: ["archived"],
- parentChannelId: null, parentMessageId: null,
- })
+ expect(registry.collections.channels.get("post-1")).toBeUndefined()
expect(registry.collections.channelMemberships.get("post-1:viewer:access")).toBeUndefined()
expect(registry.collections.channelMemberships.get("post-1:viewer:notify")).toBeUndefined()
expect(rendered.result.current.threads).toEqual([])
@@ -1186,7 +1289,7 @@ describe("forum sidebar canonical projection", () => {
canonicalChannels: [],
retainedChannel: retained.channels[0],
retainedDisposition: "eligible",
- included: retained.included,
+ resources: retained.resources,
})
expect((await grant) instanceof CancelledError).toBe(true)
expect(getCanonicalCommunityChannels(queryClient).some(({ id }) => id === "post-1"))
@@ -1215,6 +1318,7 @@ describe("forum sidebar canonical projection", () => {
publish(queryClient)
publishCommunityForumSidebar(queryClient, {
serverId: "server-1",
+ resources: envelopeFor([]).resources,
channels: [],
openers: [],
negativeRetain: { id: "post-1", disposition: "opener-archived" },
@@ -1259,7 +1363,7 @@ describe("forum sidebar canonical projection", () => {
it("keeps cold hidden-child unread ownership in canonical rows", async () => {
const { queryClient, registry, wrapper } = await setup()
- ingestServerDetail(registry, {
+ ingestServerDetail(registry, serverDirectoryFixture({
id: "server-1", name: "Server", discriminator: "0001", description: "",
icon: null, ownerId: "viewer", categories: [{
id: "cat-1", name: "Forums", channels: [{
@@ -1269,7 +1373,7 @@ describe("forum sidebar canonical projection", () => {
forumUnreadState: {
"forum-1": { baseUnread: false, childIds: ["hidden-child"] },
},
- })
+ }))
seedCommunityAttentionScope(queryClient, { channelId: "hidden-child", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(
() => useForumSidebarProjection("server-1", null, Date.now()),
@@ -1302,7 +1406,8 @@ describe("forum sidebar canonical projection", () => {
it("uses exact scope attention beyond the bounded item window for thread dots", async () => {
const { queryClient, registry, wrapper } = await setup()
publish(queryClient)
- ingestAttentionSnapshot(registry, {
+ ingestAttentionSnapshot(registry, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] },
+ resources: envelope().resources,
scopes: [{
scopeId: "post-1",
channelId: "post-1",
@@ -1348,7 +1453,7 @@ describe("forum sidebar canonical projection", () => {
expect(frames[0]).toEqual(["post-1"])
expect(rendered.result.current.fetchStatus).toBe("fetching")
const route = renderHook(() => useChannelMetadata("server-1", "post-1"), { wrapper })
- expect(route.result.current.isVerified).toBe(false)
+ expect(route.result.current.isVerified).toBe(true)
expect(route.result.current.canonical?.type).toBe("thread")
route.unmount()
rendered.unmount()
@@ -1420,8 +1525,8 @@ describe("forum sidebar canonical projection", () => {
apiFetchMock.mockReturnValue(new Promise<SidebarThreadEnvelope>(resolve => { release = resolve }))
const view = render(createElement(ProjectedSidebar), { wrapper })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
- const publishPrimary = () => ingestServerDetail(registry, { id: "server-1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
- categories: [{ id: "cat-1", name: "Forum", channels: [{ id: "forum-1", name: "Forum", type: "forum", active: false, unread: false }] }] })
+ const publishPrimary = () => ingestServerDetail(registry, serverDirectoryFixture({ id: "server-1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
+ categories: [{ id: "cat-1", name: "Forum", channels: [{ id: "forum-1", name: "Forum", type: "forum", active: false, unread: false }] }] }))
if (order === "primary-first") act(publishPrimary)
else await act(async () => { release(envelope()) })
expect(view.getByTestId(tid.channelSidebarPending("server-1"))).toBeVisible()
@@ -1511,9 +1616,9 @@ describe("forum sidebar canonical projection", () => {
it("rejects the window after the real message budget prunes its opener and starts a fresh read", async () => {
const owner = await setup()
publish(owner.queryClient, envelope(), true)
- ingestMessages(owner.registry, "forum-1", Array.from({ length: MAX_PERSISTED_MESSAGES_PER_SCOPE }, (_, index) => ({
+ ingestMessages(owner.registry, "forum-1", messageSeedFixture("forum-1", Array.from({ length: MAX_PERSISTED_MESSAGES_PER_SCOPE }, (_, index) => ({
id: `newer-${index}`, type: "chat" as const, content: "Newer", seq: index + 2, createdAt: new Date().toISOString(),
- })))
+ }))))
const target = await restorePersistedSidebar(owner.queryClient)
expect(target.registry.collections.messages.get("opener-1")).toBeUndefined()
expect(target.queryClient.getQueryData(communityKeys.forumSidebarThreads("server-1"))).toBeUndefined()
@@ -1572,7 +1677,9 @@ describe("forum sidebar canonical projection", () => {
const base = envelopeFor(["base-post"])
const extra = envelopeFor(["retained-post"])
apiFetchMock.mockResolvedValue({ ...base, canonicalChannels: base.channels, retainedChannel: extra.channels[0], retainedDisposition: "eligible",
- included: { parentMessages: [...base.included.parentMessages, ...extra.included.parentMessages] } })
+ resources: fullResourceBundleFixture("viewer", base.resources.servers,
+ [...base.resources.channels, ...extra.resources.channels.filter(row => !base.resources.channels.some(known => known.id === row.id))],
+ [...base.resources.messages, ...extra.resources.messages]) })
await grantForumSidebarChild(queryClient, "server-1", "retained-post")
expect(queryClient.getQueryData(communityKeys.forumSidebarThreads("server-1"))).toMatchObject({ threads: [], window: {
base: [{ id: "base-post" }], retained: { id: "retained-post", disposition: "eligible", reference: { id: "retained-post" } },
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 b70e526c8..e367f8a93 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -1,4 +1,6 @@
"use client"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { getServerDirectoryWindow } from "@/lib/community/server-directory-window"
import { useHydratedClient } from "@/hooks/use-hydrated-client"
import { useMountedClock } from "@/hooks/use-mounted-clock"
import { getCommunityRuntime } from "@/stores/community/runtime"
@@ -6,7 +8,7 @@ import { getCommunityRuntime } from "@/stores/community/runtime"
import { useEffect,useMemo,useRef } from "react"
import { QueryObserver,useQuery,useQueryClient,type QueryClient } from "@tanstack/react-query"
-import { type CommunityChannelIdentity, normalizeCommunityChannelIdentity } from "@alook/shared"
+import { CommunityForumSidebarEnvelopeSchema, type CommunityForumSidebarEnvelope, type CommunityResourceBundle, type CommunityChannelIdentity } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { communityKeys } from "@/lib/query-keys"
@@ -26,12 +28,13 @@ patchCanonicalCommunityChannel,
patchCanonicalCommunityMessage,
publishCommunityForumSidebar,
removeCanonicalCommunityChannelMembership,
+setCanonicalCommunityChannelMember,
setCanonicalCommunityChannelMembership,
type CommunityFreshQueryProof,
type CommunityForumSidebarChannel,
type CommunityForumSidebarOpener,
} from "@/lib/community-db/sync"
-import { supportsSidebarThreads, forumSidebarCandidates, viewerNotifyChannelIds, compareForumSidebarThreads as compareThreads,
+import { supportsSidebarThreads, forumSidebarActivityAt, forumSidebarCandidates, viewerNotifyChannelIds, compareForumSidebarThreads as compareThreads,
FORUM_SIDEBAR_ACTIVITY_WINDOW_MS as SIDEBAR_ACTIVITY_WINDOW_MS, type ForumSidebarThread } from "@/lib/community/forum-sidebar"
export type { ForumSidebarThread } from "@/lib/community/forum-sidebar"
@@ -40,14 +43,7 @@ type ForumSidebarRetainedDisposition =
| "opener-archived"
| "genuine-negative"
-export type SidebarThreadEnvelope = {
- channels: Array<CommunityForumSidebarChannel & { expiresAt: string; createdAt?: string }>
- canonicalChannels?: SidebarThreadEnvelope["channels"]
- retainedChannel?: SidebarThreadEnvelope["channels"][number] | null
- retainedDisposition?: ForumSidebarRetainedDisposition | null
- included: { parentMessages: Array<Omit<CommunityForumSidebarOpener, "type"> & { type?: string }> }
- serverNow: string
-}
+export type SidebarThreadEnvelope = CommunityForumSidebarEnvelope
export type ForumSidebarQueryData = {
/** Empty with a DB registry; only the explicit providerless test boundary uses rows. */
@@ -64,6 +60,8 @@ export type ChildChannelMeta = Omit<CommunityChannelIdentity, "serverId" | "name
}
export type NormalizedForumSidebarEnvelope = {
+ serverId: string
+ resources: CommunityResourceBundle
base: ForumSidebarQueryData
retained: ForumSidebarThread | null
retainedDisposition: ForumSidebarRetainedDisposition | null
@@ -88,14 +86,14 @@ export function hasForumSidebarThread(
}
function projectForumSidebarThreads(data: SidebarThreadEnvelope) {
- const openerById = new Map(data.included.parentMessages.map((message) => [message.id, message]))
+ const openerById = new Map(data.resources.messages.map((message) => [message.id, message]))
return data.channels.flatMap((channel): ForumSidebarThread[] => {
if (!channel.parentChannelId || !channel.parentMessageId) return []
return [{
id: channel.id,
parentChannelId: channel.parentChannelId,
parentMessageId: channel.parentMessageId,
- title: openerById.get(channel.parentMessageId)?.content || channel.name,
+ title: openerById.get(channel.parentMessageId)?.content || channel.name || "Post",
activityAt: channel.activityAt,
expiresAt: channel.expiresAt,
unread: false,
@@ -103,58 +101,25 @@ function projectForumSidebarThreads(data: SidebarThreadEnvelope) {
})
}
-function sidebarChannelResource(
- channel: SidebarThreadEnvelope["channels"][number],
-): CommunityForumSidebarChannel | null {
- if (!channel.serverId || !channel.type || !channel.parentChannelId || !channel.parentMessageId) {
- return null
- }
- return {
- ...normalizeCommunityChannelIdentity({ ...channel, archived: channel.archived ?? false, creatorId: channel.creatorId ?? null, lastMessageAt: channel.activityAt }),
- serverId: channel.serverId,
- name: channel.name,
- parentChannelId: channel.parentChannelId,
- parentMessageId: channel.parentMessageId,
- activityAt: channel.activityAt,
- unread: false,
- participating: true,
- }
-}
-
export function normalizeForumSidebarEnvelope(
- envelope: SidebarThreadEnvelope,
+ value: unknown,
retainId: string | null,
serverClockOffsetOverride?: number,
): NormalizedForumSidebarEnvelope {
- const canonicalChannels = envelope.canonicalChannels ?? envelope.channels
+ const envelope = CommunityForumSidebarEnvelopeSchema.parse(value)
+ if (retainId ? envelope.retainedDisposition === null || envelope.retainedChannel && envelope.retainedChannel.id !== retainId
+ : envelope.retainedDisposition !== null || envelope.retainedChannel !== null) throw new Error("Forum retained result scope mismatch")
const base: ForumSidebarQueryData = {
- threads: projectForumSidebarThreads({ ...envelope, channels: canonicalChannels }),
- serverNow: envelope.serverNow,
- verifiedEpoch: -1,
- serverClockOffsetMs: serverClockOffsetOverride ?? (() => {
- const serverNowMs = Date.parse(envelope.serverNow)
- return Number.isFinite(serverNowMs) ? serverNowMs - Date.now() : 0
- })(),
+ threads: projectForumSidebarThreads({ ...envelope, channels: envelope.canonicalChannels }),
+ serverNow: envelope.serverNow, verifiedEpoch: -1,
+ serverClockOffsetMs: serverClockOffsetOverride ?? Date.parse(envelope.serverNow) - Date.now(),
}
- const retainedChannel = retainId && envelope.retainedChannel?.id === retainId
- ? envelope.retainedChannel
- : retainId && envelope.retainedDisposition == null
- ? canonicalChannels.find(channel => channel.id === retainId) ?? null
- : null
- const retained = retainedChannel
- ? projectForumSidebarThreads({ ...envelope, channels: [retainedChannel] })[0] ?? null
- : null
- const retainedDisposition = retainId
- ? envelope.retainedDisposition ?? (retained ? "eligible" : "genuine-negative")
- : null
- const channels = [...new Map([
- ...canonicalChannels,
- ...(retainedDisposition === "eligible" && retainedChannel ? [retainedChannel] : []),
- ].map((channel) => [channel.id, sidebarChannelResource(channel)])).values()].filter((channel) => channel !== null)
- const openers = envelope.included.parentMessages.map((message) => ({
- ...message, type: message.type === "system" ? "system" as const : "chat" as const,
+ const retained = envelope.retainedChannel ? projectForumSidebarThreads({ ...envelope, channels: [envelope.retainedChannel] })[0] : null
+ const selected = [...new Map([...envelope.canonicalChannels, ...(envelope.retainedChannel ? [envelope.retainedChannel] : [])].map(row => [row.id, row])).values()]
+ const channels = selected.map(summary => ({
+ ...envelope.resources.channels.find(row => row.id === summary.id)!, activityAt: summary.activityAt, unread: summary.unread, participating: true,
}))
- return { base, retained, retainedDisposition, channels, openers }
+ return { serverId: envelope.serverId, resources: envelope.resources, base, retained, retainedDisposition: envelope.retainedDisposition, channels, openers: envelope.resources.messages }
}
function sidebarUrl(serverId: string, retainId: string | null) {
@@ -199,8 +164,9 @@ function publishNormalizedForumSidebar(
signal: AbortSignal | undefined,
token: ReturnType<typeof captureCommunityLiveSnapshotToken>,
) {
+ if (normalized.serverId !== serverId) throw new Error("Forum sidebar server mismatch")
publishCommunityForumSidebar(queryClient, {
- serverId, channels: normalized.channels, openers: normalized.openers,
+ serverId, resources: normalized.resources, channels: normalized.channels, openers: normalized.openers,
negativeRetain: retainId && normalized.retainedDisposition !== "eligible"
? {
id: retainId,
@@ -215,7 +181,7 @@ function publishNormalizedForumSidebar(
const result = {
...normalized.base, threads: [], verifiedEpoch: token.accessEpoch,
window: {
- version: 1 as const, accountId: token.viewerId!, serverId,
+ version: BUSINESS_SCHEMA_VERSION, accountId: token.viewerId!, serverId,
parents: [...new Set([...getCanonicalCommunityChannels(queryClient).filter(row => row.serverId === serverId && supportsSidebarThreads(row.type)).map(row => row.id), ...normalized.channels.flatMap(row => row.parentChannelId ? [row.parentChannelId] : [])])],
base: normalized.base.threads.map(reference),
retained: retainId ? normalized.retainedDisposition === "eligible" && normalized.retained
@@ -225,9 +191,9 @@ function publishNormalizedForumSidebar(
},
}
const registry = getCommunityDbRegistry(queryClient)!
- if (!readForumSidebarWindowResult(result) || registry.collections.servers.get(serverId)?.detailComplete
+ if (!readForumSidebarWindowResult(result) || getServerDirectoryWindow(registry, serverId)
&& !forumSidebarWindowComplete(result.window, {
- servers: [...registry.collections.servers.values()], channels: getCanonicalCommunityChannels(queryClient),
+ directory: getServerDirectoryWindow(registry, serverId), servers: [...registry.collections.servers.values()], channels: getCanonicalCommunityChannels(queryClient),
channelMemberships: getCanonicalCommunityChannelMemberships(queryClient), messages: getCanonicalCommunityMessages(queryClient),
}, registry.accountId, serverId, retainId, Date.now() + result.serverClockOffsetMs)) throw new Error("Incomplete forum sidebar window")
return { data: result, reconciliation }
@@ -420,7 +386,7 @@ function reconcileForumSidebarNotifyMembershipsFromBase(
|| baseIds.has(channel.id)
|| !channel.parentChannelId
) continue
- const activityAt = channel.lastMessageAt ?? ""
+ const activityAt = forumSidebarActivityAt(channel)
const activityMs = Date.parse(activityAt)
if (
Number.isFinite(serverNowMs)
@@ -442,14 +408,8 @@ function reconcileForumSidebarNotifyMembershipsFromBase(
unread: false,
}
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)
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
+ if (setCanonicalCommunityChannelMember(queryClient, channel.id, proof.token.registry!.accountId!, "notify", false, { proof })) removedIds.push(channel.id)
}
return { removedIds }
}
@@ -480,6 +440,7 @@ export async function reconcileForumSidebarArchiveTag(
childId: string,
archived: boolean,
) {
+ void queryClient.invalidateQueries({ queryKey: communityKeys.forumSidebarThreads(serverId), exact: true, refetchType: "none" })
const cancellation = queryClient.cancelQueries({ queryKey: communityKeys.forumSidebarRetained(serverId, childId), exact: true })
if (archived) {
removeCanonicalCommunityChannelMembership(queryClient, childId, "notify")
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 4ee9e06f8..a9e39483a 100644
--- a/src/web/src/hooks/community/use-friends.dom.test.ts
+++ b/src/web/src/hooks/community/use-friends.dom.test.ts
@@ -1,3 +1,4 @@
+import { friendBucketScenarioFixture } from "@/test/community-resource-fixtures"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { createElement, type PropsWithChildren } from "react"
import { type QueryClient } from "@tanstack/react-query"
@@ -42,8 +43,8 @@ describe("useFriends / friendsQueryFn", () => {
},
"/api/community/friends/blocked": {
blocked: [
- { id: "b_1", userId: "blocked_1", name: "b", avatar: "b", avatarVersion: 2 },
- { id: "b_legacy", name: "legacy", avatar: "l", avatarVersion: 0 },
+ { id: "b_1", userId: "blocked_1", name: "b", discriminator: "0042", avatar: "b", avatarVersion: 2 },
+ { id: "b_legacy", userId: "other_blocked_peer", name: "legacy", discriminator: "0043", avatar: "l", avatarVersion: 0 },
],
},
"/api/community/friends/pending": {
@@ -51,6 +52,7 @@ describe("useFriends / friendsQueryFn", () => {
id: "p_1",
userId: "pending_1",
name: "p",
+ discriminator: "0044",
avatar: "p",
avatarVersion: 3,
kind: "incoming",
@@ -59,13 +61,15 @@ describe("useFriends / friendsQueryFn", () => {
}
apiFetchMock.mockImplementation(async (url: string) => {
if (!(url in byUrl)) throw new Error(`unexpected url ${url}`)
- return byUrl[url]
+ const data = byUrl[url] as { friends?: Array<{ userId: string; name: string; discriminator: string; avatar: string; avatarVersion: number }>; pending?: Array<{ userId: string; name: string; discriminator: string; avatar: string; avatarVersion: number }>; blocked?: Array<{ userId: string; name: string; discriminator: string; avatar: string; avatarVersion: number }> }
+ const bucket = url.endsWith("/accepted") ? "friends" : url.endsWith("/blocked") ? "blocked" : "pending"
+ return friendBucketScenarioFixture(bucket, data[bucket]!)
})
const { friendsQueryFn } = await import("./use-friends")
const { client } = await createCommunityQueryOwner()
const data = await client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn })
- expect(data.ids).toEqual(["f_1", "p_1", "blocked:blocked_1", "blocked:b_legacy"])
+ expect(data.ids).toEqual(["f_1", "p_1", "blocked:blocked_1", "blocked:other_blocked_peer"])
expect([...getCommunityDbRegistry(client)!.collections.friendships.values()]).toHaveLength(4)
expect(apiFetchMock).toHaveBeenCalledTimes(3)
expect(apiFetchMock.mock.calls.map((call) => call[0]).sort()).toEqual([
@@ -94,6 +98,7 @@ describe("useFriends / friendsQueryFn", () => {
},
{
id: "legacy",
+ userId: "other_friend_peer",
name: "legacy",
discriminator: "0002",
avatar: "legacy",
@@ -126,17 +131,17 @@ describe("useFriends / friendsQueryFn", () => {
],
blocked: [
{ id: "b1", userId: "blocked_1", name: "raw blocked", avatar: "raw", avatarVersion: 1 },
- { id: "legacy-blocked", name: "legacy blocked", avatar: "legacy", avatarVersion: 0 },
+ { id: "legacy-blocked", userId: "other_blocked_peer", name: "legacy blocked", avatar: "legacy", avatarVersion: 0 },
{ id: "missing-blocked", userId: "blocked_missing", name: "missing blocked", avatar: "missing", avatarVersion: 0 },
],
}
const registry = getCommunityDbRegistry(queryClient)!
- for (const row of [...raw.friends.map((friend) => ({ id: friend.id, userId: "userId" in friend ? friend.userId : friend.id, kind: "accepted", sub: friend.sub })),
- ...raw.pending.map((pending) => ({ ...pending })),
- ...raw.blocked.map((blocked) => ({ id: "blocked:" + ("userId" in blocked ? blocked.userId : blocked.id), userId: "userId" in blocked ? blocked.userId : blocked.id, kind: "blocked" }))]) await act(async () => { registry.collections.friendships.utils.writeUpsert(friendshipSchema.parse(row)) });
+ for (const row of [...raw.friends.map((friend) => ({ id: friend.id, userId: friend.userId, kind: "accepted", sub: friend.sub })),
+ ...raw.pending.map((pending) => ({ id: pending.id, userId: pending.userId, kind: pending.kind })),
+ ...raw.blocked.map((blocked) => ({ id: "blocked:" + (blocked.userId), userId: blocked.userId, kind: "blocked" }))]) await act(async () => { registry.collections.friendships.utils.writeUpsert(friendshipSchema.parse(row)) });
for (const row of [...raw.friends, ...raw.pending, ...raw.blocked]) {
- const userId = "userId" in row ? row.userId : row.id
- await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, discriminator: null, ...row, kind: "human", id: userId })) });
+ const userId = row.userId
+ await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ id: userId, name: row.name, discriminator: "discriminator" in row ? row.discriminator : "0042", avatar: row.avatar, avatarVersion: row.avatarVersion, kind: "human" })) });
}
const window = { ids: [...registry.collections.friendships.values()].map((row) => row.id) }
queryClient.setQueryData(communityKeys.friends(), window)
@@ -164,7 +169,7 @@ describe("useFriends / friendsQueryFn", () => {
avatarVersion: 6,
}],
])
- for (const [userId, fields] of canonicalProfiles) await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ identityComplete: false, ...registry.collections.profiles.get(userId), ...fields, id: userId })) });
+ for (const [userId, fields] of canonicalProfiles) await act(async () => { registry.collections.profiles.utils.writeUpsert(profileSchema.parse({ ...Object.fromEntries(Object.entries(registry.collections.profiles.get(userId)!).filter(([key]) => key in profileSchema.shape)), ...Object.fromEntries(Object.entries(fields).filter(([key]) => key !== "presence")), id: userId })) });
await act(async () => { registry.runtime.ws.actions.seedPresence(registry.runtime.ws.actions.beginPresenceSnapshot(), [["friend_1", "online"]]) });
let rendered!: ReturnType<typeof renderHook<ReturnType<typeof useFriends>, unknown>>
await act(async () => { rendered = renderHook(() => useFriends(), {
@@ -204,11 +209,44 @@ describe("useFriends / friendsQueryFn", () => {
expect(queryClient.getQueryData(communityKeys.friends())).toBe(window)
})
+ it.each(["accepted-user-id", "blocked-user-id", "pending-user-id", "relationship-id", "full-peer-profile", "partial-peer-profile", "wrong-viewer", "pending-kind"] as const)("rejects raw current bucket missing %s before publishing that bucket", async variant => {
+ const { friendsQueryFn } = await import("./use-friends")
+ const { client, registry } = await createCommunityQueryOwner()
+ const peer = { id: "relationship-raw", kind: "incoming", userId: "peer-raw", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0 }
+ const bucket = variant === "blocked-user-id" ? "blocked" : variant.startsWith("pending") ? "pending" : "friends"
+ const data = friendBucketScenarioFixture(bucket, [peer])
+ if (variant === "full-peer-profile") data.resources.profiles = []
+ else if (variant === "partial-peer-profile") delete (data.resources.profiles[0] as Partial<typeof data.resources.profiles[0]>).avatar
+ else if (variant === "wrong-viewer") data.resources.viewerId = "other"
+ else if (variant === "relationship-id") data[bucket][0]!.id = ""
+ else if (variant === "pending-kind") data[bucket][0]!.kind = "accepted"
+ else delete (data[bucket][0] as Partial<typeof peer>).userId
+ apiFetchMock.mockImplementation(async (url: string) => {
+ if (url.endsWith(bucket === "friends" ? "/accepted" : "/blocked")) return data
+ return friendBucketScenarioFixture(url.endsWith("/accepted") ? "friends" : url.endsWith("/pending") ? "pending" : "blocked", [])
+ })
+ await expect(client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn, retry: false })).rejects.toThrow()
+ expect([...registry.collections.friendships.values()]).toEqual([])
+ expect([...registry.collections.profiles.values()]).toEqual([])
+ })
+
+ it("uses complete resource identity while retaining only relationship presentation from its summary", async () => {
+ const { friendsQueryFn } = await import("./use-friends")
+ const { client, registry } = await createCommunityQueryOwner()
+ const response = friendBucketScenarioFixture("friends", [{ id: "relation", userId: "peer", name: "Old hint", discriminator: "0001", avatar: "old", avatarVersion: 1, sub: "relationship detail" }])
+ response.resources.profiles[0] = { id: "peer", name: "Full identity", discriminator: "0042", avatar: "actual", avatarVersion: 4 }
+ apiFetchMock.mockImplementation(async (url: string) => url.endsWith("/accepted") ? response : friendBucketScenarioFixture(url.endsWith("/pending") ? "pending" : "blocked", []))
+ await client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn })
+ expect(registry.collections.profiles.get("peer")).toMatchObject({ name: "Full identity", discriminator: "0042", avatar: "actual", avatarVersion: 4 })
+ expect(registry.collections.friendships.get("relation")).toMatchObject({ userId: "peer", sub: "relationship detail" })
+ expect(registry.collections.profiles.has("relation")).toBe(false)
+ })
+
it("populates queryClient at communityKeys.friends() and is invalidated by prefix", async () => {
apiFetchMock
- .mockResolvedValueOnce({ friends: [] })
- .mockResolvedValueOnce({ blocked: [] })
- .mockResolvedValueOnce({ pending: [] })
+ .mockResolvedValueOnce(friendBucketScenarioFixture("friends", []))
+ .mockResolvedValueOnce(friendBucketScenarioFixture("blocked", []))
+ .mockResolvedValueOnce(friendBucketScenarioFixture("pending", []))
const { friendsQueryFn } = await import("./use-friends")
const { client: queryClient } = await createCommunityQueryOwner()
const key = communityKeys.friends()
diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.ts
index 1410fde2b..0b14afddb 100644
--- a/src/web/src/hooks/community/use-friends.ts
+++ b/src/web/src/hooks/community/use-friends.ts
@@ -1,4 +1,6 @@
"use client"
+import { CommunityAcceptedFriendsReadSchema, CommunityBlockedFriendsReadSchema, CommunityPendingFriendsReadSchema, type CommunityResourceBundle } from "@alook/shared"
+import type { z } from "zod"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import type { QueryFunctionContext } from "@tanstack/react-query"
@@ -6,7 +8,6 @@ import { useQuery, keepPreviousData, type UseQueryResult } from "@tanstack/react
import { useMemo } from "react"
import { apiFetch } from "@/lib/api/client"
import {
- apiFetchProfiles,
communityUserProfilePatch,
loadAndSeedProfiles,
} from "@/lib/community/profile-seed"
@@ -57,49 +58,27 @@ export const friendsQueryFn = async (context: QueryFunctionContext) => {
// bucket from its own sub-resource endpoint (friends/accepted · friends/blocked
// · friends/pending) and compose the same triad. Same query key / cache grain
// as before, so mutations still fire one invalidation.
+ const readBucket = <T extends { resources: CommunityResourceBundle; stale?: false } | { stale: true }>(path: string, schema: z.ZodType<T>) => loadAndSeedProfiles(
+ origin => apiFetch<unknown>(path, { ...origin, signal: context.signal }).then(data => schema.parse(data)),
+ data => {
+ if (data.stale) throw new StaleReadError()
+ if (data.resources.viewerId !== registry!.accountId) throw new Error("Friend profile account mismatch")
+ return data.resources.profiles.map(profile => communityUserProfilePatch(profile.id, profile))
+ }, registry, context.signal, token,
+ )
const [acceptedData, blockedData, pendingData] = await Promise.all([
- apiFetchProfiles<{ friends: Friend[]; stale?: boolean }>(
- "/api/community/friends/accepted",
- (data) => {
- throwIfStale(data)
- return data.friends.map((friend) => communityUserProfilePatch(friend.userId ?? friend.id, friend, { legacyPresentation: true }))
- }, { signal: context.signal }, getCommunityDbRegistry(context.client),
- ),
- apiFetchProfiles<{ blocked: BlockedUser[]; stale?: boolean }>(
- "/api/community/friends/blocked",
- (data) => {
- throwIfStale(data)
- return data.blocked.map((blocked) => ({
- id: blocked.userId ?? blocked.id,
- identityAbout: { name: blocked.name },
- avatar: {
- avatar: blocked.avatar,
- avatarVersion: blocked.avatarVersion,
- },
- }))
- }, { signal: context.signal }, getCommunityDbRegistry(context.client),
- ),
- apiFetchProfiles<{ pending: PendingRequest[]; stale?: boolean }>(
- "/api/community/friends/pending",
- (data) => {
- throwIfStale(data)
- return data.pending.map((pending) => ({
- id: pending.userId,
- identityAbout: { name: pending.name },
- avatar: {
- avatar: pending.avatar,
- avatarVersion: pending.avatarVersion,
- },
- }))
- }, { signal: context.signal }, getCommunityDbRegistry(context.client),
- ),
+ readBucket("/api/community/friends/accepted", CommunityAcceptedFriendsReadSchema),
+ readBucket("/api/community/friends/blocked", CommunityBlockedFriendsReadSchema),
+ readBucket("/api/community/friends/pending", CommunityPendingFriendsReadSchema),
])
- publishCommunityFriendships(context.client, [
- ...acceptedData.friends.map((friend) => ({ id: friend.id, userId: friend.userId ?? friend.id, kind: "accepted" as const, sub: friend.sub })),
- ...pendingData.pending.map((pending) => ({ id: pending.id, userId: pending.userId, kind: pending.kind, needsOwnerApproval: pending.needsOwnerApproval })),
- ...blockedData.blocked.map((blocked) => ({ id: `blocked:${blocked.userId ?? blocked.id}`, userId: blocked.userId ?? blocked.id, kind: "blocked" as const })),
- ], { token, signal: context.signal })
- return { ids: [...acceptedData.friends.map((friend) => friend.id), ...pendingData.pending.map((pending) => pending.id), ...blockedData.blocked.map((blocked) => `blocked:${blocked.userId ?? blocked.id}`)] }
+ if (acceptedData.stale || blockedData.stale || pendingData.stale) throw new StaleReadError()
+ const rows = [
+ ...acceptedData.friends.map(row => ({ ...row, kind: "accepted" as const })),
+ ...pendingData.pending,
+ ...blockedData.blocked.map(row => ({ ...row, id: `blocked:${row.userId}`, kind: "blocked" as const })),
+ ]
+ publishCommunityFriendships(context.client, rows, { token, signal: context.signal })
+ return { ids: rows.map(row => row.id) }
}
export function useFriends(options?: { enabled?: boolean }): UseQueryResult<{ ids: string[] }> & {
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 3d93cddcc..56b8b5c39 100644
--- a/src/web/src/hooks/community/use-inbox.dom.test.ts
+++ b/src/web/src/hooks/community/use-inbox.dom.test.ts
@@ -1,3 +1,6 @@
+import { writeCommunityCollectionRows } from "@/lib/community-db/write"
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
+import { attentionSnapshotScenarioFixture, fullResourceBundleFixture, serverResourceFixture, channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import React, { useLayoutEffect } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import type { AccountAttentionSnapshot } from "@alook/shared"
@@ -14,6 +17,10 @@ import {
import {
clearAttentionScopeOptimistically,
ingestAttentionSnapshot,
+ captureCommunityLiveSnapshotToken,
+ publishAccountAttentionSnapshot,
+ projectCommunityWsEventToDb,
+ applyCommunityDmBlockAccess,
ingestServers,
} from "@/lib/community-db/sync"
import { useCommunityWsStore } from "@/stores/community/ws"
@@ -49,7 +56,7 @@ function forumSnapshot(): AccountAttentionSnapshot {
lastMessageAt: `2026-09-28T00:00:${openerSeq ?? 30}.000Z`,
...(openerSeq === undefined ? {} : { openerSeq, openerUnread: true }),
})
- return {
+ return attentionSnapshotScenarioFixture({
scopes: [{
scopeId: "forum",
channelId: "forum",
@@ -92,11 +99,11 @@ function forumSnapshot(): AccountAttentionSnapshot {
content: `Post ${seq}`,
})),
},
- }
+ })
}
function truncatedAttentionOnlySnapshot(): AccountAttentionSnapshot {
- return {
+ return attentionSnapshotScenarioFixture({
scopes: [{
scopeId: "channel",
channelId: "channel",
@@ -127,12 +134,12 @@ function truncatedAttentionOnlySnapshot(): AccountAttentionSnapshot {
profiles: [],
messages: [],
},
- }
+ })
}
function truncatedAttentionWithBoundedItemSnapshot(): AccountAttentionSnapshot {
const snapshot = truncatedAttentionOnlySnapshot()
- return {
+ return attentionSnapshotScenarioFixture({
...snapshot,
items: [{
id: "mention:mention",
@@ -163,12 +170,12 @@ function truncatedAttentionWithBoundedItemSnapshot(): AccountAttentionSnapshot {
content: "hello",
}],
},
- }
+ })
}
function emptyAttentionScopeSnapshot(): AccountAttentionSnapshot {
const snapshot = truncatedAttentionOnlySnapshot()
- return {
+ return attentionSnapshotScenarioFixture({
...snapshot,
scopes: [{
...snapshot.scopes[0]!,
@@ -178,11 +185,11 @@ function emptyAttentionScopeSnapshot(): AccountAttentionSnapshot {
}],
limit: 100,
truncated: false,
- }
+ })
}
function dmSnapshot({ mention = false }: { mention?: boolean } = {}): AccountAttentionSnapshot {
- return {
+ return attentionSnapshotScenarioFixture({
scopes: [{
scopeId: "dm",
channelId: "dm",
@@ -236,11 +243,11 @@ function dmSnapshot({ mention = false }: { mention?: boolean } = {}): AccountAtt
content: "hello",
}] : [],
},
- }
+ })
}
function childThreadSnapshot(): AccountAttentionSnapshot {
- return {
+ return attentionSnapshotScenarioFixture({
scopes: [{
scopeId: "child",
channelId: "child",
@@ -290,11 +297,11 @@ function childThreadSnapshot(): AccountAttentionSnapshot {
content: "Child",
}],
},
- }
+ })
}
function friendRequestSnapshot(): AccountAttentionSnapshot {
- return {
+ return attentionSnapshotScenarioFixture({
scopes: [],
items: [{
id: "friend_request:request",
@@ -320,7 +327,7 @@ function friendRequestSnapshot(): AccountAttentionSnapshot {
}],
messages: [],
},
- }
+ })
}
async function createHarness({
@@ -392,19 +399,75 @@ beforeEach(() => {
})
describe("useInboxAttention", () => {
+ it.each(["dm", "thread"] as const)("publishes current validated attention %s presentation through the HTTP owner", async (kind) => {
+ const snapshot = kind === "dm" ? dmSnapshot() : childThreadSnapshot()
+ apiFetchMock.mockResolvedValue(snapshot)
+ const harness = await createHarness({ owner: true })
+ try {
+ await waitFor(() => {
+ if (kind === "dm") {
+ expect(harness.latest.dms).toEqual([expect.objectContaining({ channelId: "dm", otherUserName: "Peer", lastUnreadSeq: 9 })])
+ expect(harness.registry.collections.channelMemberships.get("dm:peer:access")).toMatchObject({ channelId: "dm", userId: "peer", relation: "access" })
+ } else {
+ expect(harness.latest.servers[0]?.channels[0]?.children[0]).toMatchObject({ channelId: "child", openerSeq: 7, openerUnread: false })
+ expect(harness.registry.collections.channels.get("child")).toMatchObject({ openerSeq: 7, openerUnread: false })
+ }
+ })
+ expect(harness.latest.isSuccess).toBe(true)
+ } finally { harness.dispose() }
+ })
+
+ it("rejects a raw current attention DM descriptor before any collection changes", async () => {
+ const harness = await createHarness()
+ try {
+ const snapshot = dmSnapshot()
+ snapshot.included.dms[0].userId = "missing-full-peer"
+ const before = Object.fromEntries(Object.entries(harness.registry.collections).map(([name, collection]) => [name, [...collection.values()]]))
+ expect(() => ingestAttentionSnapshot(harness.registry, snapshot)).toThrow()
+ expect(Object.fromEntries(Object.entries(harness.registry.collections).map(([name, collection]) => [name, [...collection.values()]]))).toEqual(before)
+ } finally { harness.dispose() }
+ })
+
+ it("keeps newer canonical opener facts through a held attention query", async () => {
+ const harness = await createHarness()
+ try {
+ const snapshot = childThreadSnapshot()
+ ingestAttentionSnapshot(harness.registry, snapshot)
+ const token = captureCommunityLiveSnapshotToken(harness.queryClient)
+ const child = harness.registry.collections.channels.get("child")!
+ await writeCommunityCollectionRows(harness.registry, "channels", [{ ...child, openerSeq: 9, openerUnread: true }], row => row.id)
+ projectCommunityWsEventToDb(harness.queryClient, { type: "community:channel.update", channelId: "child", serverId: "server", changes: { name: "Newer child" } })
+ publishAccountAttentionSnapshot(harness.queryClient, { snapshot, proof: { token, signal: undefined } })
+ expect(harness.registry.collections.channels.get("child")).toMatchObject({ name: "Newer child", openerSeq: 9, openerUnread: true })
+ } finally { harness.dispose() }
+ })
+
+ it("rejects held attention after a current DM block retires its access", async () => {
+ const harness = await createHarness()
+ try {
+ const snapshot = dmSnapshot()
+ ingestAttentionSnapshot(harness.registry, snapshot)
+ const token = captureCommunityLiveSnapshotToken(harness.queryClient)
+ applyCommunityDmBlockAccess(harness.registry, "peer", true)
+ expect(harness.registry.runtime.ws.actions.isChannelAccessRevoked("dm", null)).toBe(true)
+ expect(() => publishAccountAttentionSnapshot(harness.queryClient, { snapshot, proof: { token, signal: undefined } })).toThrow("Stale community live snapshot")
+ expect(harness.registry.runtime.ws.actions.isChannelAccessRevoked("dm", null)).toBe(true)
+ } finally { harness.dispose() }
+ })
+
it("keeps unread server identity aligned with its canonical owner", async () => {
const harness = await createHarness()
try {
const server = { id: "server", name: "Server", discriminator: "0001", initial: "S", active: false, unread: true, mentions: 0, icon: "/first-server-icon.png" }
act(() => {
- ingestServers(harness.registry, { servers: [server] })
- ingestAttentionSnapshot(harness.registry, forumSnapshot())
+ ingestServers(harness.registry, serverRailResponseFixture({ servers: [server] }, (harness.registry)!.accountId))
+ ingestAttentionSnapshot(harness.registry, { ...forumSnapshot(), resources: { ...forumSnapshot().resources, servers: [serverResourceFixture({ id: server.id, name: server.name, discriminator: server.discriminator, icon: server.icon, ownerId: "viewer" })] } })
})
await waitFor(() => expect(harness.latest.servers[0]).toMatchObject({
serverName: "Server",
serverIcon: "/first-server-icon.png",
}))
- act(() => ingestServers(harness.registry, { servers: [{ ...server, name: "Renamed", icon: null }] }))
+ act(() => ingestServers(harness.registry, serverRailResponseFixture({ servers: [{ ...server, name: "Renamed", icon: null }] }, (harness.registry)!.accountId)))
await waitFor(() => expect(harness.latest.servers[0]).toMatchObject({
serverName: "Renamed",
serverIcon: null,
@@ -521,6 +584,8 @@ describe("useInboxAttention", () => {
archived: false,
lastMessageAt: "2026-09-28T00:00:40.000Z",
})
+ snapshot.resources.channels.push(channelResourceFixture({ id: "direct", serverId: "server", name: "Direct", lastMessageAt: "2026-09-28T00:00:40.000Z" }))
+ snapshot.resources.memberships.push({ channelId: "direct", userId: "viewer", relation: "access", source: "explicit" })
const harness = await createHarness()
try {
act(() => ingestAttentionSnapshot(harness.registry, snapshot))
@@ -588,6 +653,7 @@ describe("useInboxAttention", () => {
await registry.preload()
const unregister = registerCommunityDbRegistry(registry)
apiFetchMock.mockResolvedValueOnce({
+ resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "server" })], [channelResourceFixture({ id: "channel", serverId: "server" })], [messageResourceFixture({ id: "message", channelId: "channel", seq: 5, authorId: "peer", createdAt: "2026-09-28T00:00:05.000Z", content: "keep" })]),
marked: [{
id: "mark",
server: "Server",
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index dede0cee4..f82ea4cdd 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -13,7 +13,7 @@ import { communityRequestOptions } from "@/lib/community-db/sync"
import { apiFetch } from "@/lib/api/client"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { communityKeys } from "@/lib/query-keys"
-import { communityMessagePreviewFromLegacy } from "@alook/shared"
+import type { CommunityResourceBundle } from "@alook/shared"
import type {
InboxFriendRequest,
Marked,
@@ -35,7 +35,7 @@ useDmProjection,
} from "@/lib/community-db/projections"
import {
captureCommunityLiveSnapshotToken,
-publishCommunityEmbeddedMessages,
+publishCommunityResourceBundle,
} from "@/lib/community-db/sync"
import { useAccountAttentionProjection } from "./use-account-attention"
@@ -280,7 +280,7 @@ export function useInboxUnreads() {
return useInboxAttention()
}
-type MarkedResponse = { marked: Marked[] }
+type MarkedResponse = MarkedWindowResponse & { resources: CommunityResourceBundle }
type MarkedWindowResponse = { marked: Array<Omit<Marked, "m"> & { m: Pick<Marked["m"], "id"> }> }
const inboxMarkedQueryFn = (queryClient: QueryClient) =>
@@ -290,15 +290,7 @@ const inboxMarkedQueryFn = (queryClient: QueryClient) =>
"/api/community/users/me/marks",
signal ? { signal } : undefined, publicationToken,
))
- {
- publishCommunityEmbeddedMessages(queryClient, {
- entries: data.marked.map((marked) => ({
- channelId: marked.channelId,
- message: { ...communityMessagePreviewFromLegacy(marked.m, marked.channelId), resourceComplete: false },
- })),
- proof: { token: publicationToken, signal },
- })
- }
+ publishCommunityResourceBundle(queryClient, data.resources, { token: publicationToken, signal }, data.marked.map(row => ({ id: row.m.id, channelId: row.channelId })))
return { marked: data.marked.map((row) => ({ ...row, m: { id: row.m.id } })) }
}
diff --git a/src/web/src/hooks/community/use-invitable-friends.dom.test.ts b/src/web/src/hooks/community/use-invitable-friends.dom.test.ts
index aef228075..75dd6e233 100644
--- a/src/web/src/hooks/community/use-invitable-friends.dom.test.ts
+++ b/src/web/src/hooks/community/use-invitable-friends.dom.test.ts
@@ -1,3 +1,4 @@
+import { serverMembersReadFixture, friendBucketScenarioFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -19,9 +20,9 @@ describe("Native invitable friend projection", () => {
api.mockClear()
api.mockImplementation(async (path: string) => {
if (path.endsWith("/accepted")) return accepted
- if (path.endsWith("/blocked")) return { blocked: [] }
- if (path.endsWith("/pending")) return { pending: [] }
- if (path.includes("/members")) return { members: [], hasMore: false, limit: 100, total: 0 }
+ if (path.endsWith("/blocked")) return friendBucketScenarioFixture("blocked", [])
+ if (path.endsWith("/pending")) return friendBucketScenarioFixture("pending", [])
+ if (path.includes("/members")) return serverMembersReadFixture("server_1", [])
throw new Error(`Unexpected friend request: ${path}`)
})
const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { staleTime: 5_000, retry: false } } })
@@ -35,7 +36,7 @@ describe("Native invitable friend projection", () => {
expect(view.result.current.picker.isSuccess).toBe(false)
expect(api.mock.calls.filter(([path]) => path.endsWith("/accepted"))).toHaveLength(1)
- await act(async () => { release({ friends: [friend] }); await accepted })
+ await act(async () => { release(friendBucketScenarioFixture("friends", [friend])); await accepted })
await waitFor(() => expect(view.result.current.picker.isSuccess).toBe(true))
expect(view.result.current.picker.friends).toEqual([expect.objectContaining(friend)])
expect(view.result.current.shell.friends).toEqual([expect.objectContaining(friend)])
@@ -46,10 +47,10 @@ describe("Native invitable friend projection", () => {
const friend = { id: "friendship_warm", userId: "friend_warm", name: "Warm friend", discriminator: "0042", avatar: "W", avatarVersion: 0, status: "offline", sub: "" }
api.mockClear()
api.mockImplementation(async (path: string) => {
- if (path.endsWith("/accepted")) return { friends: [friend] }
- if (path.endsWith("/blocked")) return { blocked: [] }
- if (path.endsWith("/pending")) return { pending: [] }
- if (path.includes("/members")) return { members: [], hasMore: false, limit: 100, total: 0 }
+ if (path.endsWith("/accepted")) return friendBucketScenarioFixture("friends", [friend])
+ if (path.endsWith("/blocked")) return friendBucketScenarioFixture("blocked", [])
+ if (path.endsWith("/pending")) return friendBucketScenarioFixture("pending", [])
+ if (path.includes("/members")) return serverMembersReadFixture("server_1", [])
throw new Error(`Unexpected friend request: ${path}`)
})
const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { staleTime: 5_000, retry: false } } })
@@ -70,10 +71,10 @@ describe("Native invitable friend projection", () => {
const friend = { id: "friendship_selected", userId: "friend_selected", name: "Selected friend", discriminator: "0042", avatar: "S", avatarVersion: 0, status: "offline", sub: "" }
api.mockClear()
api.mockImplementation(async (path: string) => {
- if (path.endsWith("/accepted")) return { friends: [friend] }
- if (path.endsWith("/blocked")) return { blocked: [] }
- if (path.endsWith("/pending")) return { pending: [] }
- if (path.includes("/members")) return { members: [], hasMore: false, limit: 100, total: 0 }
+ if (path.endsWith("/accepted")) return friendBucketScenarioFixture("friends", [friend])
+ if (path.endsWith("/blocked")) return friendBucketScenarioFixture("blocked", [])
+ if (path.endsWith("/pending")) return friendBucketScenarioFixture("pending", [])
+ if (path.includes("/members")) return serverMembersReadFixture("server_1", [])
throw new Error(`Unexpected friend request: ${path}`)
})
const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { staleTime: 5_000, retry: false } } })
@@ -92,7 +93,7 @@ describe("Native invitable friend projection", () => {
it("keeps raw complete member pages with a default selector on fetched and cached reads", async () => {
const member = { id: "member_selected", userId: "user_selected", name: "Member", discriminator: "0042", avatar: "M", avatarVersion: 0, status: "offline", sub: "", role: "member" }
api.mockClear()
- api.mockResolvedValue({ members: [member], hasMore: false, cursor: null, limit: 100, total: 1 })
+ api.mockResolvedValue(serverMembersReadFixture("server_1", [member]))
const owner = await createCommunityQueryOwner()
const select = vi.fn(() => ({ pages: [], pageParams: [] }))
owner.client.setQueryDefaults(communityKeys.members("server_1"), { select })
@@ -111,11 +112,11 @@ describe("Native invitable friend projection", () => {
api.mockImplementation(async (path: string) => {
if (path.endsWith("/accepted")) {
if (failing) throw new Error("Friends unavailable")
- return { friends: [] }
+ return friendBucketScenarioFixture("friends", [])
}
- if (path.endsWith("/blocked")) return { blocked: [] }
- if (path.endsWith("/pending")) return { pending: [] }
- if (path.includes("/members")) return { members: [], hasMore: false, limit: 100, total: 0 }
+ if (path.endsWith("/blocked")) return friendBucketScenarioFixture("blocked", [])
+ if (path.endsWith("/pending")) return friendBucketScenarioFixture("pending", [])
+ if (path.includes("/members")) return serverMembersReadFixture("server_1", [])
throw new Error(`Unexpected friend request: ${path}`)
})
const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { retry: 1, retryDelay: 0 } } })
@@ -129,24 +130,24 @@ describe("Native invitable friend projection", () => {
expect(view.result.current.friends).toEqual([])
expect(view.result.current.data).toEqual({ friends: [] })
})
- it("seeds identified friends and preserves identifier-free presentation", async () => {
+ it("seeds explicit peer identities while preserving relationship presentation", async () => {
const identified = { id: "friendship_1", userId: "friend_1", name: "Alice", discriminator: "0042", avatar: "A", avatarVersion: 2, status: "offline", sub: "" }
- const legacy = { id: "legacy", name: "Legacy", discriminator: "0000", avatar: "L", avatarVersion: 0, status: "offline", sub: "" }
+ const other = { id: "relationship_other", userId: "friend_other", name: "Other", discriminator: "0000", avatar: "L", avatarVersion: 0, status: "offline", sub: "" }
api.mockImplementation(async (path: string) => {
- if (path.endsWith("/accepted")) return { friends: [identified, legacy] }
- if (path.endsWith("/blocked")) return { blocked: [] }
- if (path.endsWith("/pending")) return { pending: [] }
- if (path.includes("/members")) return { members: [], hasMore: false, limit: 100, total: 0 }
+ if (path.endsWith("/accepted")) return friendBucketScenarioFixture("friends", [identified, other])
+ if (path.endsWith("/blocked")) return friendBucketScenarioFixture("blocked", [])
+ if (path.endsWith("/pending")) return friendBucketScenarioFixture("pending", [])
+ if (path.includes("/members")) return serverMembersReadFixture("server_1", [])
throw new Error(`Unexpected friend request: ${path}`)
})
const owner = await createCommunityQueryOwner()
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
const view = renderHook(() => useInvitableFriends("server_1"), { wrapper })
await waitFor(() => expect(view.result.current.friends).toEqual([
- expect.objectContaining(identified), expect.objectContaining(legacy),
+ expect.objectContaining(identified), expect.objectContaining(other),
]))
- expect(owner.client.getQueryData(communityKeys.invitableFriends("server_1"))).toEqual({ serverId: "server_1", friendIds: ["friendship_1", "legacy"] })
+ expect(owner.client.getQueryData(communityKeys.invitableFriends("server_1"))).toEqual({ serverId: "server_1", friendIds: ["friendship_1", "relationship_other"] })
expect(owner.registry.collections.profiles.get("friend_1")?.name).toBe("Alice")
- expect(owner.registry.collections.friendships.get("legacy")).toMatchObject({ id: "legacy", kind: "accepted" })
+ expect(owner.registry.collections.friendships.get("relationship_other")).toMatchObject({ id: "relationship_other", userId: "friend_other", kind: "accepted" })
})
})
diff --git a/src/web/src/hooks/community/use-machines.list.dom.test.tsx b/src/web/src/hooks/community/use-machines.list.dom.test.tsx
index f2a6801b5..2b100db3d 100644
--- a/src/web/src/hooks/community/use-machines.list.dom.test.tsx
+++ b/src/web/src/hooks/community/use-machines.list.dom.test.tsx
@@ -1,3 +1,4 @@
+import { machineResourceFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -22,7 +23,7 @@ describe("machine list primary readiness", () => {
it("keeps a complete machine update instead of replacing it with an automatic old list read", async () => {
const { client } = await createCommunityQueryOwner()
const original = { id: "m1", hostname: "host", displayName: "Host", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "0.1.7", lastSeenAt: null, status: "online" as const, availableRuntimes: [], createdAt: "created", updatedAt: "updated" }
- load.mockImplementation((url: string) => Promise.resolve(url.endsWith("view=list") ? { machines: [original] } : { quotas: [] }))
+ load.mockImplementation((url: string) => Promise.resolve(url.endsWith("view=list") ? { machines: [original], complete: true } : { quotas: [] }))
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client }, children)
const hook = renderHook(() => useMachines(), { wrapper })
await waitFor(() => expect(hook.result.current.machines[0]?.daemonVersion).toBe("0.1.7"))
@@ -36,16 +37,16 @@ describe("machine list primary readiness", () => {
it.each([false, true])("keeps restored capacity unknown until the live list arrives (empty=%s)", async (empty) => {
const { client } = await createCommunityQueryOwner()
const primary = deferred<MachinesResponse>()
- const machine = { id: "m1", hostname: "host" }
+ const machine = machineResourceFixture()
const machineCapacity = { plan: { id: "free", displayName: "Free" }, isFounder: false, limit: 1, ownedCount: 1, onlineCount: 1 }
- client.setQueryData(communityKeys.machines(), { machines: empty ? [] : [machine], observed: false, source: "restored_idb" })
+ client.setQueryData(communityKeys.machines(), { machines: empty ? [] : [machine], complete: true, observed: false, source: "restored_idb" })
load.mockImplementation((url: string) => url.endsWith("view=list") ? primary.promise : Promise.resolve({ quotas: [], machineCapacity }))
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client }, children)
const hook = renderHook(() => useMachines(), { wrapper })
await waitFor(() => expect(client.getQueryData([...communityKeys.machines(), "observations"])).toMatchObject({ machineCapacity }))
expect(hook.result.current.isLoading).toBe(false)
expect(hook.result.current.data?.machineCapacity).toBeUndefined()
- await act(async () => primary.resolve({ machines: [{ ...machine, status: "online" }] } as MachinesResponse))
+ await act(async () => primary.resolve({ machines: [{ ...machine, status: "online" }], complete: true }))
await waitFor(() => expect(hook.result.current.data?.machineCapacity).toMatchObject({ onlineCount: 1, ownedCount: 1 }))
hook.unmount()
})
@@ -53,7 +54,7 @@ describe("machine list primary readiness", () => {
it("renders the actual list while optional observations wait or fail, and never recreates a removed machine", async () => {
const { client } = await createCommunityQueryOwner()
const optional = deferred<{ quotas: Array<{ machineId: string; quota: [] }> }>()
- load.mockImplementation((url: string) => url.endsWith("view=list") ? Promise.resolve({ machines: [{ id: "m1", hostname: "host", status: "online" }] }) : optional.promise)
+ load.mockImplementation((url: string) => url.endsWith("view=list") ? Promise.resolve({ machines: [machineResourceFixture()], complete: true }) : optional.promise)
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client }, children)
const hook = renderHook(() => useMachines(), { wrapper })
await waitFor(() => expect(hook.result.current.machines.map(row => row.id)).toEqual(["m1"]))
@@ -61,7 +62,7 @@ describe("machine list primary readiness", () => {
expect(hook.result.current.data?.machineCapacity).toBeUndefined()
expect(hook.result.current.capacityPending).toBe(true)
expect(client.getQueryData(communityKeys.machines())).not.toHaveProperty("quotas")
- await act(async () => { await publishMachines(client, captureMachinesPublication(client), current => ({ ...current, machines: [] })) })
+ await act(async () => { await publishMachines(client, captureMachinesPublication(client), current => current ? ({ ...current, machines: [] }) : undefined) })
await act(async () => optional.resolve({ quotas: [{ machineId: "m1", quota: [] }] }))
await waitFor(() => expect(hook.result.current.machines).toEqual([]))
expect(client.getQueryData(communityKeys.machines())).toMatchObject({ machines: [] })
@@ -70,7 +71,7 @@ describe("machine list primary readiness", () => {
it("retains a confirmed empty list when only quota fails", async () => {
const { client } = await createCommunityQueryOwner()
- load.mockImplementation((url: string) => url.endsWith("view=list") ? Promise.resolve({ machines: [] }) : Promise.reject(new Error("quota unavailable")))
+ load.mockImplementation((url: string) => url.endsWith("view=list") ? Promise.resolve({ machines: [], complete: true }) : Promise.reject(new Error("quota unavailable")))
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client }, children)
const hook = renderHook(() => useMachines(), { wrapper })
await waitFor(() => expect(hook.result.current.isSuccess).toBe(true))
@@ -82,7 +83,7 @@ describe("machine list primary readiness", () => {
it("merges observed quota only into its matching live row and preserves unmatched rows", async () => {
const { client } = await createCommunityQueryOwner()
const primary = deferred<MachinesResponse>()
- const first = { id: "m1", hostname: "one", displayName: "One", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "0.1.53", status: "online" as const, createdAt: "created", updatedAt: "updated" }
+ const first = { lastSeenAt: null, availableRuntimes: [], id: "m1", hostname: "one", displayName: "One", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "0.1.53", status: "online" as const, createdAt: "created", updatedAt: "updated" }
const second = { ...first, id: "m2", hostname: "two", status: "offline" as const }
const quota: [] = []
load.mockImplementation((url: string) => url.endsWith("view=list") ? primary.promise
@@ -92,7 +93,7 @@ describe("machine list primary readiness", () => {
await waitFor(() => expect(client.getQueryData([...communityKeys.machines(), "observations"])).toMatchObject({ quotas: [{ machineId: "m1", quota }, { machineId: "removed", quota: [] }] }))
expect(hook.result.current.machines).toEqual([])
expect(hook.result.current.isPending).toBe(true)
- await act(async () => primary.resolve({ machines: [first, second] }))
+ await act(async () => primary.resolve({ machines: [first, second], complete: true }))
await waitFor(() => expect(hook.result.current.machines[0]).toHaveProperty("quota", quota))
expect(hook.result.current.machines.map(row => row.id)).toEqual(["m1", "m2"])
expect(hook.result.current.machines[1]).toEqual(second)
diff --git a/src/web/src/hooks/community/use-machines.test.ts b/src/web/src/hooks/community/use-machines.test.ts
index 95ef4f388..676211ec9 100644
--- a/src/web/src/hooks/community/use-machines.test.ts
+++ b/src/web/src/hooks/community/use-machines.test.ts
@@ -33,7 +33,7 @@ const machineFixture: CommunityMachineSummary = {
describe("useMachines / machinesQueryFn", () => {
it("returns the machines envelope from GET /api/community/machines", async () => {
- apiFetchMock.mockResolvedValueOnce({ machines: [machineFixture] })
+ apiFetchMock.mockResolvedValueOnce({ machines: [machineFixture], complete: true })
const { machinesQueryFn } = await import("./use-machines")
const { client: qc } = await createCommunityQueryOwner()
const data = await qc.query({ queryKey: communityKeys.machines(), queryFn: machinesQueryFn })
@@ -42,12 +42,12 @@ describe("useMachines / machinesQueryFn", () => {
})
it("populates queryClient at communityKeys.machines()", async () => {
- apiFetchMock.mockResolvedValueOnce({ machines: [machineFixture] })
+ apiFetchMock.mockResolvedValueOnce({ machines: [machineFixture], complete: true })
const { machinesQueryFn } = await import("./use-machines")
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.machines()
await qc.query({ queryKey: key, queryFn: machinesQueryFn })
- expect(qc.getQueryData(key)).toEqual({ machines: [machineFixture], source: "network" })
+ expect(qc.getQueryData(key)).toEqual({ machines: [machineFixture], complete: true, observed: true, source: "network" })
// Prefix invalidation from communityKeys.all cascades to this key.
await qc.invalidateQueries({ queryKey: communityKeys.all })
const state = qc.getQueryState(key)
diff --git a/src/web/src/hooks/community/use-machines.ts b/src/web/src/hooks/community/use-machines.ts
index 30d452a64..9d1e75bb6 100644
--- a/src/web/src/hooks/community/use-machines.ts
+++ b/src/web/src/hooks/community/use-machines.ts
@@ -35,7 +35,7 @@ export function useMachines(options?: Pick<UseQueryOptions<MachinesResponse>, "s
const quota = observations.data?.quotas?.find(row => row.machineId === machine.id)?.quota
return quota ? { ...machine, quota } : machine
}) ?? (EMPTY_MACHINES as MachineSummary[]), [query.data?.machines, observations.data])
- const capacity = query.data?.complete !== false && query.data?.observed !== false && machines.every(machine => machine.status !== undefined)
+ const capacity = query.data?.complete === true && query.data?.observed === true && machines.every(machine => machine.status !== undefined)
? observations.data?.machineCapacity
: undefined
const data = useMemo(() => query.data ? { ...query.data, machines, ...(capacity ? { machineCapacity: { ...capacity, ownedCount: machines.length, onlineCount: machines.filter(machine => isPresenceOnline(machine.status)).length } } : {}) } : undefined, [query.data, machines, capacity])
diff --git a/src/web/src/hooks/community/use-message-unread-count.dom.test.ts b/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
index 2be175ad5..1deee1e20 100644
--- a/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
+++ b/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
@@ -1,3 +1,4 @@
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { expect, it } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -9,7 +10,7 @@ import { useMessageUnreadCount } from "./use-message-unread-count"
it("projects admitted local progress without changing the frozen entry boundary or confirming the read", async () => {
const owner = await createCommunityQueryOwner()
- const messages = [2, 5, 9].map(seq => ({ id: `m${seq}`, channelId: "c1", seq, authorId: "peer", type: "chat" as const, content: "Message", createdAt: `2026-10-27T00:00:0${seq}.000Z` }))
+ const messages = [2, 5, 9].map(seq => messageResourceFixture({ id: `m${seq}`, channelId: "c1", seq, authorId: "peer", content: "Message", createdAt: `2026-10-27T00:00:0${seq}.000Z` }))
ingestMessages(owner.registry, "c1", messages)
const entry = Object.freeze({ lastReadSeq: 2 })
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
diff --git a/src/web/src/hooks/community/use-message.dom.test.ts b/src/web/src/hooks/community/use-message.dom.test.ts
index a54f15796..6afb823dc 100644
--- a/src/web/src/hooks/community/use-message.dom.test.ts
+++ b/src/web/src/hooks/community/use-message.dom.test.ts
@@ -1,11 +1,13 @@
+import { messageProfilesFixture, messageResourceFixture, singleMessageReadFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import { CommunityDbProvider } from "@/lib/community-db/projections"
-import { ingestMessages } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishCommunityMessages } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
+import { writeCommunityCollectionRows } from "@/lib/community-db/write"
import { useMessage } from "./use-message"
import { takeMessageIdsForAccessScope } from "@/lib/community-db/message-access-scope"
@@ -29,18 +31,38 @@ function Owner({ children }: PropsWithChildren) {
return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children))
}
const scope = { channelId: "channel-1", serverId: "server-1" }
-const message = { id: "m_1", type: "chat" as const, authorId: "u_1", authorName: "Alice", content: "cached opener", createdAt: "2026-07-03T00:00:00.000Z" }
+const message = messageResourceFixture({ id: "m_1", channelId: scope.channelId, authorId: "u_1", authorName: "Alice", content: "cached opener", createdAt: "2026-07-03T00:00:00.000Z" })
describe("useMessage cache-first placeholder", () => {
it("returns a cached canonical list message while the exact query is pending", async () => {
- ingestMessages(registry, scope.channelId, [message])
+ publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
client.setQueryData(communityKeys.channelMessages(scope.channelId), { pages: [{ ids: [message.id], hasMore: false }], pageParams: [{ mode: "newest" }] })
const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
- await waitFor(() => expect(rendered.result.current.message).toMatchObject(message))
+ await waitFor(() => expect(rendered.result.current.message).toMatchObject({ id: message.id, type: message.type, seq: message.seq, authorId: message.authorId, authorName: message.authorName, content: message.content, createdAt: message.createdAt }))
expect(rendered.result.current.isPlaceholderData).toBe(true)
expect(rendered.result.current.fetchStatus).toBe("fetching")
})
+ it.each(["body", "profile"] as const)("repairs a fresh cached ID with its native %s missing through the same query", async missing => {
+ publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ client.setQueryData(communityKeys.message(message.id), message.id)
+ if (missing === "body") await writeCommunityCollectionRows(registry, "messages", [], row => row.id)
+ else await writeCommunityCollectionRows(registry, "profiles", [], row => row.id)
+ let release!: (value: ReturnType<typeof singleMessageReadFixture>) => void
+ const held = new Promise<ReturnType<typeof singleMessageReadFixture>>(resolve => { release = resolve })
+ apiFetchMock.mockImplementationOnce(() => held)
+ const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
+ expect(rendered.result.current.message).toBeNull()
+ await waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
+ expect(apiFetchMock).toHaveBeenCalledWith(`/api/community/messages/${message.id}`, expect.any(Object))
+ expect(rendered.result.current.message).toBeNull()
+ await act(async () => { release(singleMessageReadFixture(message)); await held })
+ await waitFor(() => expect(rendered.result.current.message).toMatchObject({ id: message.id, authorId: message.authorId, authorName: "Alice", content: message.content }))
+ expect(client.getQueryData(communityKeys.message(message.id))).toBe(message.id)
+ expect(registry.collections.profiles.get(message.authorId)).toMatchObject({ id: message.authorId, name: "Alice", discriminator: expect.any(String), avatarVersion: 0 })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ })
+
it("keeps a missing id disabled and returns no message", () => {
const rendered = renderHook(() => useMessage(null), { wrapper: Owner })
expect(rendered.result.current.message).toBeNull()
@@ -50,7 +72,7 @@ describe("useMessage cache-first placeholder", () => {
it("uses canonical identity exclusively when the DB provider is active", async () => {
client.setQueryData(communityKeys.message(message.id), { ...message, authorId: "raw", content: "raw query" })
- ingestMessages(registry, scope.channelId, [{ ...message, authorId: "canonical", authorName: "Canonical", content: "canonical row" }])
+ publishCommunityMessages(client, { channelId: scope.channelId, messages: [{ ...message, authorId: "canonical", authorName: "Canonical", content: "canonical row" }], profiles: messageProfilesFixture([{ ...message, authorId: "canonical", authorName: "Canonical" }]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.message).toMatchObject({ authorId: "canonical", content: "canonical row" }))
})
@@ -64,7 +86,7 @@ describe("useMessage cache-first placeholder", () => {
})
it.each(["current", "retired"] as const)("observes a %s native server retirement without copying access state", async lifetime => {
- ingestMessages(registry, scope.channelId, [message])
+ publishCommunityMessages(client, { channelId: scope.channelId, messages: [message], profiles: messageProfilesFixture([message]), proof: { token: captureCommunityLiveSnapshotToken(client) } })
client.setQueryData(communityKeys.message(message.id), message.id)
const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.message?.id).toBe(message.id))
diff --git a/src/web/src/hooks/community/use-message.test.ts b/src/web/src/hooks/community/use-message.test.ts
index dbfdba0f8..b5e370621 100644
--- a/src/web/src/hooks/community/use-message.test.ts
+++ b/src/web/src/hooks/community/use-message.test.ts
@@ -1,7 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityMessageReadSchema, type CommunityMessageResource } from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { profileResourceFixture } from "@/test/community-resource-fixtures"
+import { writeCommunityProfilePatches, communityUserProfilePatch } from "@/lib/community/profile-seed"
import { ingestMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
import { findCachedMessage, messageQueryFn, prefetchCommunityMessage, prefetchCommunityLatestMessage } from "./use-message"
@@ -9,25 +11,29 @@ const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
beforeEach(() => { apiFetchMock.mockReset() })
-const payload = {
+const payload = { seq: 4, replyToId: null, clientNonce: null, attachments: [],
id: "m_1", channelId: "channel-1", type: "chat" as const, authorId: "u_1",
- authorName: "Alice", authorAvatar: "", authorAvatarVersion: 0, content: "hi there",
+ authorName: "Alice", authorAvatar: null, authorAvatarVersion: 0, content: "hi there",
createdAt: "2026-07-03T00:00:00.000Z",
}
-const completePayload = { ...payload, resourceComplete: true as const, seq: 4, replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] }
+const completePayload = { ...payload, seq: 4, replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] }
+
+const authorProfile = profileResourceFixture({ id: "u_1", name: "Alice", discriminator: "0001" })
+const singleRead = (message: CommunityMessageResource) => CommunityMessageReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: message.channelId, message, profiles: [authorProfile] })
+const pageRead = (messages: CommunityMessageResource[]) => ({ messages, profiles: messages.length ? [authorProfile] : [], latestSeq: Math.max(0, ...messages.map(message => message.seq)), hasMoreOlder: false, hasMoreNewer: false })
describe("background canonical message hydration", () => {
it("deduplicates concurrent reads and shares the exact message cache without opening a window", async () => {
const { client, registry } = await createCommunityQueryOwner()
- let release!: (value: typeof completePayload) => void
+ let release!: (value: ReturnType<typeof singleRead>) => void
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
const first = prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
const second = prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
- release(completePayload)
+ release(singleRead(completePayload))
await Promise.all([first, second])
- expect(registry.collections.messages.get(payload.id)).toMatchObject({ resourceComplete: true, content: payload.content, seq: 4 })
+ expect(registry.collections.messages.get(payload.id)).toMatchObject({ content: payload.content, seq: 4 })
expect(client.getQueryData(communityKeys.message(payload.id))).toBe(payload.id)
expect(client.getQueryData(communityKeys.channelMessages(payload.channelId))).toBeUndefined()
await prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
@@ -36,25 +42,27 @@ describe("background canonical message hydration", () => {
it("reads a hint-only channel's latest full resource without creating a conversation window", async () => {
const { client, registry } = await createCommunityQueryOwner()
- apiFetchMock.mockResolvedValue({ messages: [completePayload] })
+ apiFetchMock.mockResolvedValue(pageRead([completePayload]))
await Promise.all([
prefetchCommunityLatestMessage(client, payload.channelId),
prefetchCommunityLatestMessage(client, payload.channelId),
])
expect(apiFetchMock.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/channel-1/messages?limit=1"])
- expect(new Headers(apiFetchMock.mock.calls[0][1].headers).get(COMMUNITY_CONTRACT_HEADER)).toBe("3")
- expect(registry.collections.messages.get(payload.id)?.resourceComplete).toBe(true)
+ expect(new Headers(apiFetchMock.mock.calls[0][1].headers).get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(registry.collections.messages.get(payload.id)).toMatchObject(payload)
expect(client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBe(payload.id)
expect(client.getQueryData(communityKeys.channelMessages(payload.channelId))).toBeUndefined()
})
- it("hydrates a partial canonical message through the existing exact-ID reader", async () => {
+ it("rejects a partial canonical message and hydrates through the existing exact-ID reader", async () => {
const { client, registry } = await createCommunityQueryOwner()
- ingestMessages(registry, payload.channelId, [{ ...payload, seq: 4 }])
- apiFetchMock.mockResolvedValueOnce(completePayload)
+ const { attachments: _attachments, ...partial } = payload
+ expect(() => ingestMessages(registry, payload.channelId, [partial])).toThrow()
+ expect(registry.collections.messages.get(payload.id)).toBeUndefined()
+ apiFetchMock.mockResolvedValueOnce(singleRead(completePayload))
await prefetchCommunityMessage(client, payload.id, { channelId: payload.channelId })
expect(apiFetchMock.mock.calls.map(([path]) => path)).toEqual(["/api/community/messages/m_1"])
- expect(registry.collections.messages.get(payload.id)?.resourceComplete).toBe(true)
+ expect(registry.collections.messages.get(payload.id)).toMatchObject(payload)
})
it("does not fetch for retired access or an inactive owner", async () => {
@@ -70,12 +78,12 @@ describe("background canonical message hydration", () => {
it("does not publish a latest resource after its account owner retires", async () => {
const owner = await createCommunityQueryOwner()
- let release!: (value: { messages: typeof completePayload[] }) => void
+ let release!: (value: ReturnType<typeof pageRead>) => void
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
const result = prefetchCommunityLatestMessage(owner.client, payload.channelId).catch((error) => error)
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
owner.runtime.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
- release({ messages: [completePayload] })
+ release(pageRead([completePayload]))
expect(await result).toMatchObject({ name: "AbortError" })
expect(apiFetchMock).toHaveBeenCalledTimes(1)
expect(owner.registry.collections.messages.get(payload.id)).toBeUndefined()
@@ -85,11 +93,11 @@ describe("background canonical message hydration", () => {
const { client, registry } = await createCommunityQueryOwner()
const next = { ...completePayload, id: "new", seq: 5, content: "newest" }
const other = { ...completePayload, id: "other", channelId: "channel-2" }
- let releaseOld!: (value: { messages: typeof completePayload[] }) => void
- let releaseOther!: (value: { messages: typeof completePayload[] }) => void
+ let releaseOld!: (value: ReturnType<typeof pageRead>) => void
+ let releaseOther!: (value: ReturnType<typeof pageRead>) => void
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { releaseOld = resolve }))
.mockImplementationOnce(() => new Promise((resolve) => { releaseOther = resolve }))
- .mockResolvedValueOnce({ messages: [next] })
+ .mockResolvedValueOnce(pageRead([next]))
const old = prefetchCommunityLatestMessage(client, payload.channelId).catch((error) => error)
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
const secondChannel = prefetchCommunityLatestMessage(client, other.channelId)
@@ -97,27 +105,27 @@ describe("background canonical message hydration", () => {
await prefetchCommunityLatestMessage(client, payload.channelId)
expect(apiFetchMock.mock.calls[0][1].signal.aborted).toBe(true)
expect(apiFetchMock.mock.calls[1][1].signal.aborted).toBe(false)
- releaseOld({ messages: [completePayload] })
- releaseOther({ messages: [other] })
+ releaseOld(pageRead([completePayload]))
+ releaseOther(pageRead([other]))
await Promise.all([old, secondChannel])
expect(registry.collections.messages.get(payload.id)).toBeUndefined()
expect(registry.collections.messages.get(next.id)?.content).toBe("newest")
- expect(registry.collections.messages.get(other.id)?.resourceComplete).toBe(true)
+ expect(registry.collections.messages.get(other.id)).toMatchObject(other)
expect(client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBe(next.id)
expect(client.getQueryData(communityKeys.channelLatestMessage(other.channelId))).toBe(other.id)
})
it("stores null for an empty latest page and rejects a late revoked-scope resource", async () => {
const owner = await createCommunityQueryOwner()
- apiFetchMock.mockResolvedValueOnce({ messages: [] })
+ apiFetchMock.mockResolvedValueOnce(pageRead([]))
await prefetchCommunityLatestMessage(owner.client, payload.channelId)
expect(owner.client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBeNull()
- let release!: (value: { messages: typeof completePayload[] }) => void
+ let release!: (value: ReturnType<typeof pageRead>) => void
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
const result = prefetchCommunityLatestMessage(owner.client, payload.channelId).catch((error) => error)
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
retireCommunityChannelReading(owner.registry, payload.channelId, { reason: "read-denied" })
- release({ messages: [completePayload] })
+ release(pageRead([completePayload]))
await result
expect(owner.registry.collections.messages.get(payload.id)).toBeUndefined()
expect(owner.client.getQueryData(communityKeys.channelLatestMessage(payload.channelId))).toBeUndefined()
@@ -125,12 +133,12 @@ describe("background canonical message hydration", () => {
it("does not publish a full message response after channel access is revoked", async () => {
const owner = await createCommunityQueryOwner()
- let release!: (value: typeof completePayload) => void
+ let release!: (value: ReturnType<typeof singleRead>) => void
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
const result = prefetchCommunityMessage(owner.client, payload.id, { channelId: payload.channelId }).catch((error) => error)
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
owner.runtime.ws.actions.revokeChannelAccess(null, payload.channelId)
- release(completePayload)
+ release(singleRead(completePayload))
expect(await result).toMatchObject({ name: "AbortError" })
expect(owner.registry.collections.messages.get(payload.id)).toBeUndefined()
})
@@ -140,28 +148,28 @@ describe("useMessage / messageQueryFn", () => {
it("clears absent rich fields from a fresh complete exact response", async () => {
const { client, registry } = await createCommunityQueryOwner()
ingestMessages(registry, payload.channelId, [{ ...payload,
- attachments: [{ name: "old.txt", url: "/old", sizeBytes: 1024 }],
+ attachments: [{ id: "old", name: "old.txt", url: "/old", sizeBytes: 1024, thumbnailUrl: null, contentType: null, width: null, height: null }],
embeds: [{ title: "Old" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
- replyTo: { id: "reply", authorName: "Peer", text: "Old reply" },
+ replyToId: "reply", replyTo: { id: "reply", authorId: "peer", authorName: "Peer", text: "Old reply" },
}])
- apiFetchMock.mockResolvedValueOnce({ ...payload, resourceComplete: true, seq: 1, replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] })
+ apiFetchMock.mockResolvedValueOnce(singleRead({ ...payload, seq: 1, replyToId: null, clientNonce: null, attachments: [], embeds: [], reactions: [] }))
await client.query({ queryKey: communityKeys.message(payload.id), queryFn: messageQueryFn(payload.id, client) })
expect(registry.collections.messages.get(payload.id)).toMatchObject({ attachments: [], embeds: [], reactions: [], replyToId: null })
expect(registry.collections.messages.get(payload.id)?.replyTo).toBeUndefined()
})
it("fetches from /messages/:id and publishes the hydrated payload into canonical DB", async () => {
const { client, registry } = await createCommunityQueryOwner()
- apiFetchMock.mockResolvedValueOnce(payload)
+ apiFetchMock.mockResolvedValueOnce(singleRead(payload))
const data = await client.query({ queryKey: communityKeys.message(payload.id), queryFn: messageQueryFn(payload.id, client) })
expect(data).toBe(payload.id)
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/messages/m_1", expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
expect(registry.collections.messages.get(payload.id)).toMatchObject(payload)
- expect(registry.collections.profiles.get(payload.authorId)).toMatchObject({ name: "Alice" })
+ expect(registry.collections.profiles.get(payload.authorId)).toMatchObject(authorProfile)
})
it("populates queryClient at communityKeys.message(messageId) with only the ID", async () => {
const { client } = await createCommunityQueryOwner()
- apiFetchMock.mockResolvedValueOnce(payload)
+ apiFetchMock.mockResolvedValueOnce(singleRead(payload))
const key = communityKeys.message(payload.id)
await client.query({ queryKey: key, queryFn: messageQueryFn(payload.id, client) })
expect(client.getQueryData(key)).toBe(payload.id)
@@ -169,7 +177,7 @@ describe("useMessage / messageQueryFn", () => {
it("publishes an exact opener through the channel id carried by its response", async () => {
const { client, registry } = await createCommunityQueryOwner()
- apiFetchMock.mockResolvedValueOnce({ ...payload, channelId: "archived-post-1", content: "archived opener" })
+ apiFetchMock.mockResolvedValueOnce(singleRead({ ...payload, channelId: "archived-post-1", content: "archived opener" }))
await client.query({ queryKey: communityKeys.message(payload.id), queryFn: messageQueryFn(payload.id, client, "route-hint") })
expect(registry.collections.messages.get(payload.id)).toMatchObject({ channelId: "archived-post-1", content: "archived opener" })
})
@@ -178,15 +186,16 @@ describe("useMessage / messageQueryFn", () => {
const { client, registry } = await createCommunityQueryOwner()
const message = {
...payload, content: "cached opener",
- replyTo: { id: "m_0", authorName: "Bob", text: "parent" },
- attachments: [{ name: "notes.txt", url: "/notes.txt", sizeBytes: 1024 }],
+ replyToId: "m_0", replyTo: { id: "m_0", authorId: "u_0", authorName: "Bob", text: "parent" },
+ attachments: [{ id: "notes", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, thumbnailUrl: null, contentType: null, width: null, height: null }],
embeds: [{ title: "Reference" }],
reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_1"] }],
}
+ writeCommunityProfilePatches([authorProfile, profileResourceFixture({ id: "u_0", name: "Bob" })].map(profile => communityUserProfilePatch(profile.id, profile)), registry)
ingestMessages(registry, "channel-1", [message])
client.setQueryData(communityKeys.channelMessages("channel-1"), { pages: [{ ids: [message.id], hasMoreOlder: false, hasMoreNewer: false }], pageParams: [{ mode: "newest" }] })
- const { channelId: _channelId, ...view } = message
- expect(findCachedMessage(client, message.id)).toMatchObject({ ...view, attachments: [{ kind: "file", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, size: "1.0 KB" }] })
+ const { channelId: _channelId, replyToId: _replyToId, clientNonce: _clientNonce, ...view } = message
+ expect(findCachedMessage(client, message.id)).toMatchObject({ ...view, authorAvatar: "A", attachments: [{ kind: "file", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, size: "1.0 KB" }] })
expect(findCachedMessage(client, "missing")).toBeUndefined()
})
@@ -195,7 +204,7 @@ describe("useMessage / messageQueryFn", () => {
["communityKeys.all", communityKeys.all],
])("invalidation via %s marks the exact message resource invalidated", async (_label, queryKey) => {
const { client } = await createCommunityQueryOwner()
- apiFetchMock.mockResolvedValueOnce(payload)
+ apiFetchMock.mockResolvedValueOnce(singleRead(payload))
const key = communityKeys.message(payload.id)
await client.query({ queryKey: key, queryFn: messageQueryFn(payload.id, client) })
await client.invalidateQueries({ queryKey })
@@ -204,12 +213,12 @@ describe("useMessage / messageQueryFn", () => {
it("does not publish an exact opener after its original owner retires", async () => {
const a = await createCommunityQueryOwner("A"), b = await createCommunityQueryOwner("B")
- let release!: (data: typeof payload) => void
+ let release!: (data: ReturnType<typeof singleRead>) => void
apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
const result = a.client.query({ queryKey: communityKeys.message(payload.id), queryFn: messageQueryFn(payload.id, a.client) }).then(() => null, (error) => error)
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(1))
a.runtime.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
- release(payload)
+ release(singleRead(payload))
expect(await result).toMatchObject({ name: "AbortError" })
expect(a.registry.collections.messages.get(payload.id)).toBeUndefined()
expect(b.registry.collections.messages.get(payload.id)).toBeUndefined()
diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.ts
index 8e14ebbbc..51317cb86 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -12,13 +12,15 @@ import {
type UseQueryResult,
} from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
-import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_RESOURCE_CONTRACT_VERSION, CommunityMessageResourcesSchema, CommunityResourceProfileSchema, communityMessageProfileIds, type CommunityMessageRead } from "@alook/shared"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { communityKeys } from "@/lib/query-keys"
-import type { MessageInput, MessagesPage, Msg } from "@/lib/community/models/message"
+import type { MessagesReadPage, Msg } from "@/lib/community/models/message"
+import { avatarInitial } from "@/lib/community/avatar"
import { presentCanonicalMessage } from "@/lib/community/message-wire"
import {
useCanonicalMessagesById,
+ useCanonicalProfilesProjection,
useOptionalCommunityDbRegistry,
} from "@/lib/community-db/projections"
import {
@@ -34,7 +36,7 @@ import {
captureCommunityLiveSnapshotToken,
assertCommunityLiveSnapshotTokenCurrent,
publishCommunityMessages,
- getCanonicalCommunityMessages,
+ getCanonicalCommunityMessages, getCanonicalCommunityMessageResources,
} from "@/lib/community-db/sync"
/**
@@ -60,15 +62,17 @@ export const messageQueryFn = (
) => (context: QueryFunctionContext) => withConversationReadDeadline(context.signal, async readSignal => {
if (context.client !== queryClient) throw new DOMException("Mismatched message query owner", "AbortError")
const token = captureCommunityLiveSnapshotToken(queryClient, channelId)
- const message = await apiFetchCommunity<MessageInput>(
+ const read = await apiFetchCommunity<CommunityMessageRead>(
`/api/community/messages/${messageId}`,
{ signal: readSignal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) } }, token,
)
+ const message = read.message
const publishChannelId = message.channelId ?? channelId
if (publishChannelId) {
publishCommunityMessages(queryClient, {
channelId: publishChannelId,
messages: [message],
+ profiles: read.profiles,
proof: { token, signal: readSignal },
})
}
@@ -91,7 +95,7 @@ export async function prefetchCommunityMessage(queryClient: QueryClient, message
|| !communityScopeAllowsAccess(registry.runtime.ws.get(), scope)
|| queryClient.getMutationCache().findAll({ mutationKey: communityServerRetirementKey, status: "pending" }).some(mutation => communityServerRetirementId(mutation, registry) === scope.serverId && scope.serverId != null)) return
rememberMessageAccessScope(queryClient, messageId, scope)
- if (registry.collections.messages.get(messageId)?.resourceComplete) return
+ if (findCachedMessage(queryClient, messageId)) return
await queryClient.query({ ...messageQueryOptions(queryClient, messageId, scope.channelId), staleTime: 0, select: undefined })
}
@@ -111,11 +115,11 @@ export async function prefetchCommunityLatestMessage(queryClient: QueryClient, c
retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey }).retry),
networkMode: "always",
queryFn: ({ signal }) => withConversationReadDeadline(signal, async (readSignal) => {
- const page = await apiFetchCommunity<MessagesPage>(
+ const page = await apiFetchCommunity<MessagesReadPage>(
`/api/community/channels/${channelId}/messages?limit=1`,
{ signal: readSignal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) } }, token,
)
- publishCommunityMessages(queryClient, { channelId, messages: page.messages, proof: { token, signal: readSignal } })
+ publishCommunityMessages(queryClient, { channelId, messages: page.messages, profiles: page.profiles, proof: { token, signal: readSignal } })
return page.messages[0]?.id ?? null
}),
select: undefined,
@@ -128,14 +132,17 @@ export function findCachedMessage(
): OpenerPayload | undefined {
const message = getCanonicalCommunityMessages(queryClient).find((row) => row.id === messageId)
if (!message?.authorId || !message.createdAt) return undefined
+ const graph = getCanonicalCommunityMessageResources(queryClient, [message])
+ const author = graph?.profiles.find(profile => profile.id === message.authorId)
+ if (!author) return undefined
const view = presentCanonicalMessage(message)
return {
...view,
authorId: message.authorId,
- authorName: message.authorName ?? "Deleted user",
- authorAvatar: view.authorAvatar ?? "",
- authorAvatarVersion: message.authorAvatarVersion ?? 0,
- content: message.content ?? "",
+ authorName: author.name,
+ authorAvatar: author.avatar ?? avatarInitial(author.name),
+ authorAvatarVersion: author.avatarVersion,
+ content: message.content,
createdAt: message.createdAt,
}
@@ -152,15 +159,23 @@ export function useMessage(
const retiringServers = useMutationState({ filters: { mutationKey: communityServerRetirementKey, status: "pending" }, select: mutation => communityServerRetirementId(mutation, registry) })
const accessAllowed = useCommunityWsStore((state) => !accessScope || communityScopeAllowsAccess(state, accessScope))
&& !(accessScope?.serverId && retiringServers.includes(accessScope.serverId))
+ const canonical = messageId ? canonicalMessages?.get(messageId) : undefined
+ const raw = messageId ? registry?.collections.messages.get(messageId) : undefined
+ const profileIds = raw ? communityMessageProfileIds([raw]) : []
+ const profiles = useCanonicalProfilesProjection(profileIds)
+ const graph = raw ? getCanonicalCommunityMessageResources(queryClient, [raw]) : undefined
+ const nativeGraph = graph ? CommunityMessageResourcesSchema.safeParse({ messages: graph.messages, profiles: [...profiles.resourceProfiles.values()].flatMap(profile => {
+ const parsed = CommunityResourceProfileSchema.strip().safeParse(profile)
+ return parsed.success ? [parsed.data] : []
+ }) }) : undefined
+ const profilesReady = profileIds.length === 0 || profiles.isReady && !profiles.isError && nativeGraph?.success === true
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)?.id : undefined,
- [accessAllowed, messageId, queryClient],
- )
+ const placeholderData = messageId && accessAllowed ? findCachedMessage(queryClient, messageId)?.id : undefined
+
const query = useQuery({
...messageQueryOptions(queryClient, enabled ? messageId! : "__none__", accessScope?.channelId),
queryFn: enabled
@@ -169,13 +184,12 @@ export function useMessage(
enabled,
placeholderData,
})
- const canonical = messageId ? canonicalMessages?.get(messageId) : undefined
+ const refetch = query.refetch
+ useEffect(() => {
+ if (enabled && typeof query.data === "string" && !graph && query.isSuccess && !query.isFetching) void refetch({ cancelRefetch: false })
+ }, [enabled, query.data, graph, query.isSuccess, query.isFetching, refetch])
return {
...query,
- message: accessAllowed
- ? registry
- ? (canonical as OpenerPayload | undefined) ?? null
- : null
- : null,
+ message: accessAllowed && profilesReady && canonical && messageId ? findCachedMessage(queryClient, messageId) ?? null : null,
}
}
diff --git a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx
index 6854ef5f7..835d1fd04 100644
--- a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx
+++ b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx
@@ -1,3 +1,4 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClientProvider, onlineManager } from "@tanstack/react-query"
@@ -37,7 +38,7 @@ describe("entry-owned message activation", () => {
const first = renderHook(useSurface, { wrapper })
await waitFor(() => expect(first.result.current.initialPositionKnown).toBe(true))
expect(first.result.current.messages?.map(row => row.id)).toEqual(["m1"])
- expect(load).toHaveBeenCalledOnce()
+ expect(load, JSON.stringify(load.mock.calls.map(call => call[0]))).toHaveBeenCalledOnce()
first.unmount()
const returned = renderHook(useSurface, { wrapper })
await waitFor(() => expect(returned.result.current.messages?.map(row => row.id)).toEqual(["m1"]))
@@ -78,7 +79,7 @@ describe("entry-owned message activation", () => {
const m3 = { ...m2, id: "m3", seq: 3, content: "New landing", createdAt: "2026-10-01T00:00:03.000Z" }
load.mockImplementation((url: string) => url.includes("entry=1")
? Promise.resolve({ ...packet, messages: [packet.messages[0], m3], page: { ...packet.page, latestSeq: 3 } })
- : Promise.resolve({ messages: [m2, m3], latestSeq: 3, hasMoreNewer: false, hasMoreOlder: true }))
+ : Promise.resolve(messageReadPageFixture({ messages: [m2, m3], latestSeq: 3, hasMoreNewer: false, hasMoreOlder: true })))
const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 6000)
try {
const returned = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })
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 f06d60b87..bc5584fbd 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
@@ -1,3 +1,4 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClientProvider, onlineManager } from "@tanstack/react-query"
@@ -82,7 +83,7 @@ describe("entry failure and explicit recovery", () => {
await waitFor(() => expect(hook.result.current.positionDataState).toBe("error"))
expect(hook.result.current.messages.map(row => row.id)).toEqual(["m1"])
expect(hook.result.current.positionEntry).toBe(retry)
- load.mockResolvedValue({ messages: conversationEntryFixture().messages, latestSeq: 1, hasMoreOlder: false, hasMoreNewer: false })
+ load.mockResolvedValue(messageReadPageFixture({ messages: conversationEntryFixture().messages, latestSeq: 1, hasMoreOlder: false, hasMoreNewer: false }))
await act(async () => hook.result.current.retryInitialLoad())
await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))
expect(hook.result.current.positionEntry).not.toBe(retry)
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 04ec8cfd2..e4688c7be 100644
--- a/src/web/src/hooks/community/use-messages.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.dom.test.ts
@@ -1,3 +1,5 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { messageWindowOptions } from "@/lib/community/message-window"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
@@ -35,7 +37,7 @@ async function loadHook() {
describe("channelMessagesQueryFn — url per mode", () => {
it("newest → no query params", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMore: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("ch_1")({ client, signal: new AbortController().signal, pageParam: { mode: "newest" } })
expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/ch_1/messages", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))
@@ -43,7 +45,7 @@ describe("channelMessagesQueryFn — url per mode", () => {
it("older → ?cursor=<c>", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMore: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("ch_1")({
client,
@@ -58,7 +60,7 @@ describe("channelMessagesQueryFn — url per mode", () => {
it("newer → ?since=<c>", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMoreNewer: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMoreNewer: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("ch_1")({
client,
@@ -73,7 +75,7 @@ describe("channelMessagesQueryFn — url per mode", () => {
it("anchor → ?anchor=<id>", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("ch_1")({
client,
@@ -88,7 +90,7 @@ describe("channelMessagesQueryFn — url per mode", () => {
it("since → ?since=<c>", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMoreNewer: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMoreNewer: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("ch_1")({
client,
@@ -122,7 +124,7 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
} else {
runtime.ws.actions.revokeChannelAccess("server-1", "ch_1")
}
- resolveTransport({ messages: [], hasMore: false })
+ resolveTransport(messageReadPageFixture({ messages: [], hasMore: false }))
await rejection
},
@@ -130,11 +132,11 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
it("strips the transport receipt before returning a cache-safe page", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({
messages: [],
hasMore: false,
surfaceReceipt: { channelId: "ch_1", surfaceKind: "channel" },
- })
+ }))
const { client } = await createCommunityQueryOwner()
const page = await channelMessagesQueryFn("ch_1")({
@@ -148,7 +150,7 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
it("passes TanStack's AbortSignal to apiFetch", async () => {
const { channelMessagesQueryFn } = await loadHook()
const controller = new AbortController()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMore: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("ch_abort")({
@@ -167,7 +169,7 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
it("populates queryClient at communityKeys.channelMessages(channelId)", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_1" }], hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [messageResourceFixture({ id: "m_1", channelId: "ch_1" })], hasMore: false }))
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.channelMessages("ch_1")
await qc.infiniteQuery({
@@ -179,7 +181,7 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
})
it("prefix invalidation includes anchored message windows", async () => {
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMore: false }))
const { client: qc } = await createCommunityQueryOwner()
const cursorKey = communityKeys.channelMessagesWindow("ch_1", { mode: "anchor", anchor: "m1" })
await qc.query({ queryKey: cursorKey, queryFn: () => apiFetchMock() })
@@ -192,11 +194,11 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
describe("shared DM message window transport", () => {
it("strips the authoritative receipt before QueryClient storage", async () => {
- apiFetchMock.mockResolvedValueOnce({
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({
messages: [],
hasMore: false,
surfaceReceipt: { channelId: "dm_1", surfaceKind: "dm" },
- })
+ }))
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.dmMessages("dm_1")
@@ -209,7 +211,7 @@ describe("shared DM message window transport", () => {
it("passes TanStack's AbortSignal to apiFetch", async () => {
const { channelMessagesQueryFn } = await loadHook()
const controller = new AbortController()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMore: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("dm_abort")({
@@ -228,7 +230,7 @@ describe("shared DM message window transport", () => {
it("newest → no query params", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMore: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("dm_1")({ client, signal: new AbortController().signal, pageParam: { mode: "newest" } })
expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/dm_1/messages", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))
@@ -236,7 +238,7 @@ describe("shared DM message window transport", () => {
it("older cursor → ?cursor", async () => {
const { channelMessagesQueryFn } = await loadHook()
- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [], hasMore: false, latestSeq: 0 }))
const { client } = await createCommunityQueryOwner()
await channelMessagesQueryFn("dm_1")({
client,
@@ -251,8 +253,8 @@ describe("shared DM message window transport", () => {
it("fetchNextPage (older) produces a new page under the same infinite key", async () => {
apiFetchMock
- .mockResolvedValueOnce({ messages: [{ id: "m_1" }], hasMore: true, cursor: "cur_1", latestSeq: 1 })
- .mockResolvedValueOnce({ messages: [{ id: "m_2" }], hasMore: false, latestSeq: 1 })
+ .mockResolvedValueOnce(messageReadPageFixture({ messages: [messageResourceFixture({ id: "m_1", channelId: "dm_1" })], hasMore: true, cursor: "cur_1", latestSeq: 1 }))
+ .mockResolvedValueOnce(messageReadPageFixture({ messages: [messageResourceFixture({ id: "m_2", channelId: "dm_1", seq: 2 })], hasMore: false, latestSeq: 1 }))
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.dmMessages("dm_1")
await qc.infiniteQuery({
@@ -390,13 +392,13 @@ describe("bounded messages publication", () => {
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
retireCommunityChannelReading(registry, "parent", { reason: "read-denied", serverId: "server" })
if (lineage === "late-lineage") runtime.ws.actions.observeChannelScope("server", "child", "parent")
- resolve({ messages: [{ id: "late-child-message", type: "chat", seq: 1, authorId: "late-author", authorName: "Late", content: "private" }], hasMore: false, latestSeq: 1, surfaceReceipt: { channelId: "child", surfaceKind: "thread" } })
+ resolve(messageReadPageFixture({ messages: [messageResourceFixture({ channelId: "child", id: "late-child-message", type: "chat", seq: 1, authorId: "late-author", authorName: "Late", content: "private" })], hasMore: false, latestSeq: 1, surfaceReceipt: { channelId: "child", surfaceKind: "thread" } }))
await rejected
expect(registry.collections.messages.has("late-child-message")).toBe(false)
expect(registry.collections.profiles.has("late-author")).toBe(false)
expect(client.getQueryData(key)).toBeUndefined()
expect(() => assertCommunityLiveSnapshotTokenCurrent(client, sibling, undefined)).not.toThrow()
- apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "fresh-child-message", type: "chat", seq: 2, authorId: "fresh-author", authorName: "Fresh", content: "fresh" }], hasMore: false, latestSeq: 2 })
+ apiFetchMock.mockResolvedValueOnce(messageReadPageFixture({ messages: [messageResourceFixture({ channelId: "child", id: "fresh-child-message", type: "chat", seq: 2, authorId: "fresh-author", authorName: "Fresh", content: "fresh" })], hasMore: false, latestSeq: 2 }))
await client.infiniteQuery({ queryKey: key, queryFn: channelMessagesQueryFn("child"), initialPageParam: { mode: "newest" }, getNextPageParam: () => undefined, retry: false })
expect(registry.collections.messages.has("fresh-child-message")).toBe(true)
expect(client.getQueryData(key)).toBeDefined()
@@ -412,10 +414,10 @@ describe("bounded messages publication", () => {
const request = channelMessagesQueryFn("sibling-dm")({ client, pageParam: { mode: "newest" } })
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
retireCommunityChannelReading(registry, "parent", { reason: "read-denied", serverId: "server" })
- resolve({ messages: [{ id: "dm-message", type: "chat", seq: 1, authorId: "peer", authorName: "Peer", content: "current" }], hasMore: false, latestSeq: 1 })
+ resolve(messageReadPageFixture({ messages: [messageResourceFixture({ channelId: "sibling-dm", id: "dm-message", type: "chat", seq: 1, authorId: "peer", authorName: "Peer", content: "current" })], hasMore: false, latestSeq: 1 }))
await expect(request).resolves.toMatchObject({ messages: [{ id: "dm-message" }] })
expect(registry.collections.messages.has("dm-message")).toBe(true)
- expect(registry.collections.profiles.has("peer")).toBe(true)
+ expect(registry.collections.profiles.get("peer")).toMatchObject({ id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0 })
})
it("does not publish a late message, profile or navigation receipt after deadline failure", async () => {
@@ -430,7 +432,7 @@ describe("bounded messages publication", () => {
await rejected
expect(apiFetchMock.mock.calls[0][1].signal.aborted).toBe(true)
await act(async () => {
- resolve({ messages: [{ id: "late_message", type: "chat", seq: 1, authorId: "late_author", authorName: "Late", content: "late" }], hasMore: false, latestSeq: 1, surfaceReceipt: { channelId: "ch_deadline", surfaceKind: "channel" } })
+ resolve(messageReadPageFixture({ messages: [messageResourceFixture({ channelId: "ch_deadline", id: "late_message", type: "chat", seq: 1, authorId: "late_author", authorName: "Late", content: "late" })], hasMore: false, latestSeq: 1, surfaceReceipt: { channelId: "ch_deadline", surfaceKind: "channel" } }))
await vi.advanceTimersByTimeAsync(0)
})
const registry = getCommunityDbRegistry(client)!
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 62242264e..ead9587f2 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
@@ -1,3 +1,4 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren, Suspense, useLayoutEffect } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClientProvider } from "@tanstack/react-query"
@@ -25,7 +26,7 @@ function packet(kind: "channel" | "dm", anchor = "m1", channelId = "c1") {
messages: [{ ...value.messages[0], id: anchor, channelId, content: anchor }], page: { ...value.page, hasMoreNewer: true } }
}
function page(id: string) {
- return { messages: [{ ...conversationEntryFixture().messages[0], id, content: id, seq: 8 }], latestSeq: 8, hasMoreOlder: false, hasMoreNewer: false }
+ return messageReadPageFixture({ messages: [{ ...conversationEntryFixture().messages[0], id, content: id, seq: 8 }], latestSeq: 8, hasMoreOlder: false, hasMoreNewer: false })
}
async function setup(kind: "channel" | "dm", anchor = "m1", channelId = "c1") {
const owner = await createCommunityQueryOwner()
diff --git a/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts b/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts
index e0693a879..121a6a71b 100644
--- a/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.loading-state.dom.test.ts
@@ -1,7 +1,10 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { writeCommunityCollectionRows } from "@/lib/community-db/write"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { conversationEntryFixture, conversationEntryFromChannel, seedConversationEntry } from "@/test/conversation-entry-fixtures"
import { createCommunityQueryOwner, seedCommunityMessageWindow } from "@/test/community-query-owner"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
-import { ingestMessages } from "@/lib/community-db/sync"
+import { ingestMessages, publishCommunityMessageFields, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
import { getCommunityRuntime } from "@/stores/community/runtime"
import type { CanonicalMessage, MessageScope } from "@/lib/community/message-stream"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
@@ -16,7 +19,7 @@ import { getMessageStreamState } from "@/test/community-query-owner"
function dispatchLive(client: QueryClient, scope: MessageScope, event: { type: "wsMessage"; message: CanonicalMessage }) {
const registry = getCommunityDbRegistry(client)
if (!registry) throw new Error("Missing original message fixture owner")
- ingestMessages(registry, scope.id, [event.message])
+ ingestMessages(registry, scope.id, [messageResourceFixture({ ...event.message, channelId: scope.id })])
registry.runtime.messageStream.actions.dispatch(scope, event)
}
@@ -45,9 +48,10 @@ async function renderChannelMessages(
const queryClient = originalClient ?? (await createCommunityQueryOwner()).client
if (seedTail) {
await seedConversationEntry(queryClient, conversationEntryFromChannel({ id: "ch_new", serverId: "s1", type: "text", name: "Channel", archived: false, createdAt: "2026-10-01T00:00:00Z" }))
+ await writeCommunityCollectionRows(getCommunityDbRegistry(queryClient)!, "profiles", conversationEntryFixture().profiles, row => row.id)
seedCommunityMessageWindow(queryClient, communityKeys.channelMessages("ch_new"), {
pages: [{
- messages: seedTail.map(row => ({ ...conversationEntryFixture().messages[0], content: row.id, ...getCommunityDbRegistry(queryClient)!.collections.messages.get(row.id), ...row, resourceComplete: true as const, channelId: "ch_new" })),
+ messages: seedTail.map(row => ({ ...conversationEntryFixture().messages[0], content: row.id, ...getCommunityDbRegistry(queryClient)!.collections.messages.get(row.id), ...row, channelId: "ch_new" })),
hasMore: false,
latestSeq: seedTail.at(-1)?.seq ?? 0,
}],
@@ -65,9 +69,10 @@ async function renderChannelMessages(
async function renderDmMessages(seedTail: { id: string; seq: number }[], originalClient?: QueryClient) {
const queryClient = originalClient ?? (await createCommunityQueryOwner()).client
await seedConversationEntry(queryClient, conversationEntryFromChannel({ id: "dm_new", serverId: null, type: "dm", name: null, archived: false, createdAt: "2026-10-01T00:00:00Z" }))
+ await writeCommunityCollectionRows(getCommunityDbRegistry(queryClient)!, "profiles", conversationEntryFixture().profiles, row => row.id)
seedCommunityMessageWindow(queryClient, communityKeys.dmMessages("dm_new"), {
pages: [{
- messages: seedTail.map(row => ({ ...conversationEntryFixture().messages[0], content: row.id, ...getCommunityDbRegistry(queryClient)!.collections.messages.get(row.id), ...row, resourceComplete: true as const, channelId: "dm_new" })),
+ messages: seedTail.map(row => ({ ...conversationEntryFixture().messages[0], content: row.id, ...getCommunityDbRegistry(queryClient)!.collections.messages.get(row.id), ...row, channelId: "dm_new" })),
hasMore: false,
latestSeq: seedTail.at(-1)?.seq ?? 0,
}],
@@ -104,15 +109,15 @@ describe("useMessages — instant channel switch", () => {
const scope: MessageScope = kind === "channel" ? { kind, id: "ch_new", serverId: "s1" } : { kind, id: "dm_new" }
const attachments = [{ id: "attachment", name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, thumbnailUrl: null, contentType: "text/plain", width: null, height: null }]
const presentedAttachments = [{ name: "notes.txt", url: "/notes.txt", sizeBytes: 1024, contentType: "text/plain", kind: "file", size: "1.0 KB" }]
- const embeds = [{ title: "Existing embed" }], replyTo = { id: "reply", authorName: "Peer", text: "reply" }
+ const embeds = [{ title: "Existing embed" }], replyTo = { id: "reply", authorId: "peer", authorName: "Peer", text: "reply" }
const message: CanonicalMessage = { id: "rich", seq: 3, type: "chat", authorId: "peer", authorName: "Peer", content: "before", clientNonce: "rich-nonce", createdAt: "2026-08-07T10:00:00.000Z" }
- ingestMessages(registry, scope.id, [{ ...message, attachments, embeds, replyTo }])
+ ingestMessages(registry, scope.id, [messageResourceFixture({ ...message, channelId: scope.id, replyToId: "reply", attachments, embeds, replyTo })])
const rendered = kind === "channel" ? await renderChannelMessages(undefined, [{ id: message.id, seq: message.seq }], client) : await renderDmMessages([{ id: message.id, seq: message.seq }], client)
expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, attachments: presentedAttachments, embeds, replyTo })])
- await act(async () => { dispatchLive(client, scope, { type: "wsMessage", message: { ...message, content: "sparse live" } }) })
- expect(registry.collections.messages.get(message.id)).toMatchObject({ content: "sparse live", attachments, embeds, replyTo })
- expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, content: "sparse live", attachments: presentedAttachments, embeds, replyTo })])
- await act(async () => { dispatchLive(client, scope, { type: "wsMessage", message: { ...message, resourceComplete: true, channelId: scope.id, replyToId: "reply", content: "cleared", attachments: [], embeds: [] } }) })
+ await act(async () => { publishCommunityMessageFields(client, message.id, { content: "content patch" }, { token: captureCommunityLiveSnapshotToken(client, scope.id) }) })
+ expect(registry.collections.messages.get(message.id)).toMatchObject({ content: "content patch", attachments, embeds, replyTo })
+ expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, content: "content patch", attachments: presentedAttachments, embeds, replyTo })])
+ await act(async () => { dispatchLive(client, scope, { type: "wsMessage", message: { ...message, channelId: scope.id, replyToId: "reply", content: "cleared", attachments: [], embeds: [] } }) })
expect(registry.collections.messages.get(message.id)).toMatchObject({ attachments: [], embeds: [] })
expect(rendered.result.current.messages, JSON.stringify(rendered.result.current.messages)).toEqual([expect.objectContaining({ id: message.id, content: "cleared", attachments: [], embeds: [], replyTo })])
expect(apiFetchMock).not.toHaveBeenCalled()
diff --git a/src/web/src/hooks/community/use-messages.observation.dom.test.ts b/src/web/src/hooks/community/use-messages.observation.dom.test.ts
index 32c6eac45..87326d127 100644
--- a/src/web/src/hooks/community/use-messages.observation.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.observation.dom.test.ts
@@ -2,7 +2,7 @@ import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures
import { createElement, type PropsWithChildren } from "react"
import { ROOT_CONTEXT, SpanKind, context, trace } from "@opentelemetry/api"
import { InMemorySpanExporter, SimpleSpanProcessor, WebTracerProvider } from "@opentelemetry/sdk-trace-web"
-import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { afterEach, expect, it, vi } from "vitest"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
@@ -41,8 +41,8 @@ it.each(["channel", "dm"] as const)("keeps real %s API events and native spans o
span.end()
const entry = conversationEntryFromChannel({ id: "channel-a", serverId: kind === "channel" ? "server-a" : null, type: kind === "channel" ? "text" : "dm", name: null, archived: false, createdAt: "2026-10-01T00:00:00Z" })
return Response.json(new URL(url, "https://example.test").searchParams.has("entry") ? entry : {
- contractVersion: COMMUNITY_CONTRACT_VERSION, channelId: entry.channelId, messages: entry.messages, page: entry.page, surfaceReceipt: entry.surfaceReceipt,
- }, { headers: { [COMMUNITY_CONTRACT_HEADER]: new URL(url, "https://example.test").searchParams.has("entry") ? "3" : String(COMMUNITY_CONTRACT_VERSION) } })
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: entry.channelId, profiles: entry.profiles, messages: entry.messages, page: entry.page, surfaceReceipt: entry.surfaceReceipt,
+ }, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
}))
const href = kind === "channel" ? "/c/channels/server-a/channel-a" : "/c/me/channel-a"
diff --git a/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx b/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
index 1a087e778..7385e6207 100644
--- a/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
+++ b/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
@@ -1,3 +1,4 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClientProvider } from "@tanstack/react-query"
@@ -69,7 +70,7 @@ describe("returned entry and selected message window", () => {
expect(hook.result.current.positionDataState).toBe("pending")
expect(hook.result.current.initialPositionKnown).toBe(true)
expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
- await act(async () => late.resolve({ messages: fresh.messages, latestSeq: 2, hasMoreNewer: false }))
+ await act(async () => late.resolve(messageReadPageFixture({ messages: fresh.messages, latestSeq: 2, hasMoreNewer: false })))
await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))
} finally { hook.unmount() }
})
@@ -104,14 +105,14 @@ describe("returned entry and selected message window", () => {
fresh.channel.messageCount = 13
fresh.channel.lastMessageAt = fresh.messages.at(-1)!.createdAt
fresh.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 13 }
- await act(async () => ingestMessages(registry, "c1", fresh.messages.map(message => ({ ...message, resourceComplete: true }))))
- expect(fresh.messages.every(message => registry.collections.messages.get(message.id)?.resourceComplete === true)).toBe(true)
+ await act(async () => ingestMessages(registry, "c1", fresh.messages))
+ expect(fresh.messages.every(message => registry.collections.messages.has(message.id))).toBe(true)
const response = deferred<ReturnType<typeof fixture>>()
load.mockImplementation((url: string) => {
const search = new URL(url, "https://example.test").searchParams
if (search.has("entry")) return response.promise
- if (search.has("since")) return Promise.resolve({ ...fresh.page, messages: fresh.messages.slice(1) })
- if (search.size === 0) return Promise.resolve({ ...fresh.page, messages: fresh.messages })
+ if (search.has("since")) return Promise.resolve({ ...fresh.page, profiles: fresh.profiles, messages: fresh.messages.slice(1) })
+ if (search.size === 0) return Promise.resolve({ ...fresh.page, profiles: fresh.profiles, messages: fresh.messages })
throw new Error(`Unexpected message window ${url}`)
})
vi.spyOn(Date, "now").mockReturnValue(Date.now() + 6000)
@@ -127,7 +128,7 @@ describe("returned entry and selected message window", () => {
const expectedIds = fresh.messages.map(message => message.id)
const anchorKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
expect(client.getQueryData<MessageWindowData>(anchorKey)?.pages.flatMap(page => page.messages.map(message => message.id))).toEqual(expectedIds)
- expect(expectedIds.every(id => registry.collections.messages.get(id)?.resourceComplete === true)).toBe(true)
+ expect(expectedIds.every(id => registry.collections.messages.has(id))).toBe(true)
expect(returned.result.current.readSnapshot?.lastReadMessageId).toBe("m1")
expect(returned.result.current.readSnapshot?.lastReadSeq).toBe(1)
expect(returned.result.current.initialPositionKnown).toBe(true)
@@ -172,7 +173,7 @@ describe("returned entry and selected message window", () => {
load.mockImplementation((url: string) => {
const search = new URL(url, "https://example.test").searchParams
if (search.has("entry")) return entry.promise
- if (search.has("since")) return Promise.resolve({ ...fresh.page, messages: fresh.messages.slice(1) })
+ if (search.has("since")) return Promise.resolve({ ...fresh.page, profiles: fresh.profiles, messages: fresh.messages.slice(1) })
if (search.size === 0) return oldWindow.promise
throw new Error(`Unexpected message window ${url}`)
})
@@ -194,7 +195,7 @@ describe("returned entry and selected message window", () => {
const anchorKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
expect(client.getQueryData<MessageWindowData>(anchorKey)?.pages[0].messages).toHaveLength(13)
await act(async () => {
- oldWindow.resolve({ messages: old.messages, latestSeq: 1, hasMoreNewer: false })
+ oldWindow.resolve(messageReadPageFixture({ messages: old.messages, latestSeq: 1, hasMoreNewer: false }))
await olderRepair
})
expect(client.getQueryCache().find({ queryKey: key, exact: true })).toBe(owner)
@@ -217,7 +218,7 @@ describe("returned entry and selected message window", () => {
})
expect(signal.aborted).toBe(true)
const lateMessage = { ...fresh.messages[0], id: "late_m3", seq: 3 }
- await act(async () => late.resolve({ messages: [...fresh.messages, lateMessage], latestSeq: 3, hasMoreNewer: false }))
+ await act(async () => late.resolve(messageReadPageFixture({ messages: [...fresh.messages, lateMessage], latestSeq: 3, hasMoreNewer: false })))
expect(registry.collections.messages.get("late_m3")).toBeUndefined()
expect(client.getQueryData<MessageWindowData>(key)?.pages.flatMap(page => page.messages.map(message => message.id)) ?? []).not.toContain("late_m3")
if (kind !== "unmount") hook.unmount()
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index b3fdab0c9..a502f8b16 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -20,7 +20,7 @@ import type { Msg } from "@/lib/community/models/message"
import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"
import { ConversationReadTimeoutError, withConversationReadDeadline } from "@/lib/community/conversation-read"
import { messageReconcileOptions } from "./community-ws/reconnect-messages"
-import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
export { channelMessagesQueryFn } from "@/lib/community/message-window"
export type { MessagesPage, MessagesPageParam } from "@/lib/community/models/message"
@@ -91,8 +91,8 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const anchorMessageId = opts?.anchorMessageId ?? null
const entry = useConversationEntry(channelId && opts?.enabled !== false ? { channelId, serverId, anchorMessageId, tag } : null)
const proof = entry.scope?.proof
- const positionScope = useMemo<VirtualListPositionScope | undefined>(() => entry.canRead && proof
- ? { proof, kind: "messages", tag } : undefined, [entry.canRead, proof, tag])
+ const positionScope = useMemo<ConversationListScope | undefined>(() => entry.canRead && proof
+ ? { proof, tag } : undefined, [entry.canRead, proof, tag])
const viewKey = hashKey([channelId, serverId, anchorMessageId, tag, proof?.accountEpoch ?? -1, proof?.accessEpoch ?? -1,
channelId ? proof?.channelScopes.get(channelId)?.generation ?? 0 : 0])
const present = useMemo(() => ({ viewKey, intent: entry.intent,
@@ -127,6 +127,8 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const originalQuery = client.getQueryCache().find({ queryKey, exact: true })
const owner = useMemo(() => ({ present, retries, query: originalQuery, enabled: enabled && presented }), [present, retries, originalQuery, enabled, presented])
const committed = useRef<typeof owner | null>(null)
+ const committedWindowReady = useRef(entry.windowReady)
+ useLayoutEffect(() => { committedWindowReady.current = entry.windowReady }, [entry.windowReady])
useLayoutEffect(() => {
committed.current = owner
return () => { if (committed.current === owner) committed.current = null }
@@ -177,7 +179,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const hasMoreNewer = newest?.hasMoreNewer ?? false
const fetchPage = useCallback((direction: "older" | "newer"): MessageRequest => {
const original = committed.current
- if (!channelId || !original?.enabled || !original.query || original !== owner) return { accepted: false }
+ if (!channelId || !original?.enabled || !original.query || original !== owner || !committedWindowReady.current) return { accepted: false }
if (direction === "older" ? !query.hasNextPage || query.isFetchingNextPage : !query.hasPreviousPage || query.isFetchingPreviousPage) return { accepted: false }
const token = captureChannelMetadataToken(client, channelId)
const isCurrent = () => committed.current === original && isChannelMetadataTokenCurrent(token)
@@ -196,7 +198,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const fetchNewer = useCallback(() => fetchPage("newer"), [fetchPage])
const jumpToPresent = useCallback((): MessageRequest => {
const original = committed.current
- if (!channelId || !original?.enabled || original !== owner || present.get().pending) return { accepted: false }
+ if (!channelId || !original?.enabled || original !== owner || !committedWindowReady.current || present.get().pending) return { accepted: false }
const token = captureChannelMetadataToken(client, channelId)
const tail = messageWindowOptions(client, channelId, { mode: "newest" }, tag, { observation })
const captured = client.getQueryCache().build<unknown, Error, unknown>(client, { queryKey: tail.queryKey })
@@ -255,7 +257,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
isFetchingNewer: query.isFetchingPreviousPage || selection.pending,
fetchOlder, fetchNewer, jumpToPresent, presentVersion: selection.version, presentRequest: selection.request,
anchorReconciled: entry.targetCovered || !!selection.window,
- navigationBlocked: !entry.canRead,
+ navigationBlocked: !entry.windowReady,
readSnapshot: entry.snapshot, readSnapshotFetching,
initialPositionKnown: windowAvailable && entry.snapshot !== null && !loading && !missingCanonical && !initialLoadError && !retrySelection.pending && !entry.initialPositionPending,
initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow: query.data,
diff --git a/src/web/src/hooks/community/use-messages.window.dom.test.tsx b/src/web/src/hooks/community/use-messages.window.dom.test.tsx
index 1a8b8f3f2..b3350c90f 100644
--- a/src/web/src/hooks/community/use-messages.window.dom.test.tsx
+++ b/src/web/src/hooks/community/use-messages.window.dom.test.tsx
@@ -1,3 +1,4 @@
+import { messageReadPageFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { createElement, type PropsWithChildren } from "react"
import { QueryClientProvider } from "@tanstack/react-query"
@@ -22,7 +23,7 @@ function deferred<T>() {
}
function page(id: string, seq: number, more = false): MessagesPage {
const row = fixture().messages[0]
- return { messages: [{ ...row, resourceComplete: true, id, seq, content: id }], latestSeq: seq, hasMoreOlder: more, hasMoreNewer: false, olderCursor: more ? "older" : undefined }
+ return messageReadPageFixture({ messages: [{ ...row, id, seq, content: id }], latestSeq: seq, hasMoreOlder: more, hasMoreNewer: false, olderCursor: more ? "older" : undefined })
}
async function setup() {
const owner = await createCommunityQueryOwner()
diff --git a/src/web/src/hooks/community/use-reaction-details.dom.test.ts b/src/web/src/hooks/community/use-reaction-details.dom.test.ts
index 75a99cdde..3827b7676 100644
--- a/src/web/src/hooks/community/use-reaction-details.dom.test.ts
+++ b/src/web/src/hooks/community/use-reaction-details.dom.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient } from "@tanstack/react-query"
import { CommunityTestProvider } from "@/test/community-owner-fixture"
@@ -45,6 +46,9 @@ function wrapperFor(queryClient: QueryClient) {
type ReactionProps = { open: boolean; userIds: string[] }
function renderReactionHook(queryClient: QueryClient, initialProps: ReactionProps) {
+ const registry = getCommunityDbRegistry(queryClient)!
+ registry.collections.channels.utils.writeUpsert({ ...channelResourceFixture({ id: "channel_1", serverId: "server_1" }), muted: false, pending: false, tags: [] })
+ registry.collections.messages.utils.writeUpsert(messageResourceFixture({ id: "message_1", channelId: "channel_1" }))
return renderHook(
({ open, userIds }: ReactionProps) => useReactionDetails({
messageId: "message_1",
@@ -153,3 +157,23 @@ describe("useReactionDetails", () => {
expect(apiFetchProfiles).not.toHaveBeenCalled()
})
})
+
+it.each(["missing-later-core", "wrong-actor", "wrong-message", "wrong-scope"])("refuses a malformed named reaction identity subset %s before patching", async defect => {
+ const { communityRegistrySnapshot } = await import("@/test/community-registry-snapshot")
+ const { client, registry } = await createCommunityQueryOwner()
+ const initial = envelope(["first", "second"])
+ apiFetchProfiles.mockResolvedValueOnce(initial)
+ const hook = renderReactionHook(client, { open: true, userIds: ["first", "second"] })
+ await waitFor(() => expect(hook.result.current.data?.actors).toHaveLength(2))
+ const before = communityRegistrySnapshot(registry)
+ const malformed = structuredClone(initial)
+ malformed.actors[0]!.profile!.name = "Must not publish"
+ if (defect === "missing-later-core") delete (malformed.actors[1]!.profile as Partial<NonNullable<ReactionDetailsEnvelope["actors"][number]["profile"]>>).avatarVersion
+ if (defect === "wrong-actor") malformed.actors[1]!.profile!.id = "foreign"
+ if (defect === "wrong-message") malformed.messageId = "foreign"
+ if (defect === "wrong-scope") malformed.scope.channelId = "foreign"
+ apiFetchProfiles.mockResolvedValueOnce(malformed)
+ await act(async () => { await expect(hook.result.current.refetch({ throwOnError: true })).rejects.toThrow() })
+ expect(communityRegistrySnapshot(registry)).toEqual(before)
+ hook.unmount()
+})
diff --git a/src/web/src/hooks/community/use-reaction-details.ts b/src/web/src/hooks/community/use-reaction-details.ts
index 1d1d71064..626721348 100644
--- a/src/web/src/hooks/community/use-reaction-details.ts
+++ b/src/web/src/hooks/community/use-reaction-details.ts
@@ -1,8 +1,9 @@
"use client"
+import { parseCommunityReactionDetailsRead, type CommunityReactionDetailsRead, type CommunityReactionActorProfile } from "@alook/shared"
import { createStore } from "@tanstack/react-store"
import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { useCommunityViewSource } from "./use-community-view-source"
-import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
@@ -12,30 +13,23 @@ import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-quer
import { apiFetchProfiles, communityUserProfilePatch } from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
-export type ReactionDetailsProfile = {
- id: string
- name: string
- discriminator: string
- avatar: string
- avatarVersion: number
-}
-
-export type ReactionDetailsEnvelope = {
- messageId: string
- scope:
- | { kind: "server"; serverId: string; channelId: string }
- | { kind: "dm"; channelId: string }
- actors: Array<{
- userId: string
- profile: ReactionDetailsProfile | null
- }>
-}
+export type ReactionDetailsProfile = CommunityReactionActorProfile
+export type ReactionDetailsEnvelope = CommunityReactionDetailsRead
const loadReactionDetails = async (queryClient: QueryClient, messageId: string, signal: AbortSignal) => {
const original = captureCommunityLiveSnapshotToken(queryClient)
+ const registry = original.registry
+ if (!registry) throw new DOMException("Missing reaction owner", "AbortError")
+ await registry.ready
+ await Promise.all([registry.collections.messages.preload(), registry.collections.channels.preload()])
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, original, signal)
+ const message = registry.collections.messages.get(messageId)
+ const channel = message ? registry.collections.channels.get(message.channelId) : undefined
+ if (!message || !channel || channel.type !== "dm" && !channel.serverId) throw new Error("Missing reaction request scope")
+ const scope: CommunityReactionDetailsRead["scope"] = channel.type === "dm" ? { kind: "dm", channelId: channel.id } : { kind: "server", channelId: channel.id, serverId: channel.serverId! }
const data = await apiFetchProfiles<ReactionDetailsEnvelope>(
`/api/community/messages/${messageId}/reactions`,
- (data) => data.actors.flatMap((actor) => actor.profile ? [communityUserProfilePatch(actor.userId, actor.profile)] : []),
+ (data) => parseCommunityReactionDetailsRead(data, messageId, scope).actors.flatMap((actor) => actor.profile ? [communityUserProfilePatch(actor.userId, actor.profile)] : []),
communityRequestOptions(queryClient, original, signal), original.registry,
)
return { messageId: data.messageId, scope: data.scope, actors: data.actors.map((actor) => ({ userId: actor.userId, profilePresent: !!actor.profile })) }
diff --git a/src/web/src/hooks/community/use-read-observer.dom.test.ts b/src/web/src/hooks/community/use-read-observer.dom.test.ts
index 63eacc878..6190d74f6 100644
--- a/src/web/src/hooks/community/use-read-observer.dom.test.ts
+++ b/src/web/src/hooks/community/use-read-observer.dom.test.ts
@@ -1,3 +1,4 @@
+import { messageSeedFixture } from "@/test/community-resource-fixtures"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createElement, type PropsWithChildren } from "react"
@@ -189,7 +190,7 @@ function useTestRender(options: Partial<Parameters<typeof useTimelineReadObserve
scrollRootEl: root, snapshotStatus: "ready", feedStatus: "ready", tailAttached: true,
confirmedSeq: 2, catchUp: () => Promise.resolve(), ...options,
}
- act(() => ingestMessages(owner.registry, props.channelId ?? "channel-1", props.messages.map((message) => ({ ...message, type: "chat" }))))
+ act(() => ingestMessages(owner.registry, props.channelId ?? "channel-1", messageSeedFixture(props.channelId ?? "channel-1", props.messages.map((message) => ({ ...message, type: "chat" })))))
if (refState.persistent && activeView) activeView.rerender(props)
else {
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer-1", retainOwner: true }, children)
@@ -310,7 +311,7 @@ describe("useTimelineReadObserver", () => {
confirmedSeq: 2,
catchUp: () => Promise.resolve(),
}
- act(() => ingestMessages(owner.registry, channelId, props.messages))
+ act(() => ingestMessages(owner.registry, channelId, messageSeedFixture(channelId, props.messages)))
const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "viewer-1", retainOwner: true }, children)
const view = kind === "channel"
? renderHook(useChannelWatermark, { wrapper, initialProps: props })
diff --git a/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
index d10644885..a10c03682 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
@@ -2,91 +2,149 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent } from "@/test/react-dom-harness"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
-import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
-import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
+import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
-describe("native snapshot restoration and one-shot late unread ownership", () => {
- it.each([false, true])("keeps the saved body offset when prepend changes an unsettled restore index (StrictMode=%s)", async strict => {
+describe("ordinary reconstruction and one-shot late unread ownership", () => {
+ it.each([false, true])("uses normal entry rules after deep browsing (StrictMode=%s)", async strict => {
const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
- const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
- const original = mount({ positionScope, items }, strict)
- original.move(800)
- const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))!
- const anchorId = String(snapshot.anchorKey).slice(4)
- const top = bodyTop(original.root, anchorId)
- original.view.unmount()
- const restored = mount({ positionScope, items }, strict, undefined, undefined, 0)
- scrollFixture.bodyHeights.set(anchorId, 0)
- resize(1)
- expect(scrollFixture.latest.readPositionReady).toBe(false)
+ const positionScope: ConversationListScope = { proof: captureChannelMetadataToken(client, "A"), tag: null }
+ const items = Array.from({ length: 180 }, (_, index) => message(`m${index}`))
+ for (const source of ["tail", "read", "new", "explicit"] as const) {
+ const original = mount({ positionScope, items }, strict)
+ original.move(1800)
+ const offset = original.root.scrollTop
+ expect(offset).toBe(1800)
+ original.view.unmount()
+ const returned = mount({ positionScope, items,
+ ...(source === "read" || source === "explicit" ? { initialPositionMessageId: "m120" } : {}),
+ ...(source === "new" || source === "explicit" ? { newDividerBefore: "m100" } : {}),
+ ...(source === "explicit" ? { scrollToMessageId: "m80" } : {}),
+ }, strict)
+ const native = scrollFixture.latest.virtualizer
+ expect(returned.root.scrollTop).not.toBe(offset)
+ if (source === "tail") expect(returned.root.scrollHeight - returned.root.clientHeight - returned.root.scrollTop).toBeLessThanOrEqual(1)
+ else {
+ const id = source === "read" ? "m120" : source === "new" ? "m100" : "m80"
+ const index = native.getVirtualItems().find(row => row.key === `msg:${id}`)!.index
+ expect(returned.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(index, "center")![0], 0)
+ }
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ returned.view.unmount()
+ }
+ })
+
+ it.each([false, true])("waits for cached rows and uses the qualified read target on reconstruction (StrictMode=%s)", async strict => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: ConversationListScope = { proof: captureChannelMetadataToken(client, "A"), tag: null }
+ const items = Array.from({ length: 180 }, (_, index) => message(`m${index}`))
+ const first = mount({ positionScope, items }, strict)
+ first.move(1800)
+ first.view.unmount()
+ const returned = mount({ positionScope, items: [], initialScrollReady: false, positionDataState: "pending" }, strict)
expect(scrollFixture.latest.positionOutcome).toBe("pending")
- restored.stage({ items: [message("prepended"), ...items] })
- runFrames(1)
expect(scrollFixture.latest.readPositionReady).toBe(false)
- scrollFixture.bodyHeights.set(anchorId, 100)
- resize()
- expect(bodyTop(restored.root, anchorId)).toBeCloseTo(top, 0)
- expect(restored.root.querySelector(`[data-msg-id="${anchorId}"]`)!.closest<HTMLElement>("[data-message-row-key]")!.dataset.messageRowKey).toBe(snapshot.anchorKey)
+ returned.update({ items, initialPositionMessageId: "m120", initialScrollReady: true, positionDataState: "ready" })
+ const native = scrollFixture.latest.virtualizer
+ const index = native.getVirtualItems().find(row => row.key === "msg:m120")!.index
+ expect(returned.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(index, "center")![0], 0)
expect(scrollFixture.latest.positionOutcome).toBe("success")
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it.each([false, true])("restores a destroyed instance from its own measured snapshot (StrictMode=%s)", async strict => {
- const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
- const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
- const h = mount({ positionScope, items }, strict)
- h.move(800)
+
+ it("does not mount the whole cached history in the first committed viewport", () => {
+ let firstCount: number | undefined
+ const h = mount({ items: Array.from({ length: 180 }, (_, index) => message(`m${index}`)) }, false,
+ () => { firstCount ??= document.querySelectorAll('[data-testid="scroll"] [data-index]').length }, undefined, 0)
+ expect(firstCount).toBeGreaterThan(0)
+ expect(firstCount).toBeLessThan(60)
resize()
- const before = h.root.scrollTop
- const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))
- expect(snapshot?.offset).toBe(before)
- expect(snapshot!.measurements.length).toBeGreaterThan(0)
- h.view.unmount()
- const restored = mount({ positionScope, items }, strict)
- expect(scrollFixture.latest.virtualizer.options.initialMeasurementsCache.length).toBeGreaterThan(0)
- expect(scrollFixture.latest.virtualizer.options.initialOffset).toBe(before)
- expect(restored.root.scrollTop).toBeCloseTo(before, 0)
+ expect(h.root.querySelectorAll('[data-index]').length).toBeLessThan(60)
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
+ })
+
+ it("settles an ordinary read target whose row has overflowing content", () => {
+ scrollFixture.bodyHeights.set("m120", 400)
+ scrollFixture.overflowHeights.set("m120", 967)
+ const h = mount({ items: Array.from({ length: 180 }, (_, index) => message(`m${index}`)), initialPositionMessageId: "m120" })
+ const row = h.root.querySelector<HTMLElement>('[data-msg-id="m120"]')!.closest<HTMLElement>('[data-index]')!
+ expect(row.getBoundingClientRect().height).toBe(400)
+ expect(row.scrollHeight).toBe(967)
expect(scrollFixture.latest.positionOutcome).toBe("success")
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it.each([false, true])("restores 600px from tail when cached rows arrive after the initial mount (StrictMode=%s)", async strict => {
- const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
- const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
- const first = mount({ positionScope, items }, strict)
- first.move(first.root.scrollHeight - first.root.clientHeight - 600)
- resize()
- const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))!
- const id = String(snapshot.anchorKey).slice(4)
- const before = bodyTop(first.root, id)
- const offset = first.root.scrollTop
- expect(first.root.scrollHeight - first.root.clientHeight - offset).toBe(600)
- first.view.unmount()
- const returned = mount({ positionScope, items: [], initialScrollReady: false, positionDataState: "pending" }, strict)
+ it.each([
+ { source: "tail", overflow: 967 },
+ { source: "read", overflow: 2000 },
+ { source: "target", overflow: 2000 },
+ { source: "new", overflow: 2000 },
+ { source: "new-fallback", overflow: 2000 },
+ ] as const)("settles $source using actual overflowing content within its native landing", ({ source, overflow }) => {
+ const id = source === "tail" ? "m179" : "m120"
+ scrollFixture.bodyHeights.set(id, 400)
+ scrollFixture.overflowHeights.set(id, overflow)
+ const items = Array.from({ length: 180 }, (_, index) => ({ ...message(`m${index}`),
+ ...(source === "new" && index === 120 ? { newDivider: true } : {}),
+ }))
+ const h = mount({ items,
+ ...(source === "read" ? { initialPositionMessageId: id } : {}),
+ ...(source === "target" ? { scrollToMessageId: id } : {}),
+ ...(source === "new" || source === "new-fallback" ? { newDividerBefore: id } : {}),
+ })
+ const body = h.root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!
+ const rect = body.getBoundingClientRect()
+ expect(h.root.clientHeight).toBe(500)
+ expect(rect.height).toBe(400)
+ expect(body.scrollHeight).toBe(overflow)
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ const native = scrollFixture.latest.virtualizer
+ if (source === "tail") expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ else {
+ const key = source === "new" ? "divider:msg:m120" : `msg:${id}`
+ const index = native.getVirtualItems().find(item => item.key === key)!.index
+ expect(h.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(index, "center")![0], 0)
+ }
+ expect(rect.top).toBeLessThan(500)
+ expect(rect.top + body.scrollHeight).toBeGreaterThan(0)
+ if (source === "new") {
+ const marker = h.root.querySelector<HTMLElement>('[data-new-divider]')!.getBoundingClientRect()
+ expect(marker.top).toBeGreaterThanOrEqual(0)
+ expect(marker.bottom).toBeLessThanOrEqual(500)
+ }
+ })
+
+ it("does not accept clipped offscreen content as a visible target", () => {
+ scrollFixture.bodyHeights.set("m120", 400)
+ scrollFixture.overflowHeights.set("m120", 2000)
+ scrollFixture.overflowModes.set("m120", "hidden")
+ const h = mount({ items: Array.from({ length: 180 }, (_, index) => message(`m${index}`)), initialPositionMessageId: "m120" })
+ const body = h.root.querySelector<HTMLElement>('[data-msg-id="m120"]')!
+ expect(body.getBoundingClientRect().bottom).toBeLessThan(0)
+ expect(scrollFixture.latest.positionOutcome).toBe("pending")
expect(scrollFixture.latest.readPositionReady).toBe(false)
- expect(client.getQueryData(virtualListPositionKey(positionScope))).toBe(snapshot)
- returned.update({ items, initialScrollReady: true, positionDataState: "ready" })
- expect(returned.root.scrollTop).toBeCloseTo(offset, 0)
- expect(bodyTop(returned.root, id)).toBeCloseTo(before, 0)
+ scrollFixture.overflowModes.set("m120", "visible")
+ h.update({ items: [...h.input.items] })
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("does not restore a late snapshot after real manual takeover", async () => {
+ it("keeps manual takeover when delayed cached data becomes ready", async () => {
const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
- const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
+ const positionScope: ConversationListScope = { proof: captureChannelMetadataToken(client, "A"), tag: null }
+ const items = Array.from({ length: 180 }, (_, index) => message(`m${index}`))
const first = mount({ positionScope, items })
- first.move(800)
+ first.move(1800)
first.view.unmount()
const returned = mount({ positionScope, items: [], initialScrollReady: false, positionDataState: "pending" })
const jump = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
fireEvent.wheel(returned.root, { deltaY: -10 })
- returned.update({ items, initialScrollReady: true, positionDataState: "pending" })
+ returned.update({ items, initialPositionMessageId: "m120", initialScrollReady: true, positionDataState: "pending" })
expect(jump).not.toHaveBeenCalled()
expect(scrollFixture.latest.positionOutcome).toBe("user-cancelled")
expect(scrollFixture.latest.readPositionReady).toBe(false)
@@ -95,31 +153,6 @@ describe("native snapshot restoration and one-shot late unread ownership", () =>
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it.each(["other-channel", "other-account", "changed-rows", "changed-width", "explicit-target"] as const)("does not restore stale pixels for %s", async mode => {
- const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
- const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
- const h = mount({ positionScope, items })
- h.move(600)
- resize()
- h.view.unmount()
- const otherClient = mode === "other-account" ? (await createCommunityQueryOwner("other")).client : client
- const scope = mode === "other-channel" || mode === "other-account"
- ? { ...positionScope, proof: captureChannelMetadataToken(otherClient, mode === "other-channel" ? "B" : "A") } : positionScope
- if (mode === "changed-width") scrollFixture.width = 600
- const restored = mount({ positionScope: scope,
- items: mode === "changed-rows" ? items.map((item, index) => index === 1 ? { ...item, m: { ...item.m, content: "Edited body" } } : item) : items,
- ...(mode === "explicit-target" ? { scrollToMessageId: "m5" } : {}),
- })
- const native = scrollFixture.latest.virtualizer
- if (mode === "explicit-target") {
- const index = native.getVirtualItems().find(row => row.key === "msg:m5")!.index
- expect(restored.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(index, "center")![0], 0)
- } else expect(restored.root.scrollHeight - restored.root.clientHeight - restored.root.scrollTop).toBeLessThanOrEqual(1)
- expect(scrollFixture.latest.positionOutcome).toBe("success")
- expect(scrollFixture.latest.readPositionReady).toBe(true)
- })
-
it("centers the first late NEW once while data is pending and never restarts it for later boundaries", () => {
const h = mount({ initialPositionMessageId: "m4", positionDataState: "pending" })
const native = scrollFixture.latest.virtualizer
diff --git a/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts
index 7bb37a81f..57f265c8e 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts
@@ -1,9 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act } from "@/test/react-dom-harness"
-import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
-import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
-import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
@@ -87,25 +84,16 @@ describe("current ready-window target retirement through the native position own
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("cancels a restored anchor removed from a ready window before its command is issued", async () => {
- const { client } = await createCommunityQueryOwner()
- const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ it("cancels an ordinary read target removed before its command is issued", () => {
const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
- const first = mount({ positionScope, items })
- first.move(800)
- resize()
- const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))!
- first.view.unmount()
const settled = vi.fn()
- const restored = mount({ positionScope, items, onInitialPositionSettled: settled }, false, undefined, undefined, 0)
- const native = scrollFixture.latest.virtualizer
- expect(native.options.initialMeasurementsCache.length).toBeGreaterThan(0)
- const index = vi.spyOn(native, "scrollToIndex")
- restored.update({ positionDataState: "ready", items: items.filter(item => item.key !== snapshot.anchorKey) })
+ const h = mount({ items, initialPositionMessageId: "m5", onInitialPositionSettled: settled }, false, undefined, undefined, 0)
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ h.update({ positionDataState: "ready", items: items.filter(item => item.key !== "msg:m5") })
expect(index).not.toHaveBeenCalled()
expect(settled).toHaveBeenCalledExactlyOnceWith("cancelled")
expect(scrollFixture.latest.readPositionReady).toBe(false)
- restored.update({ items })
+ h.update({ items })
expect(index).not.toHaveBeenCalled()
expect(settled).toHaveBeenCalledOnce()
expect(scrollFixture.latest.readPositionReady).toBe(false)
diff --git a/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts
index aed38f067..abdd69e81 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts
@@ -4,7 +4,6 @@ import { configureTelemetry, installTelemetrySink, retireTelemetry } from "@/lib
import { installMessageScrollFixture, restoreMessageScrollFixture, mount, message, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
-import { virtualListPositionKey, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
let events: Array<{ name: string; attributes: Record<string, string> }>
beforeEach(() => {
@@ -22,7 +21,7 @@ it("finishes a covered local target while newer continuity remains pending witho
expect(positioned).toHaveBeenCalledExactlyOnceWith("m4")
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(scrollFixture.latest.paginationEnabled).toBe(false)
- expect(terminals()).toContainEqual(expect.objectContaining({ position_owner: "target", position_reason: "settled", target_coverage: "covered", position_source: "explicit_target", position_snapshot: "not_requested" }))
+ expect(terminals()).toContainEqual(expect.objectContaining({ position_owner: "target", position_reason: "settled", target_coverage: "covered", position_source: "explicit_target" }))
const count = terminals().length
h.update({ positionDataState: "ready" })
runFrames()
@@ -44,7 +43,7 @@ it("records an explicit imperative jump even when no target-consumed callback is
mount()
act(() => scrollFixture.latest.jumpTo("m4", "auto"))
runFrames()
- expect(terminals().at(-1)).toMatchObject({ position_owner: "target", position_source: "explicit_target", position_snapshot: "not_requested", position_reason: "settled" })
+ expect(terminals().at(-1)).toMatchObject({ position_owner: "target", position_source: "explicit_target", position_reason: "settled" })
})
it("retires an absent ready target without geometry or a false successful finish", () => {
@@ -70,82 +69,30 @@ it.each(["manual", "hidden", "entry", "unmount"] as const)("records %s retiremen
expect(terminals().some(event => event.position_reason === "settled")).toBe(false)
})
-it.each(["valid", "missing", "fingerprint", "viewport", "padding", "anchor", "expired", "version"] as const)("records actual snapshot admission for %s without exporting its values", async state => {
- const { client } = await createCommunityQueryOwner()
- const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }
- const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
- const first = mount({ items, positionScope })
- first.move(800)
- const key = virtualListPositionKey(positionScope)
- const snapshot = client.getQueryData<VirtualListPositionSnapshot>(key)!
- expect(snapshot.offset).toBe(800)
- first.view.unmount()
- events.length = 0
- if (state === "missing") client.removeQueries({ queryKey: key, exact: true })
- else if (state === "viewport") scrollFixture.width += 1
- else if (state !== "valid") client.setQueryData(key, { ...snapshot,
- ...(state === "fingerprint" ? { fingerprint: "PRIVATE-position-fingerprint" } : {}),
- ...(state === "padding" ? { paddingEnd: snapshot.paddingEnd + 1 } : {}),
- ...(state === "anchor" ? { anchorKey: "PRIVATE-position-anchor" } : {}),
- ...(state === "expired" ? { at: Date.now() - 300001 } : {}),
- ...(state === "version" ? { version: 2 } : {}),
- })
- const restored = mount({ items, positionScope })
- const expected = { valid: "accepted", missing: "missing", fingerprint: "fingerprint_mismatch", viewport: "viewport_mismatch",
- padding: "padding_mismatch", anchor: "anchor_missing", expired: "expired", version: "invalid_version" }[state]
- expect(terminals()).toEqual([expect.objectContaining({ position_owner: "initial", position_reason: "settled",
- position_source: state === "valid" ? "snapshot" : "tail", position_snapshot: expected })])
- if (state === "valid") expect(restored.root.scrollTop).toBeCloseTo(800, 0)
- expect(JSON.stringify(events)).not.toContain("PRIVATE-position")
-})
-
it.each(["read_anchor", "new_divider", "tail"] as const)("records the actual %s selection instead of inferring it from initial/settled", source => {
mount({ ...(source === "read_anchor" ? { initialPositionMessageId: "m4" } : {}),
...(source === "new_divider" ? { newDividerBefore: "m4" } : {}) })
- expect(terminals()).toEqual([expect.objectContaining({ position_source: source, position_snapshot: "no_scope", position_reason: "settled" })])
+ expect(terminals()).toEqual([expect.objectContaining({ position_source: source, position_reason: "settled" })])
})
-it("keeps a new entry decision separate from a prior successful snapshot restore", async () => {
+it("attributes a reconstructed list to its normal entry rule without physical snapshot fields", async () => {
const { client } = await createCommunityQueryOwner()
- const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }
- const first = mount({ positionScope })
- first.move(600)
+ const positionScope = { proof: captureChannelMetadataToken(client, "A"), tag: null }
+ const items = Array.from({ length: 180 }, (_, index) => message(`m${index}`))
+ const first = mount({ items, positionScope })
+ first.move(1800)
first.view.unmount()
events.length = 0
- const returned = mount({ positionScope, positionEntry: {} })
- expect(terminals()).toEqual([expect.objectContaining({ position_source: "snapshot", position_snapshot: "accepted" })])
- returned.update({ positionEntry: {} })
+ const returned = mount({ items, positionScope, positionEntry: {} })
+ expect(returned.root.scrollTop).not.toBe(1800)
+ expect(terminals()).toEqual([expect.objectContaining({ position_source: "tail", position_reason: "settled" })])
+ returned.update({ positionEntry: {}, initialPositionMessageId: "m120" })
expect(terminals()).toHaveLength(2)
- expect(terminals()[1]).toMatchObject({ position_source: "tail", position_snapshot: "entry_changed" })
+ expect(terminals()[1]).toMatchObject({ position_source: "read_anchor", position_reason: "settled" })
returned.update({ positionEntry: {}, positionDataState: "pending", initialScrollReady: false })
fireEvent.wheel(returned.root, { deltaY: -20 })
- expect(terminals().at(-1)).toMatchObject({ position_source: "unknown", position_snapshot: "entry_changed", position_reason: "manual_takeover" })
-})
-
-it("records a fingerprint changed after lookup as a rejected restore at actual admission", async () => {
- const { client } = await createCommunityQueryOwner()
- const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }
- const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
- const first = mount({ items, positionScope })
- first.move(800)
- first.view.unmount()
- events.length = 0
- const returned = mount({ items, positionScope, initialScrollReady: false, positionDataState: "pending" })
- const changed = items.map((item, index) => index === 0 ? { ...item, m: { ...item.m, content: "Changed shape" } } : item)
- returned.update({ items: changed, initialScrollReady: true, positionDataState: "ready" })
- expect(terminals()).toEqual([expect.objectContaining({ position_source: "tail", position_snapshot: "fingerprint_mismatch", position_reason: "settled" })])
-})
-
-it("does not call an available snapshot accepted when a user cancels before admission", async () => {
- const { client } = await createCommunityQueryOwner()
- const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }
- const first = mount({ positionScope })
- first.move(600)
- first.view.unmount()
- events.length = 0
- const returned = mount({ positionScope, initialScrollReady: false, positionDataState: "pending" })
- fireEvent.wheel(returned.root, { deltaY: -20 })
- expect(terminals()).toEqual([expect.objectContaining({ position_source: "unknown", position_snapshot: "available", position_reason: "manual_takeover" })])
+ expect(terminals().at(-1)).toMatchObject({ position_source: "unknown", position_reason: "manual_takeover" })
+ for (const event of terminals()) expect(event).not.toHaveProperty("position_snapshot")
})
it.each(["late-consent", "retired-session"] as const)("does not export an old attempt after %s", boundary => {
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 6f2c8a12c..93209a371 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -1,12 +1,12 @@
-import { beginPositionObservation, type PositionDecision, type PositionReason, type PositionSnapshotReason } from "@/lib/observability/position"
+import { beginPositionObservation, type PositionDecision, type PositionReason } from "@/lib/observability/position"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"
+import { useCallback, useLayoutEffect, useRef, useState } from "react"
import { measureElement, useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS, type VirtualRowsLayoutSnapshot } from "./virtualizer-react-options"
import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"
import { MESSAGE_RAIL_TAIL_PADDING_END_PX } from "@/lib/community/conversation-layout"
import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"
-import { assessVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, type VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
export const MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX = 100
const VIEWPORT_RESIZE_TAIL_DISTANCE_PX = 100
@@ -61,6 +61,14 @@ export function measureMessageRow(element: Element): number {
const row = element as HTMLElement
return Math.ceil(Math.max(element.getBoundingClientRect().height, row.scrollHeight))
}
+function messageContentBounds(element: HTMLElement | undefined) {
+ if (!element) return
+ const rect = element.getBoundingClientRect()
+ if (rect.height <= 0) return
+ const overflow = window.getComputedStyle(element).overflowY
+ const height = overflow === "visible" || overflow === "" ? measureMessageRow(element) : rect.height
+ return { top: rect.top, bottom: rect.top + height, height }
+}
export function findMessageIndex(items: FlatItem[], messageId: string): number | null {
for (let i = 0; i < items.length; i++) {
const item = items[i]
@@ -110,7 +118,7 @@ export function useScrollAnchor({
scrollToMessageId?: string | null
initialPositionMessageId?: string | null
positionEntry?: object | null
- positionScope?: VirtualListPositionScope
+ positionScope?: ConversationListScope
onScrollTargetPositioned?: (id: string) => void
onScrollTargetCancelled?: (id: string) => void
hasMoreOlder?: boolean
@@ -126,7 +134,7 @@ export function useScrollAnchor({
type Kind = "initial" | "late-new" | "target" | "present" | "idle"
type Intent = {
epoch: number
- type: "unread" | "target" | "end" | "restore"
+ type: "unread" | "target" | "end"
id: string | null
index: number | null
behavior: ScrollBehavior
@@ -151,14 +159,7 @@ export function useScrollAnchor({
isScrolling: boolean
}
const scrollRef = useRef<HTMLDivElement>(null)
- const fingerprint = useMemo(() => virtualListLayoutFingerprint(items), [items])
- const [initialPosition] = useState(() => scrollToMessageId
- ? { snapshot: null, reason: "not_requested" as const } : assessVirtualListPosition(positionScope, fingerprint))
- const initialSnapshot = initialPosition.snapshot
- const restorationRef = useRef(initialSnapshot)
- const snapshotReasonRef = useRef<PositionSnapshotReason>(initialPosition.reason)
- const snapshotReadRef = useRef(initialSnapshot !== null || !!scrollToMessageId)
- const snapshotContextRef = useRef({ scope: positionScope, fingerprint })
+ const positionScopeRef = useRef(positionScope)
const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)
const positionOwnerRef = useRef({ epoch: 0, active: true })
const positionObservationRef = useRef<{ epoch: number; finish: ReturnType<typeof beginPositionObservation>; decision: PositionDecision } | null>(null)
@@ -178,7 +179,7 @@ export function useScrollAnchor({
const readReady = useCreateAtom(false)
const [readPositionReady, setReadPositionReady] = useAtom(readReady)
const [resumeValidated, setResumeValidated] = useState(true)
- const [shortGap, setShortGap] = useAtom(useCreateAtom(initialSnapshot?.paddingStart ?? 0))
+ const [shortGap, setShortGap] = useAtom(useCreateAtom(0))
const presentation = useCreateAtom<PositionOutcome>("pending")
const [positionOutcome, setPositionOutcome] = useAtom(presentation)
const [paginationDirection, setPaginationDirection] = useAtom(useCreateAtom<"older" | "newer" | null>(null))
@@ -222,12 +223,11 @@ export function useScrollAnchor({
onTargetCancelledRef.current = onScrollTargetCancelled
settleCallbackRef.current = onInitialPositionSettled
contextRef.current = { dataState, targetDataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore }
- snapshotContextRef.current = { scope: positionScope, fingerprint }
- }, [items, positionEntry, positionScope, fingerprint, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, targetDataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])
+ positionScopeRef.current = positionScope
+ }, [items, positionEntry, positionScope, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, targetDataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])
const followSuspension = useCreateAtom(false)
const [followSuspended, setFollowSuspended] = useAtom(followSuspension)
const acceptedGeometryRef = useRef<Geometry | null>(null)
- const savedPositionRef = useRef<{ scope: VirtualListPositionScope; fingerprint: string; geometry: Geometry } | null>(null)
const geometryFrameRef = useRef<number | null>(null)
const geometryObserverRef = useRef<ResizeObserver | null>(null)
const observedPageBodyRef = useRef<HTMLElement | null>(null)
@@ -269,8 +269,7 @@ export function useScrollAnchor({
const adjustAnchoredMeasurement = useCallback<NonNullable<ReactVirtualizer<HTMLDivElement, Element>["shouldAdjustScrollPositionOnItemSizeChange"]>>((item) => {
const anchor = measurementAnchorRef.current
const owner = positionOwnerRef.current
- const intent = semanticIntentRef.current
- const ownsAnchor = positionKind.get() === "idle" || intent?.type === "restore" && intent.epoch === owner.epoch && intent.id === anchor?.key
+ const ownsAnchor = positionKind.get() === "idle"
const index = anchor && anchor.epoch === owner.epoch && owner.active && ownsAnchor
? currentItemsRef.current.findIndex(row => row.key === anchor.key) : -1
return item.index < index
@@ -278,18 +277,13 @@ export function useScrollAnchor({
const beginPosition = useCallback((kind: Kind) => {
const epoch = positionOwnerRef.current.epoch
if (kind === "idle" || !contextRef.current.visible || positionObservationRef.current?.epoch === epoch) return
- positionObservationRef.current = { epoch, finish: beginPositionObservation(kind, snapshotContextRef.current.scope, positionEntryRef.current),
- decision: { position_source: "unknown", position_snapshot: kind === "initial" ? snapshotReasonRef.current : "not_requested" } }
+ positionObservationRef.current = { epoch, finish: beginPositionObservation(kind, positionScopeRef.current, positionEntryRef.current),
+ decision: { position_source: "unknown" } }
}, [])
const finishPosition = useCallback((reason: PositionReason) => {
const observation = positionObservationRef.current
observation?.finish(reason, observation.decision)
}, [])
- const recordSnapshotDecision = useCallback((reason: PositionSnapshotReason) => {
- snapshotReasonRef.current = reason
- const observation = positionObservationRef.current
- if (observation?.epoch === positionOwnerRef.current.epoch && positionKind.get() === "initial") observation.decision.position_snapshot = reason
- }, [positionKind])
const claimPosition = useCallback((kind: Kind) => {
if (kind === "target" || kind === "present") lateNewRef.current.allowed = false
const owner = positionOwnerRef.current
@@ -380,10 +374,7 @@ export function useScrollAnchor({
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
directDomUpdates: false,
useFlushSync: true,
- initialRect: initialSnapshot ? { width: initialSnapshot.width, height: initialSnapshot.height }
- : { width: 0, height: items.reduce((size, item) => size + estimateRowHeight(item, !!hasMoreOlder), shortGap + tailPaddingEnd) },
- initialOffset: initialSnapshot?.offset ?? 0,
- initialMeasurementsCache: initialSnapshot?.measurements ?? [],
+ initialRect: { width: 0, height: 800 },
count: items.length,
getScrollElement: () => scrollRef.current,
estimateSize,
@@ -443,7 +434,7 @@ export function useScrollAnchor({
const wrapperRect = wrapper.getBoundingClientRect()
const viewport = root.getBoundingClientRect()
if (wrapperRect.height <= 0
- || Math.abs(wrapperRect.height - fold.size) > 1
+ || Math.abs((item.kind === "message" ? measureMessageRow(wrapper) : wrapperRect.height) - fold.size) > 1
|| Math.abs(wrapperRect.top - viewport.top + root.scrollTop - fold.start) > 1) return null
return {
epoch: owner.epoch, key: fold.key,
@@ -475,29 +466,6 @@ export function useScrollAnchor({
&& row.end === current.end && row.lane === current.lane
})
}, [])
- const savePosition = useCallback((geometry: Geometry) => {
- const { scope, fingerprint: currentFingerprint } = snapshotContextRef.current
- const native = virtualizerRef.current
- const committed = committedRowsRef.current
- if (!scope || !native || !positionOwnerRef.current.active || !contextRef.current.visible
- || positionKind.get() !== "idle" || geometry.epoch !== positionOwnerRef.current.epoch
- || geometry.isScrolling || paginationRef.current || contextRef.current.dataState === "error"
- || committed?.items !== currentItemsRef.current || committed.layout.totalSize !== native.getTotalSize()
- || native.options.count !== currentItemsRef.current.length
- || currentItemsRef.current.some((item, index) => native.options.getItemKey(index) !== item.key)) return
- const previous = savedPositionRef.current
- if (previous?.scope === scope && previous.fingerprint === currentFingerprint
- && previous.geometry.scrollTop === geometry.scrollTop && previous.geometry.total === geometry.total
- && previous.geometry.clientWidth === geometry.clientWidth && previous.geometry.clientHeight === geometry.clientHeight) return
- saveVirtualListPosition(scope, {
- version: 1, fingerprint: currentFingerprint, offset: geometry.scrollTop,
- width: geometry.clientWidth, height: geometry.clientHeight,
- paddingStart: native.options.paddingStart ?? 0, paddingEnd: geometry.paddingEnd,
- anchorKey: geometry.key, anchorOffset: geometry.itemStart - geometry.scrollTop,
- measurements: native.takeSnapshot(), at: Date.now(),
- })
- savedPositionRef.current = { scope, fingerprint: currentFingerprint, geometry }
- }, [positionKind])
const scheduleInitialPositionSettled = useCallback(() => {
if (initialSettleFrameRef.current !== null) return
const epoch = positionOwnerRef.current.epoch
@@ -514,9 +482,8 @@ export function useScrollAnchor({
return
}
const index = intent.type === "end" ? currentItemsRef.current.length - 1
- : intent.type === "restore" ? currentItemsRef.current.findIndex(item => item.key === intent.id)
- : intent.id ? intent.type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, intent.id)
- : findMessageIndex(currentItemsRef.current, intent.id) : null
+ : intent.id ? intent.type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, intent.id)
+ : findMessageIndex(currentItemsRef.current, intent.id) : null
if (index === null || index < 0) {
if (intent.type !== "end" && (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "ready") releasePosition(false, "cancelled", "target_missing")
return
@@ -531,7 +498,7 @@ export function useScrollAnchor({
if (intent.type === "end") native.scrollToEnd({ behavior: intent.behavior })
else {
intent.index = index
- native.scrollToIndex(index, { align: intent.type === "restore" ? "start" : "center", behavior: intent.behavior })
+ native.scrollToIndex(index, { align: "center", behavior: intent.behavior })
}
intent.issued = true
intent.origin = null
@@ -543,20 +510,12 @@ export function useScrollAnchor({
const tail = currentItemsRef.current.findLast(item => item.kind === "message")
const body = tail?.kind === "message" ? Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))
.find(element => element.dataset.msgId === tail.m.id) : undefined
- const rect = body?.getBoundingClientRect()
+ const rect = messageContentBounds(body)
const wrapper = body?.closest("[data-index]")?.getBoundingClientRect()
landed = native.isAtEnd(1)
&& Math.abs(Math.max(0, root.scrollHeight - root.clientHeight) - root.scrollTop) <= 1
&& !!rect && rect.height > 0 && !!wrapper && wrapper.height > 0
&& rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1
- } else if (intent.type === "restore") {
- if (index !== intent.index) {
- intent.index = index
- native.scrollToIndex(index, { align: "start", behavior: intent.behavior })
- }
- const targetOffset = native.getOffsetForIndex(index, "start")?.[0]
- landed = targetOffset !== undefined && Math.abs(root.scrollTop - targetOffset) <= 1 && readGeometry() !== null
- && (currentItemsRef.current[index]?.kind !== "message" || readPageMessageGeometry(intent.id!) !== null)
} else if (intent.id) {
if (index !== intent.index) {
intent.index = index
@@ -568,8 +527,8 @@ export function useScrollAnchor({
? Array.from(root.querySelectorAll<HTMLElement>("[data-message-divider-for]"))
.find((element) => element.dataset.messageDividerFor === intent.id)?.querySelector<HTMLElement>("[data-new-divider]") ?? row
: row
- const rect = boundary?.getBoundingClientRect()
- const body = row?.getBoundingClientRect()
+ const body = messageContentBounds(row)
+ const rect = boundary === row ? body : boundary?.getBoundingClientRect()
const wrapper = row?.closest("[data-index]")?.getBoundingClientRect()
if (rect && body && wrapper && wrapper.height > 0 && rect.height > 0 && body.height > 0) {
const targetOffset = native.getOffsetForIndex(index, "center")?.[0]
@@ -588,12 +547,6 @@ export function useScrollAnchor({
if (!initial && (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "pending") return
finishPosition("settled")
acceptedGeometryRef.current = geometry
- if (intent.type === "restore") {
- native.cancelScroll()
- clearMeasurementAnchor()
- scrollPaddingStartRef.current = 0
- native.setOptions({ ...native.options, scrollPaddingStart: 0 })
- }
semanticIntentRef.current = null
setOwnerKind("idle")
setReadPositionReady(true)
@@ -608,7 +561,7 @@ export function useScrollAnchor({
}
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- }, [clearMeasurementAnchor, finishPosition, hasCommittedRows, holdNativeOrigin, positionKind, readGeometry, readPageMessageGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])
+ }, [finishPosition, hasCommittedRows, holdNativeOrigin, positionKind, readGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])
const onRowsLayoutCommit = useCallback((layout: VirtualRowsLayoutSnapshot | null) => {
committedRowsRef.current = layout ? { layout, native: virtualizer, entry: positionEntry, items } : null
@@ -623,11 +576,9 @@ export function useScrollAnchor({
beginPosition(positionKind.get())
const observation = positionObservationRef.current
if (observation?.epoch === owner.epoch) observation.decision = {
- position_source: type === "restore" ? "snapshot" : type === "end" ? "tail" : type === "unread" ? "new_divider" : positionKind.get() === "initial" ? "read_anchor" : "explicit_target",
- position_snapshot: positionKind.get() === "initial" ? snapshotReasonRef.current : "not_requested",
+ position_source: type === "end" ? "tail" : type === "unread" ? "new_divider" : positionKind.get() === "initial" ? "read_anchor" : "explicit_target",
}
- const index = type === "restore" ? currentItemsRef.current.findIndex(item => item.key === id)
- : type === "end" ? currentItemsRef.current.length - 1
+ const index = type === "end" ? currentItemsRef.current.length - 1
: id ? type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, id)
: findMessageIndex(currentItemsRef.current, id) : null
semanticIntentRef.current = {
@@ -635,24 +586,15 @@ export function useScrollAnchor({
awaitingData: positionKind.get() === "initial" || positionKind.get() === "late-new" ? !contextRef.current.initialScrollReady : (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "pending",
viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },
issued: false,
- origin: positionKind.get() === "initial" && type !== "restore" && !initialSnapshot ? { root: scrollRef.current, offset: scrollRef.current?.scrollTop ?? 0 } : null,
+ origin: positionKind.get() === "initial" ? { root: scrollRef.current, offset: scrollRef.current?.scrollTop ?? 0 } : null,
}
if (semanticIntentRef.current.awaitingData) return
if (type === "end" && loadedTailPresent) {
virtualizerRef.current?.scrollToEnd({ behavior })
semanticIntentRef.current.issued = true
}
- if (type === "restore" && restorationRef.current) {
- scrollPaddingStartRef.current = restorationRef.current.anchorOffset
- const native = virtualizerRef.current
- if (native) {
- measurementAnchorRef.current = { key: id!, epoch: owner.epoch }
- native.shouldAdjustScrollPositionOnItemSizeChange = adjustAnchoredMeasurement
- native.setOptions({ ...native.options, scrollPaddingStart: scrollPaddingStartRef.current })
- }
- }
scheduleInitialPositionSettled()
- }, [adjustAnchoredMeasurement, beginPosition, initialSnapshot, positionKind, scheduleInitialPositionSettled])
+ }, [beginPosition, positionKind, scheduleInitialPositionSettled])
useLayoutEffect(() => {
const owner = positionOwnerRef.current
@@ -714,11 +656,8 @@ export function useScrollAnchor({
finishPosition("entry_changed")
claimPosition("initial")
entryResolvedRef.current = false
- snapshotReadRef.current = initialRetiredRef.current
- recordSnapshotDecision(snapshotReadRef.current ? "entry_changed" : "not_requested")
initialRetiredRef.current = false
setPositionOutcome("pending")
- restorationRef.current = null
lateNewRef.current = { allowed: true, consumed: false }
targetIntentRef.current = null
positionedTargetRef.current = null
@@ -726,7 +665,7 @@ export function useScrollAnchor({
consumedLocalSubmitVersionRef.current = localSubmitVersion ?? 0
userInputRef.current.handover = false
setFollowSuspended(false)
- }, [claimPosition, committedEntry, finishPosition, localSubmitVersion, positionEntry, presentVersion, recordSnapshotDecision, setFollowSuspended, setPositionOutcome])
+ }, [claimPosition, committedEntry, finishPosition, localSubmitVersion, positionEntry, presentVersion, setFollowSuspended, setPositionOutcome])
useLayoutEffect(() => {
const target = scrollToMessageId ?? null
@@ -779,11 +718,10 @@ export function useScrollAnchor({
acceptedGeometryRef.current = {
...next, isScrolling: next.isScrolling && unchangedPosition ? previous.isScrolling : next.isScrolling,
}
- savePosition(acceptedGeometryRef.current)
if (readReady.get()) setResumeValidated(true)
holdNativeOrigin(next.scrollTop <= 1 && !next.pinEligible ? currentItemsRef.current[0]?.key ?? null : null)
}
- }, [holdNativeOrigin, positionKind, readReady, savePosition])
+ }, [holdNativeOrigin, positionKind, readReady])
const reconcilePage = useCallback(() => {
const page = paginationRef.current
@@ -945,12 +883,8 @@ export function useScrollAnchor({
scheduleInitialPositionSettled()
}
if (intent) scheduleInitialPositionSettled()
- if (positionKind.get() === "idle") {
- const geometry = readGeometry()
- if (geometry) savePosition(geometry)
- }
reconcileGeometry(true)
- }, [positionKind, readGeometry, reconcileGeometry, savePosition, scheduleInitialPositionSettled])
+ }, [reconcileGeometry, scheduleInitialPositionSettled])
const reconcileGeometryRef = useRef(reconcileGeometry)
useLayoutEffect(() => {
reconcileGeometryRef.current = reconcileGeometry
@@ -1240,37 +1174,11 @@ export function useScrollAnchor({
if (dataState === "pending" && !initialScrollReady) return
if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages) return
if (!entryResolvedRef.current) {
- if (!snapshotReadRef.current) {
- snapshotReadRef.current = true
- const read = scrollToMessageId ? { snapshot: null, reason: "not_requested" as const } : assessVirtualListPosition(positionScope, fingerprint)
- restorationRef.current = read.snapshot
- recordSnapshotDecision(read.reason)
- }
- const snapshot = restorationRef.current
- const root = scrollRef.current
- if (snapshot && (!root || root.clientWidth <= 0 || root.clientHeight <= 0)) return
entryResolvedRef.current = true
if (newDividerBefore) lateNewRef.current.consumed = true
- if (snapshot && snapshot.fingerprint === fingerprint && snapshot.width === root?.clientWidth
- && snapshot.height === root.clientHeight && snapshot.paddingEnd === tailPaddingEnd
- && items.some(item => item.key === snapshot.anchorKey)) {
- recordSnapshotDecision("accepted")
- startIntent("restore", String(snapshot.anchorKey))
- }
- else {
- if (snapshot) {
- recordSnapshotDecision(snapshot.fingerprint !== fingerprint ? "fingerprint_mismatch"
- : snapshot.width !== root?.clientWidth || snapshot.height !== root?.clientHeight ? "viewport_mismatch"
- : snapshot.paddingEnd !== tailPaddingEnd ? "padding_mismatch" : "anchor_missing")
- restorationRef.current = null
- virtualizer.setOptions({ ...virtualizer.options, initialMeasurementsCache: [] })
- virtualizer.measure()
- scrollRef.current?.querySelectorAll<HTMLElement>("[data-index]").forEach(element => virtualizer.measureElement(element))
- }
- startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)
- }
+ startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)
} else scheduleInitialPositionSettled()
- }, [dataState, targetDataState, fingerprint, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionScope, positionKind, recordSnapshotDecision, scrollToMessageId, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, tailPaddingEnd, virtualItems, virtualizer, visible])
+ }, [dataState, targetDataState, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, virtualItems, visible])
const scrollToBottom = useCallback(() => {
if (!positionOwnerRef.current.active || !contextRef.current.visible) return
diff --git a/src/web/src/hooks/community/use-server-cold.dom.test.tsx b/src/web/src/hooks/community/use-server-cold.dom.test.tsx
index a144aaa39..202117af5 100644
--- a/src/web/src/hooks/community/use-server-cold.dom.test.tsx
+++ b/src/web/src/hooks/community/use-server-cold.dom.test.tsx
@@ -1,3 +1,4 @@
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
import React from "react"
import { QueryClient } from "@tanstack/react-query"
import { afterEach, describe, expect, it, vi } from "vitest"
@@ -11,7 +12,7 @@ const api = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: api }))
afterEach(() => api.mockReset())
function client() { return new QueryClient({ defaultOptions: { queries: { retry: false } } }) }
-const list = { servers: [{ id: "srv", name: "Cold", discriminator: "0001", icon: null, ownerId: "viewer", role: "owner" }] }
+const list = serverRailResponseFixture({ servers: [{ id: "srv", name: "Cold", discriminator: "0001", icon: null, ownerId: "viewer", isOwner: true, memberId: "member-viewer", role: "owner" }] })
function respond(path: string) {
if (path.endsWith("/categories")) return { categories: [] }
if (path.endsWith("/channels")) return { channels: [] }
diff --git a/src/web/src/hooks/community/use-server-members.dom.test.ts b/src/web/src/hooks/community/use-server-members.dom.test.ts
index d0be285fb..9a82a32eb 100644
--- a/src/web/src/hooks/community/use-server-members.dom.test.ts
+++ b/src/web/src/hooks/community/use-server-members.dom.test.ts
@@ -47,8 +47,8 @@ import type {
CommunityMemberUpdate,
} from "@alook/shared"
-function m(id: string, userId = id, role: Member["role"] = "member"): Member {
- return { id, userId, name: `n_${id}`, discriminator: "0000", avatar: `A`, avatarVersion: 0, status: "offline", sub: "", role }
+function m(id: string, userId = id, role: Member["role"] = "member"): Member & { statusEmoji: null; statusText: string } {
+ return { id, userId, name: `n_${id}`, discriminator: "0000", avatar: `A`, avatarVersion: 0, status: "offline", sub: "", role, statusEmoji: null, statusText: "" }
}
function joinEvent(userId: string, id = userId): CommunityMemberJoin {
@@ -241,8 +241,12 @@ function makeCache(pages: MembersEnvelope[]): InfiniteData<MembersEnvelope> {
return { pages, pageParams: pages.map((_, i) => (i === 0 ? null : `cur_${i}`)) }
}
-function makeEnvelope(members: Member[], hasMore: boolean, total = members.length): MembersEnvelope {
- return { members, hasMore, limit: 50, total, ...(hasMore ? { cursor: "cur_next" } : {}) }
+function makeEnvelope(members: Member[], hasMore: boolean, total = members.length): MembersEnvelope & { viewerId: string; serverId: string } {
+ return { viewerId: "viewer", serverId: "srv_1", members, hasMore, limit: 50, total, ...(hasMore ? { cursor: "cur_next" } : {}) }
+}
+
+function makeSearchEnvelope(members: ReturnType<typeof m>[], hasMore: boolean) {
+ return { viewerId: "viewer", serverId: "srv_1", members, hasMore, limit: 50, ...(hasMore ? { cursor: "cur_next" } : {}) }
}
describe("patchCacheJoin", () => {
@@ -352,13 +356,13 @@ describe("patchCacheRole", () => {
describe("membersPageQueryFn", () => {
it("hits /members with no query string on page 1 and appends cursor on later pages", async () => {
- apiFetchMock.mockResolvedValueOnce({ members: [], hasMore: false, limit: 50, total: 0 })
+ apiFetchMock.mockResolvedValueOnce({ viewerId: "viewer", serverId: "srv_1", members: [], hasMore: false, limit: 50, total: 0 })
const { client } = await createCommunityQueryOwner()
const fn = membersPageQueryFn("srv_1")
await fn({ pageParam: null, client })
expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/servers/srv_1/members", expect.objectContaining({ authenticationAccount: "viewer" }))
- apiFetchMock.mockResolvedValueOnce({ members: [], hasMore: false, limit: 50, total: 0 })
+ apiFetchMock.mockResolvedValueOnce({ viewerId: "viewer", serverId: "srv_1", members: [], hasMore: false, limit: 50, total: 0 })
await fn({ pageParam: "cur_1|abc", client })
expect(apiFetchMock).toHaveBeenLastCalledWith(
"/api/community/servers/srv_1/members?cursor=cur_1%7Cabc",
@@ -367,7 +371,7 @@ describe("membersPageQueryFn", () => {
})
it("populates queryClient at communityKeys.members(serverId)", async () => {
- apiFetchMock.mockResolvedValueOnce({ members: [], hasMore: false, limit: 50, total: 0 })
+ apiFetchMock.mockResolvedValueOnce({ viewerId: "viewer", serverId: "srv_1", members: [], hasMore: false, limit: 50, total: 0 })
const qc = (await createCommunityQueryOwner()).client
const key = communityKeys.members("srv_1")
await qc.infiniteQuery({
@@ -382,8 +386,8 @@ describe("membersPageQueryFn", () => {
it("fetchNextPage produces a new page under the same key", async () => {
apiFetchMock
- .mockResolvedValueOnce({ members: [m("a")], hasMore: true, cursor: "cur_1|a", limit: 50, total: 2 })
- .mockResolvedValueOnce({ members: [m("b")], hasMore: false, limit: 50, total: 2 })
+ .mockResolvedValueOnce({ viewerId: "viewer", serverId: "srv_1", members: [m("a")], hasMore: true, cursor: "cur_1|a", limit: 50, total: 2 })
+ .mockResolvedValueOnce({ viewerId: "viewer", serverId: "srv_1", members: [m("b")], hasMore: false, limit: 50, total: 2 })
const qc = (await createCommunityQueryOwner()).client
const key = communityKeys.members("srv_1")
await qc.infiniteQuery({
@@ -420,7 +424,7 @@ describe("native member subscriptions", () => {
})
it("canonical member removal drops the exact row from an active search window", async () => {
vi.useFakeTimers()
- apiFetchMock.mockResolvedValue(makeEnvelope([m("mem_1"), m("mem_2"), m("mem_3")], false))
+ apiFetchMock.mockImplementation((url: string) => Promise.resolve(isSearchUrl(url) ? makeSearchEnvelope([m("mem_1"), m("mem_2"), m("mem_3")], false) : makeEnvelope([m("mem_1"), m("mem_2"), m("mem_3")], false)))
const harness = await mountServerMembers()
await act(async () => harness.resultRef.current!.searchMembers("mem"))
await act(async () => vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS + 1))
@@ -496,7 +500,7 @@ describe("useServerMembers search lifecycle", () => {
expect(resultRef.current).toMatchObject({ loading: true, failed: false })
expect(observations.every((value) => value.loading || value.failed)).toBe(true)
await act(async () => {
- queryClient.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ identityComplete: false, id: person.userId, name: person.name, discriminator: person.discriminator, avatar: person.avatar, avatarVersion: 0 })])
+ queryClient.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ id: person.userId, name: person.name, discriminator: person.discriminator, avatar: person.avatar, avatarVersion: 0 })])
restore.resolve(); await registry.preload()
})
await vi.waitFor(() => expect(resultRef.current).toMatchObject({ loading: false, failed: false, members: [expect.objectContaining({ id: "a", discriminator: "0000" })] }))
@@ -505,12 +509,12 @@ describe("useServerMembers search lifecycle", () => {
})
it("debounces once, leaves the first page ready, and appends only requested continuation pages", async () => {
vi.useFakeTimers()
- const first = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()
- const second = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()
+ const first = deferred<ReturnType<typeof makeSearchEnvelope>>()
+ const second = deferred<ReturnType<typeof makeSearchEnvelope>>()
apiFetchMock.mockImplementation((url: unknown) => {
if (!isSearchUrl(url)) return Promise.resolve(makeEnvelope([], false, 0))
if (url.includes("q=none")) {
- return Promise.resolve({ members: [], hasMore: false, limit: 50 })
+ return Promise.resolve({ viewerId: "viewer", serverId: "srv_1", members: [], hasMore: false, limit: 50 })
}
return url.includes("cursor=cur_2") ? second.promise : first.promise
})
@@ -534,7 +538,7 @@ describe("useServerMembers search lifecycle", () => {
["/api/community/servers/srv_1/members/search?q=ad", expect.objectContaining({ authenticationAccount: "viewer", signal: expect.any(AbortSignal) })],
])
- first.resolve({ members: [m("a"), m("b")], hasMore: true, cursor: "cur_2", limit: 50 })
+ first.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("a"), m("b")], hasMore: true, cursor: "cur_2", limit: 50 })
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
members: [m("a"), m("b")],
@@ -550,7 +554,7 @@ describe("useServerMembers search lifecycle", () => {
["/api/community/servers/srv_1/members/search?cursor=cur_2&q=ad", expect.objectContaining({ authenticationAccount: "viewer", signal: expect.any(AbortSignal) })],
])
- second.resolve({ members: [m("b"), m("c")], hasMore: false, limit: 50 })
+ second.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("b"), m("c")], hasMore: false, limit: 50 })
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
members: [m("a"), m("b"), m("c")],
@@ -574,11 +578,11 @@ describe("useServerMembers search lifecycle", () => {
it("keeps the latest query when older success and error responses settle late", async () => {
vi.useFakeTimers()
- const requests = new Map<string, Deferred<{ members: Member[]; hasMore: boolean; limit: number }>>()
+ const requests = new Map<string, Deferred<ReturnType<typeof makeSearchEnvelope>>>()
apiFetchMock.mockImplementation((url: unknown) => {
if (!isSearchUrl(url)) return Promise.resolve(makeEnvelope([], false, 0))
const query = new URL(url, "https://alook.local").searchParams.get("q")!
- const request = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()
+ const request = deferred<ReturnType<typeof makeSearchEnvelope>>()
requests.set(query, request)
return request.promise
})
@@ -590,14 +594,14 @@ describe("useServerMembers search lifecycle", () => {
harness.resultRef.current!.searchMembers("new-success")
await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)
})
- requests.get("old-success")!.resolve({ members: [m("old")], hasMore: false, limit: 50 })
+ requests.get("old-success")!.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("old")], hasMore: false, limit: 50 })
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
searchQuery: "new-success",
searchStatus: "loading",
members: [],
})
- requests.get("new-success")!.resolve({ members: [m("new")], hasMore: false, limit: 50 })
+ requests.get("new-success")!.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("new")], hasMore: false, limit: 50 })
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
searchQuery: "new-success",
@@ -619,7 +623,7 @@ describe("useServerMembers search lifecycle", () => {
searchStatus: "loading",
members: [],
})
- requests.get("final")!.resolve({ members: [m("final")], hasMore: false, limit: 50 })
+ requests.get("final")!.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("final")], hasMore: false, limit: 50 })
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
searchQuery: "final",
@@ -633,9 +637,9 @@ describe("useServerMembers search lifecycle", () => {
it("retains accumulated members on a current continuation error and same-term refresh", async () => {
vi.useFakeTimers()
- const first = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()
- const continuation = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()
- const refreshed = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()
+ const first = deferred<ReturnType<typeof makeSearchEnvelope>>()
+ const continuation = deferred<ReturnType<typeof makeSearchEnvelope>>()
+ const refreshed = deferred<ReturnType<typeof makeSearchEnvelope>>()
let searchCall = 0
apiFetchMock.mockImplementation((url: unknown) => {
if (!isSearchUrl(url)) return Promise.resolve(makeEnvelope([], false, 0))
@@ -650,7 +654,7 @@ describe("useServerMembers search lifecycle", () => {
harness.resultRef.current!.searchMembers("ad")
await vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS)
})
- first.resolve({ members: [m("a")], hasMore: true, cursor: "next", limit: 50 })
+ first.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("a")], hasMore: true, cursor: "next", limit: 50 })
await flushEffects()
await act(async () => { await vi.advanceTimersByTimeAsync(1) })
expect(searchCall).toBe(1)
@@ -674,7 +678,7 @@ describe("useServerMembers search lifecycle", () => {
searchStatus: "loading",
searchQuery: "ad",
})
- refreshed.resolve({ members: [m("refreshed")], hasMore: false, limit: 50 })
+ refreshed.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("refreshed")], hasMore: false, limit: 50 })
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
members: [m("refreshed")],
@@ -695,7 +699,7 @@ describe("useServerMembers search lifecycle", () => {
it("clears pending searches and cancels the debounce on unmount", async () => {
vi.useFakeTimers()
apiFetchMock.mockImplementation((url: unknown) => {
- if (isSearchUrl(url)) return Promise.resolve({ members: [], hasMore: false, limit: 50 })
+ if (isSearchUrl(url)) return Promise.resolve({ viewerId: "viewer", serverId: "srv_1", members: [], hasMore: false, limit: 50 })
return Promise.resolve(makeEnvelope([], false, 0))
})
const harness = await mountServerMembers()
@@ -721,10 +725,10 @@ describe("useServerMembers search lifecycle", () => {
it("drops the previous server overlay and ignores its late response", async () => {
vi.useFakeTimers()
- const oldResponse = deferred<{ members: Member[]; hasMore: boolean; limit: number }>()
+ const oldResponse = deferred<ReturnType<typeof makeSearchEnvelope>>()
apiFetchMock.mockImplementation((url: unknown) => {
if (isSearchUrl(url)) return oldResponse.promise
- return Promise.resolve(makeEnvelope([], false, 0))
+ return Promise.resolve({ ...makeEnvelope([], false, 0), serverId: new URL(String(url), "https://alook.local").pathname.split("/")[4] })
})
const harness = await mountServerMembers()
@@ -748,7 +752,7 @@ describe("useServerMembers search lifecycle", () => {
searchStatus: "idle",
})
- oldResponse.resolve({ members: [m("old")], hasMore: false, limit: 50 })
+ oldResponse.resolve({ viewerId: "viewer", serverId: "srv_1", members: [m("old")], hasMore: false, limit: 50 })
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
isSearching: false,
@@ -762,3 +766,25 @@ describe("useServerMembers search lifecycle", () => {
harness.queryClient.clear()
})
})
+
+it.each(["missing-later-core", "wrong-server", "wrong-viewer", "duplicate-user"])("rejects an entire warm member page %s before any canonical write", async defect => {
+ const { communityRegistrySnapshot } = await import("@/test/community-registry-snapshot")
+ const { client, registry } = await createCommunityQueryOwner()
+ const fn = membersPageQueryFn("srv_1")
+ const first = { ...m("first"), statusEmoji: null, statusText: "" }
+ const second = { ...m("second"), statusEmoji: null, statusText: "" }
+ const envelope = { viewerId: "viewer", serverId: "srv_1", members: [first, second], hasMore: false, limit: 50, total: 2 }
+ apiFetchMock.mockResolvedValueOnce(envelope)
+ await fn({ pageParam: null, client })
+ const before = communityRegistrySnapshot(registry)
+ const malformed = structuredClone(envelope)
+ malformed.members[0]!.name = "Must not publish first"
+ malformed.members[1]!.name = "Must not publish later"
+ if (defect === "missing-later-core") delete (malformed.members[1] as Partial<typeof second>).avatarVersion
+ if (defect === "wrong-server") malformed.serverId = "foreign-server"
+ if (defect === "wrong-viewer") malformed.viewerId = "foreign-viewer"
+ if (defect === "duplicate-user") malformed.members[1]!.userId = first.userId
+ apiFetchMock.mockResolvedValueOnce(malformed)
+ await expect(fn({ pageParam: null, client })).rejects.toThrow()
+ expect(communityRegistrySnapshot(registry)).toEqual(before)
+})
diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.ts
index 3d8b70a4f..a2606d6bc 100644
--- a/src/web/src/hooks/community/use-server-members.ts
+++ b/src/web/src/hooks/community/use-server-members.ts
@@ -14,6 +14,7 @@ import { serverMembershipKey } from "@/lib/community-db/schema"
import { useCommunityViewSource } from "./use-community-view-source"
import { communityKeys } from "@/lib/query-keys"
import type { Member } from "@/lib/community/models/people"
+import { parseCommunityServerMembersRead } from "@alook/shared"
import type { CommunityMemberJoin, CommunityMemberLeave, CommunityMemberUpdate, CommunityRole } from "@alook/shared"
import { avatarInitial } from "@/lib/community/avatar"
@@ -45,7 +46,7 @@ export function applyJoinEvent(
id: event.member.id,
userId: event.member.userId,
name: event.member.name,
- discriminator: event.member.discriminator,
+ discriminator: event.member.discriminator ?? "",
avatar: event.member.avatar ?? avatarInitial(event.member.name),
avatarVersion: event.member.avatarVersion,
status: "online",
@@ -80,13 +81,6 @@ export type MembersEnvelope = {
total: number
}
-type SearchEnvelope = {
- members: Member[]
- limit: number
- hasMore: boolean
- cursor?: string
-}
-
export function mergeMemberSearchPage(
current: Member[],
incoming: Member[],
@@ -268,10 +262,10 @@ export const membersPageQueryFn = (serverId: string, search = "", limit?: number
if (search) params.set("q", search)
if (limit) params.set("limit", String(limit))
const path = "/api/community/servers/" + serverId + "/members" + (search ? "/search" : "") + (params.size ? "?" + params : "")
- const data = await apiFetch<MembersEnvelope | SearchEnvelope>(path, communityRequestOptions(client, token, signal, assert))
+ const data = parseCommunityServerMembersRead(await apiFetch<unknown>(path, communityRequestOptions(client, token, signal, assert)), serverId, registry.accountId!, !!search)
assert()
if (data.hasMore && !data.cursor) throw new Error("members page missing cursor")
- writeCommunityProfilePatches(data.members.map((member) => communityUserProfilePatch(member.userId, member, { legacyPresentation: true })), registry, { snapshot: profileSnapshot })
+ writeCommunityProfilePatches(data.members.map((member) => communityUserProfilePatch(member.userId, member)), registry, { snapshot: profileSnapshot })
publishCommunityMembersSnapshot(client, serverId, data.members, { token, signal })
assert()
return { members: data.members.map(({ id, userId }) => ({ id, userId })), hasMore: data.hasMore, cursor: data.cursor, limit: data.limit, ...("total" in data ? { total: data.total } : {}), liveRevision: protocol.liveRevision }
@@ -430,7 +424,7 @@ export function useServerMembers(serverId: string | null): UseServerMembers {
})
}, [identities, membershipProjection.data, profiles])
const active = searching ? search : infinite
- const readState = getMemberReadState(!!serverId, { pending: !data || active.isRefetching, failed: (!searching || searchReady) && active.isError && !active.isFetching }, [membershipProjection, profileProjection], members.filter((member) => member.userId !== membershipProjection.registry?.accountId).map((member) => member.userId), profiles)
+ const readState = getMemberReadState(!!serverId, { pending: !data || active.isRefetching, failed: (!searching || searchReady) && active.isError && !active.isFetching }, [membershipProjection, profileProjection], identities.filter((member) => member.userId !== membershipProjection.registry?.accountId).map((member) => member.userId), profileProjection.resourceProfiles)
const pendingKicks = useMutationState({ filters: { mutationKey: ["community", "member-command"], status: "pending" }, select: (mutation) => {
const variables = mutation.state.variables as { kind: string; input: { serverId: string; memberId: string } }
const current = queryClient.getQueryData<MembersWindowCache>(key)
diff --git a/src/web/src/hooks/community/use-server-panels.test.ts b/src/web/src/hooks/community/use-server-panels.test.ts
index 334da1a1f..64f31f98a 100644
--- a/src/web/src/hooks/community/use-server-panels.test.ts
+++ b/src/web/src/hooks/community/use-server-panels.test.ts
@@ -1,3 +1,4 @@
+import { invitesReadFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
@@ -13,8 +14,7 @@ beforeEach(() => {
describe("useInvites / invitesQueryFn", () => {
it("materialises raw invite rows into InviteRow shape", async () => {
- apiFetchMock.mockResolvedValueOnce({
- invites: [
+ apiFetchMock.mockResolvedValueOnce(invitesReadFixture("srv_1", [
{
id: "inv_1",
token: "abcd",
@@ -23,10 +23,8 @@ describe("useInvites / invitesQueryFn", () => {
expiresAt: null,
createdAt: "2026-07-03T00:00:00.000Z",
creatorId: "u_alice",
- creatorName: "Alice",
},
- ],
- })
+ ], [{ id: "u_alice", name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 }]))
const { invitesQueryFn } = await import("./use-server-panels")
const { client: qc, registry } = await createCommunityQueryOwner()
const data = await qc.query({ queryKey: communityKeys.invites("srv_1"), queryFn: invitesQueryFn("srv_1") })
@@ -42,7 +40,7 @@ describe("useInvites / invitesQueryFn", () => {
})
it("populates queryClient at communityKeys.invites(serverId)", async () => {
- apiFetchMock.mockResolvedValueOnce({ invites: [] })
+ apiFetchMock.mockResolvedValueOnce(invitesReadFixture("srv_1"))
const { invitesQueryFn } = await import("./use-server-panels")
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.invites("srv_1")
diff --git a/src/web/src/hooks/community/use-server-panels.ts b/src/web/src/hooks/community/use-server-panels.ts
index 028807404..aa6002db1 100644
--- a/src/web/src/hooks/community/use-server-panels.ts
+++ b/src/web/src/hooks/community/use-server-panels.ts
@@ -1,12 +1,13 @@
"use client"
+import { CommunityInvitesReadSchema } from "@alook/shared"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import type { QueryFunctionContext } from "@tanstack/react-query"
import { useQuery,useQueryClient,useMutationState,keepPreviousData,type UseQueryResult } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
-import { loadAndSeedProfiles,beginCommunityProfileSeed,writeCommunityProfilePatches } from "@/lib/community/profile-seed"
+import { communityUserProfilePatch, loadAndSeedProfiles } from "@/lib/community/profile-seed"
import { captureCommunityLiveSnapshotToken,assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
-import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
+
import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { communityKeys } from "@/lib/query-keys"
import type { InviteRow } from "@/lib/community/models/people"
@@ -19,22 +20,6 @@ function throwIfStale<T extends { stale?: boolean }>(v: T): T {
return v
}
-/**
- * Fetches the invite list surfaced in the settings tab. The API returns raw
- * rows; we transform to the display shape here so consumers get render-ready
- * cache entries (matching the old context's `InviteRow` mapping).
- */
-type RawInvite = {
- id: string
- token: string
- maxUses: number | null
- uses: number
- expiresAt: string | null
- createdAt: string
- creatorId: string | null
- creatorName: string | null
-}
-
type InviteResourceRow = Omit<InviteRow, "by">
export type InvitesResponse = { invites: InviteResourceRow[] }
@@ -44,15 +29,15 @@ const EMPTY_INVITES: readonly InviteRow[] = Object.freeze([])
export const invitesQueryFn = (serverId: string) => async (context: QueryFunctionContext): Promise<InvitesResponse> => {
const original = captureCommunityLiveSnapshotToken(context.client)
const assert = () => assertCommunityLiveSnapshotTokenCurrent(context.client, original, context.signal)
- const snapshot = beginCommunityProfileSeed(original.registry)
await original.registry?.ready
assert()
- const data = await apiFetch<{ invites: RawInvite[] }>(
- `/api/community/servers/${serverId}/invites`,
- communityRequestOptions(context.client, original, context.signal, assert),
+ const data = await loadAndSeedProfiles(
+ origin => apiFetch<unknown>(`/api/community/servers/${serverId}/invites`, { ...origin, signal: context.signal }).then(value => CommunityInvitesReadSchema.parse(value)),
+ value => {
+ if (value.serverId !== serverId || value.resources.viewerId !== original.registry!.accountId) throw new Error("Invite resource scope mismatch")
+ return value.resources.profiles.map(profile => communityUserProfilePatch(profile.id, profile))
+ }, original.registry, context.signal, original,
)
- assert()
- writeCommunityProfilePatches(data.invites.flatMap((i) => i.creatorId && i.creatorName !== null ? [{ id: i.creatorId, identityAbout: { name: i.creatorName } }] : []), original.registry, { snapshot })
const invites: InviteResourceRow[] = data.invites.map((i) => ({
code: i.token,
uses: i.uses,
diff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.ts
index 7d3753686..c4415961f 100644
--- a/src/web/src/hooks/community/use-servers.dom.test.ts
+++ b/src/web/src/hooks/community/use-servers.dom.test.ts
@@ -1,3 +1,5 @@
+import { CommunityChannelResourceSchema, AttentionIncludedChannelSchema } from "@alook/shared"
+import { serverRailResponseFixture, serverResourceFixture, categoryResourceFixture, channelResourceFixture, fullResourceBundleFixture, serverDirectoryFixture, resourceBundleFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider, CancelledError } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -27,22 +29,23 @@ beforeEach(async () => {
})
function Owner({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children)) }
const identity = { id: "srv_1", name: "Alook", discriminator: "0001", description: "Build together", icon: null, ownerId: "viewer" }
-const canonical = (id = "srv_1") => ({ ...identity, id, initial: "A", active: false, unread: false, mentions: 0, isOwner: false })
+const canonical = (id = "srv_1") => serverRailResponseFixture({ servers: [{ ...identity, id, role: "member", isOwner: false }] }, "viewer").servers[0]!
function publish(snapshot: Parameters<typeof publishCommunityLiveSnapshot>[1]["snapshot"]) {
return publishCommunityLiveSnapshot(client, { snapshot, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
}
function seedList(servers: ServersResponse["servers"] = [canonical()]) {
- publish({ kind: "servers", data: { servers } })
+ publish({ kind: "servers", data: serverRailResponseFixture({ servers }, "viewer") })
client.setQueryData(communityKeys.servers(), servers.map((server) => server.id))
}
function seedDetail(channels: ServerDetail["categories"][number]["channels"] = []) {
seedList()
- publish({ kind: "server-detail", data: { ...identity, categories: [{ id: "cat_1", name: "Main", private: 0, channels }] } })
- client.setQueryData(communityKeys.server(identity.id), identity.id)
+ publish({ kind: "server-detail", data: serverDirectoryFixture({ ...identity, categories: [{ id: "cat_1", name: "Main", private: false, channels }] }) })
}
function attention(channelId: string, count = 1, parentChannelId: string | null = null) {
publishAccountAttentionSnapshot(client, {
- snapshot: { scopes: [{ scopeId: channelId, channelId, serverId: identity.id, parentChannelId, ordinaryUnread: true, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: count }], items: [], limit: 100, truncated: false },
+ snapshot: { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: fullResourceBundleFixture("viewer", [serverResourceFixture(identity)], parentChannelId
+ ? [channelResourceFixture({ id: parentChannelId, serverId: identity.id, type: "forum" }), channelResourceFixture({ id: channelId, serverId: identity.id, type: "thread", parentChannelId, parentMessageId: `opener-${channelId}` })]
+ : [(registry.collections.channels.get(channelId) ? CommunityChannelResourceSchema.strip().parse(registry.collections.channels.get(channelId)) : channelResourceFixture({ id: channelId, serverId: identity.id }))]), scopes: [{ scopeId: channelId, channelId, serverId: identity.id, parentChannelId, ordinaryUnread: true, lastUnreadSeq: 4, lastAttentionSeq: 4, attentionCount: count }], items: [], limit: 100, truncated: false },
proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
}
@@ -53,8 +56,8 @@ function fetchDetail() {
return client.query({ queryKey: communityKeys.server(identity.id), queryFn: ({ signal }) => serverProjectedQueryFn(client, identity.id, signal)(), staleTime: 0 })
}
function detailApi(url: string) {
- if (url === "/api/community/servers") return { servers: [identity] }
- if (url.endsWith("/categories")) return { categories: [{ id: "cat_1", name: "Main", private: 0 }] }
+ if (url === "/api/community/servers") return serverRailResponseFixture({ servers: [identity] }, "viewer")
+ if (url.endsWith("/categories")) return { categories: [categoryResourceFixture({ id: "cat_1", serverId: identity.id, name: "Main" })] }
if (url.endsWith("/channels")) return { channels: [] }
throw new Error("unexpected " + url)
}
@@ -69,7 +72,7 @@ async function rawList() {
describe("useServers / serversQueryFn", () => {
it("materialises raw server rows into render-ready Server shape", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [{ ...identity, official: true, role: "owner", mentions: 3, unread: true }, { ...identity, id: "srv_2", name: "Beta", discriminator: "12345", role: "member", description: undefined }] })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers: [{ ...identity, official: true, role: "owner", mentions: 3, unread: true }, { ...identity, id: "srv_2", name: "Beta", discriminator: "12345", role: "member", description: "", official: false }] }, "viewer"))
const data = await rawList()
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
expect(data.servers[0]).toMatchObject({ ...identity, official: true, initial: "A", isOwner: true, mentions: 0, active: false, unread: false })
@@ -78,19 +81,19 @@ describe("useServers / serversQueryFn", () => {
})
it("preserves mentions when provided; defaults to 0 when omitted", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [{ ...identity, mentions: 7 }, { ...identity, id: "srv_2" }] })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers: [{ ...identity, mentions: 7 }, { ...identity, id: "srv_2" }] }, "viewer"))
expect((await rawList()).servers.map((server) => server.mentions)).toEqual([0, 0])
})
it("passes TanStack's abort signal to the canonical request", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [] })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers: [] }, "viewer"))
let signal!: AbortSignal
await client.query({ queryKey: communityKeys.servers(), queryFn: async (context) => { signal = context.signal; return (await serversQueryFn(context)).servers.map((server) => server.id) } })
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.objectContaining({ signal, assertActive: expect.any(Function) }))
})
it("populates queryClient at communityKeys.servers() with transport IDs only", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [identity] })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers: [identity] }, "viewer"))
await fetchList()
expect(client.getQueryData(communityKeys.servers())).toEqual([identity.id])
expect(registry.collections.servers.get(identity.id)).toMatchObject(identity)
@@ -103,13 +106,13 @@ describe("useServers / serversQueryFn", () => {
const result = pending.catch((error) => error)
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
registry.runtime.ws.actions.activateProfileAccount("replacement")
- release({ servers: [identity] })
+ release(serverRailResponseFixture({ servers: [identity] }, "viewer"))
expect(await result).toMatchObject({ name: "AbortError" })
expect(registry.collections.servers.size).toBe(0)
})
it("confirms live list authority only for the current QueryClient and auth generation", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [] })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers: [] }, "viewer"))
const rendered = renderHook(() => useServers(), { wrapper: Owner })
expect(rendered.result.current.isLiveAuthoritative).toBe(false)
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
@@ -127,7 +130,7 @@ describe("useServers / serversQueryFn", () => {
})
it("invalidates live list authority when the access epoch changes", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [] })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers: [] }, "viewer"))
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
act(() => registry.runtime.ws.actions.revokeServerAccess("s1"))
@@ -136,19 +139,19 @@ describe("useServers / serversQueryFn", () => {
it("binds live authority to the projected unordered server membership", async () => {
const servers = Array.from({ length: 7 }, (_, index) => ({ ...canonical("s" + (index + 1)), name: "Server " + (index + 1) }))
- apiFetchMock.mockResolvedValueOnce({ servers })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers }, "viewer"))
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
expect(rendered.result.current.servers.map((server) => server.id)).toEqual(servers.map((server) => server.id))
act(() => client.setQueryData(communityKeys.servers(), [...servers.map((server) => server.id)].reverse()))
expect(rendered.result.current.isLiveAuthoritative).toBe(true)
- act(() => publish({ kind: "servers", data: { servers: servers.slice(0, 6) } }))
+ act(() => publish({ kind: "servers", data: serverRailResponseFixture({ servers: servers.slice(0, 6) }, "viewer") }))
await waitFor(() => expect(rendered.result.current.servers).toHaveLength(6))
expect(rendered.result.current.isLiveAuthoritative).toBe(false)
- apiFetchMock.mockResolvedValueOnce({ servers })
+ apiFetchMock.mockResolvedValueOnce(serverRailResponseFixture({ servers }, "viewer"))
await act(async () => { await rendered.result.current.refetch() })
await waitFor(() => expect(rendered.result.current.isLiveAuthoritative).toBe(true))
- act(() => publish({ kind: "servers", data: { servers: [...servers, canonical("s8")] } }))
+ act(() => publish({ kind: "servers", data: serverRailResponseFixture({ servers: [...servers, canonical("s8")] }, "viewer") }))
await waitFor(() => expect(rendered.result.current.servers).toHaveLength(8))
expect(rendered.result.current.isLiveAuthoritative).toBe(false)
})
@@ -194,7 +197,7 @@ describe("useServers / serversQueryFn", () => {
seedList([{ ...canonical(), unread: true }])
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
- act(() => publish({ kind: "servers", data: { servers: [{ ...canonical(), unread: true, unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }] }] } }))
+ act(() => publish({ kind: "servers", data: serverRailResponseFixture({ servers: [{ ...canonical(), unread: true, unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }] }] }, "viewer") }))
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
act(() => publish({ kind: "read-state", data: { revision: 1, readStates: [{ channelId: "c1", lastReadMessageId: "m4", lastReadAt: null, lastReadSeq: 4 }] } }))
expect(rendered.result.current.servers[0]?.unread).toBe(false)
@@ -220,7 +223,7 @@ describe("useServer / projected canonical detail", () => {
await waitFor(() => expect(retirement === "owner" ? !registry.runtime.lifecycle.get().active : registry.runtime.ws.get().profileViewerId === "replacement").toBe(true))
await waitFor(() => expect(view.result.current.fetchStatus).toBe("idle"))
expect(view.result.current.server).toBeNull()
- expect(registry.collections.servers.get(identity.id)?.detailComplete).toBe(false)
+ expect(client.getQueryData(communityKeys.server(identity.id))).toBeUndefined()
expect(apiFetchMock.mock.calls.filter(([url]) => String(url).endsWith("/categories"))).toHaveLength(1)
} finally {
unsubscribe()
@@ -310,14 +313,15 @@ describe("useServer / projected canonical detail", () => {
seedList(); apiFetchMock.mockImplementation(detailApi)
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server).toMatchObject({ ...identity, categories: [{ id: "cat_1", channels: [] }] }))
- expect(client.getQueryData(communityKeys.server(identity.id))).toBe(identity.id)
+ expect(client.getQueryData(communityKeys.server(identity.id))).toMatchObject({ serverId: identity.id })
})
it.each([["offline", new Error("offline")], ["5xx", new ApiError("unavailable", 503)]])("keeps the cached server list on a transient %s failure", async (_label, error) => {
seedDetail(); apiFetchMock.mockRejectedValue(error)
await expect(fetchDetail()).rejects.toBe(error)
expect(client.getQueryData(communityKeys.servers())).toEqual([identity.id])
- expect(registry.collections.servers.get(identity.id)).toMatchObject({ ...identity, detailComplete: true })
+ expect(registry.collections.servers.get(identity.id)).toMatchObject(identity)
+ expect(client.getQueryData(communityKeys.server(identity.id))).toMatchObject({ serverId: identity.id, categoryIds: ["cat_1"] })
})
it.each([403, 404])("evicts live and persisted server state on definitive %s", async (status) => {
@@ -333,13 +337,13 @@ describe("useServer / projected canonical detail", () => {
it("does not merge stale positives from the retired server unread endpoint", async () => {
seedList(); apiFetchMock.mockImplementation((url: string) => url.endsWith("/unreads") ? { channelIds: ["c1"], sources: [{ channelId: "c1", lastUnreadSeq: 3 }], stale: true } : detailApi(url))
- await expect(fetchDetail()).resolves.toBe(identity.id)
+ await expect(fetchDetail()).resolves.toMatchObject({ serverId: identity.id })
expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
it("projects child scope metadata and confirms every loaded channel", async () => {
seedList()
- apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [{ id: "forum_1", name: "Forum", type: "forum", categoryId: "cat_1" }] } : detailApi(url))
+ apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [{ id: "forum_1", name: "Forum", type: "forum", categoryId: "cat_1" }].map(row => channelResourceFixture({ ...row, serverId: identity.id })) } : detailApi(url))
await fetchDetail()
expect(registry.collections.channels.get("forum_1")).toMatchObject({ serverId: identity.id, type: "forum" })
})
@@ -348,8 +352,13 @@ describe("useServer / projected canonical detail", () => {
seedDetail([{ id: "c1", name: "One", active: false, unread: false }, { id: "c2", name: "Two", active: false, unread: true }]); attention("c1")
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server?.categories[0]?.channels.map((channel) => channel.unread)).toEqual([true, false]))
+ const currentWindow = client.getQueryData(communityKeys.server(identity.id))
act(() => client.setQueryData(communityKeys.server(identity.id), { id: identity.id, categories: [{ channels: [{ id: "raw", unread: true }] }] }))
- expect(rendered.result.current.server?.categories[0]?.channels.map((channel) => channel.id)).toEqual(["c1", "c2"])
+ expect(registry.collections.channels.has("raw")).toBe(false)
+ expect(registry.collections.channels.has("c1")).toBe(true)
+ expect(registry.collections.channels.has("c2")).toBe(true)
+ act(() => client.setQueryData(communityKeys.server(identity.id), currentWindow))
+ await waitFor(() => expect(rendered.result.current.server?.categories[0]?.channels.map(channel => channel.id)).toEqual(["c1", "c2"]))
})
it("does not retain rolling-deploy server-detail unread without canonical attention", async () => {
@@ -362,15 +371,15 @@ describe("useServer / projected canonical detail", () => {
it("composes a single server detail from canonical resources", async () => {
const legacyChannel = { id: "ch_1", name: "general", type: "text", serverId: identity.id, categoryId: "cat_1", topic: "Legacy topic", parentChannelId: null,
- parentMessageId: null, creatorId: "viewer", position: 2, archived: 0, createdAt: "created", lastMessageAt: null, messageCount: 3 }
- apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [legacyChannel, { ...legacyChannel, id: "ch_2", name: "loose", categoryId: null, archived: 1 }] } : detailApi(url))
+ parentMessageId: null, creatorId: "viewer", position: 2, archived: false, createdAt: "created", lastMessageAt: null, messageCount: 3 }
+ apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [legacyChannel, { ...legacyChannel, id: "ch_2", name: "loose", categoryId: null, archived: true }] } : detailApi(url))
await fetchDetail()
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server).toMatchObject({ ...identity, categories: [{ id: "cat_1", channels: [{ id: "ch_1", unread: false }] }, { id: "__uncategorized__", channels: [{ id: "ch_2", unread: false }] }] }))
- expect(client.getQueryData(communityKeys.server(identity.id))).toBe(identity.id)
+ expect(client.getQueryData(communityKeys.server(identity.id))).toMatchObject({ serverId: identity.id })
expect(client.getQueryData(communityKeys.servers())).toEqual([identity.id])
- expect(registry.collections.channels.get("ch_1")).toMatchObject({ topic: "Legacy topic", createdAt: "created", messageCount: 3, archived: false, resourceComplete: false })
- expect(registry.collections.channels.get("ch_2")).toMatchObject({ archived: true, resourceComplete: false })
+ expect(registry.collections.channels.get("ch_1")).toMatchObject({ topic: "Legacy topic", createdAt: "created", messageCount: 3, archived: false })
+ expect(registry.collections.channels.get("ch_2")).toMatchObject({ archived: true })
})
it("passes the navigation AbortSignal to every server-detail resource", async () => {
@@ -396,10 +405,10 @@ describe("useServer / projected canonical detail", () => {
const rail = fetchList()
await waitFor(() => expect(release).toBeTypeOf("function"))
try {
- await expect(fetchDetail()).resolves.toBe(identity.id)
+ await expect(fetchDetail()).resolves.toMatchObject({ serverId: identity.id })
expect(client.getQueryState(communityKeys.servers())?.fetchStatus).toBe("fetching")
expect(registry.collections.servers.get(identity.id)).toMatchObject(identity)
- } finally { release({ servers: [identity] }); await rail }
+ } finally { release(serverRailResponseFixture({ servers: [identity] }, "viewer")); await rail }
})
it("joins a native in-flight rail read for a cold canonical identity without duplicate IO", async () => {
@@ -410,20 +419,20 @@ describe("useServer / projected canonical detail", () => {
const detail = fetchDetail()
await waitFor(() => expect(apiFetchMock.mock.calls.filter(([url]) => String(url).endsWith("/channels"))).toHaveLength(1))
expect(client.getQueryState(communityKeys.server(identity.id))?.fetchStatus).toBe("fetching")
- release({ servers: [identity] })
- await expect(rail).resolves.toEqual([identity.id]); await expect(detail).resolves.toBe(identity.id)
+ release(serverRailResponseFixture({ servers: [identity] }, "viewer"))
+ await expect(rail).resolves.toEqual([identity.id]); await expect(detail).resolves.toMatchObject({ serverId: identity.id })
expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/servers")).toHaveLength(1)
})
it("reads warm server identity without issuing another list request", async () => {
seedList(); apiFetchMock.mockImplementation(detailApi)
- await expect(fetchDetail()).resolves.toBe(identity.id)
+ await expect(fetchDetail()).resolves.toMatchObject({ serverId: identity.id })
expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/servers")).toHaveLength(0)
expect(apiFetchMock).toHaveBeenCalledTimes(2)
})
it("does not cold-boot forum unread from the retired server unread endpoint", async () => {
- apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [{ id: "forum_1", name: "Forum", type: "forum", categoryId: "cat_1" }] } : detailApi(url))
+ apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [channelResourceFixture({ id: "forum_1", name: "Forum", type: "forum", serverId: identity.id, categoryId: "cat_1" })] } : detailApi(url))
const rendered = renderHook(() => useServer(identity.id), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.server?.categories[0]?.channels[0]?.unread).toBe(false))
expect(rendered.result.current.server?.forumUnreadState).toBeUndefined()
@@ -443,7 +452,7 @@ describe("useServer / projected canonical detail", () => {
it("does not issue a raw server unread read", async () => {
apiFetchMock.mockImplementation(detailApi)
- await expect(fetchDetail()).resolves.toBe(identity.id)
+ await expect(fetchDetail()).resolves.toMatchObject({ serverId: identity.id })
expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
})
@@ -459,9 +468,9 @@ describe("qualified viewer server role", () => {
it.each([false, true])("admits an authoritative owner role with newer forum-presence confirmation=%s", async confirmed => {
const entry = forumConversationEntryFixture("forum", identity.id)
publishAccountAttentionSnapshot(client, {
- snapshot: { scopes: [], items: [], limit: 100, truncated: false, included: {
+ snapshot: { resources: fullResourceBundleFixture("viewer", [serverResourceFixture(identity)], [entry.channel]), scopes: [], items: [], limit: 100, truncated: false, included: {
servers: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator }],
- channels: [entry.channel], dms: [], profiles: [], messages: [],
+ channels: [AttentionIncludedChannelSchema.strip().parse(entry.channel)], dms: [], profiles: [], messages: [],
} },
proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
@@ -471,7 +480,7 @@ describe("qualified viewer server role", () => {
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.anything()))
expect(view.result.current).toBeUndefined()
if (confirmed) await act(async () => { await seedConversationEntry(client, entry) })
- await act(async () => { held.resolve({ servers: [{ ...identity, role: "owner", memberId: "own-member" }] }) })
+ await act(async () => { held.resolve(serverRailResponseFixture({ servers: [{ ...identity, role: "owner", memberId: "own-member" }] }, "viewer")) })
await waitFor(() => expect(view.result.current).toBe("owner"))
view.unmount()
})
@@ -487,7 +496,7 @@ describe("qualified viewer server role", () => {
type: "community:member.update", serverId: identity.id, memberId: "own-member", userId: "viewer", changes: { role: "member" },
}))
await act(async () => {
- held.resolve({ servers: [{ ...identity, role: "owner", memberId: "own-member" }] })
+ held.resolve(serverRailResponseFixture({ servers: [{ ...identity, role: "owner", memberId: "own-member" }] }, "viewer"))
await request
})
const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })
@@ -498,9 +507,9 @@ describe("qualified viewer server role", () => {
it("keeps confirmed membership when an older server list omits it", async () => {
const entry = forumConversationEntryFixture("forum", identity.id)
publishAccountAttentionSnapshot(client, {
- snapshot: { scopes: [], items: [], limit: 100, truncated: false, included: {
+ snapshot: { resources: fullResourceBundleFixture("viewer", [serverResourceFixture(identity)], [entry.channel]), scopes: [], items: [], limit: 100, truncated: false, included: {
servers: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator }],
- channels: [entry.channel], dms: [], profiles: [], messages: [],
+ channels: [AttentionIncludedChannelSchema.strip().parse(entry.channel)], dms: [], profiles: [], messages: [],
} },
proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
@@ -509,18 +518,18 @@ describe("qualified viewer server role", () => {
const request = fetchList()
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.anything()))
await act(async () => { await seedConversationEntry(client, entry) })
- await act(async () => { held.resolve({ servers: [] }); await request })
+ await act(async () => { held.resolve(serverRailResponseFixture({ servers: [] }, "viewer")); await request })
expect(registry.collections.servers.get(identity.id)).toBeDefined()
expect(registry.collections.serverMemberships.get("srv_1:viewer")).toMatchObject({ userId: "viewer", viewer: true })
})
it("uses the live own membership before roster pagination and follows member-id-only demotion", async () => {
- apiFetchMock.mockResolvedValue({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] })
+ apiFetchMock.mockResolvedValue(serverRailResponseFixture({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] }, "viewer"))
await fetchList()
const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })
await waitFor(() => expect(view.result.current).toBe("admin"))
expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual(["/api/community/servers"])
- act(() => publishCommunityChannelDirectory(client, { directory: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator, channels: [] }], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } }))
+ act(() => publishCommunityChannelDirectory(client, { resources: resourceBundleFixture({ viewerId: "viewer", servers: [serverResourceFixture(identity)], serverMemberships: [{ serverId: identity.id, userId: "viewer", memberId: "own-member", role: "admin" }] }), directory: [{ id: identity.id, name: identity.name, discriminator: identity.discriminator, channels: [] }], proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } }))
expect(registry.collections.serverMemberships.get("srv_1:viewer")).toMatchObject({ role: "admin", memberId: "own-member" })
act(() => projectCommunityWsEventToDb(client, { type: "community:member.update", serverId: identity.id, memberId: "own-member", changes: { role: "member" } }))
await waitFor(() => expect(view.result.current).toBe("member"))
@@ -528,7 +537,7 @@ describe("qualified viewer server role", () => {
})
it("retains a current own role when access to an unrelated channel is revoked", async () => {
- apiFetchMock.mockResolvedValue({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] })
+ apiFetchMock.mockResolvedValue(serverRailResponseFixture({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] }, "viewer"))
await fetchList()
const view = renderHook(() => useViewerServerRole(identity.id, "viewer"), { wrapper: Owner })
await waitFor(() => expect(view.result.current).toBe("admin"))
@@ -539,12 +548,14 @@ describe("qualified viewer server role", () => {
it("does not authorize a restored role, a revoked server or another viewer", async () => {
seedList()
- registry.collections.serverMemberships.utils.writeUpsert([{ ...registry.collections.serverMemberships.get("srv_1:viewer")!, role: "admin" }])
+ const restoredMembership = registry.collections.serverMemberships.get("srv_1:viewer")!
+ await registry.collections.serverMemberships.utils.writeUpsert([{ id: restoredMembership.id, serverId: restoredMembership.serverId,
+ userId: restoredMembership.userId, memberId: restoredMembership.memberId, role: "admin", viewer: true }])
const held = deferred<{ servers: Array<typeof identity & { role: string; memberId: string }> }>()
apiFetchMock.mockReturnValue(held.promise)
const view = renderHook(({ viewerId }) => useViewerServerRole(identity.id, viewerId), { wrapper: Owner, initialProps: { viewerId: "viewer" } })
expect(view.result.current).toBeUndefined()
- await act(async () => { const request = fetchList(); held.resolve({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] }); await request })
+ await act(async () => { const request = fetchList(); held.resolve(serverRailResponseFixture({ servers: [{ ...identity, role: "admin", memberId: "own-member" }] }, "viewer")); await request })
await waitFor(() => expect(view.result.current).toBe("admin"))
view.rerender({ viewerId: "other-account" })
expect(view.result.current).toBeUndefined()
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 3518759c5..139a5e9a7 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -1,4 +1,6 @@
"use client"
+import { ServerDirectorySnapshotSchema, getServerDirectoryWindow, type ServerDirectorySnapshot, type ServerDirectoryWindow } from "@/lib/community/server-directory-window"
+import { CommunityChannelResourceSchema, CommunityCategoryResourceSchema, serverSchema, type CommunityCategoryResource } from "@alook/shared"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"
import { useSelector } from "@tanstack/react-store"
@@ -19,7 +21,7 @@ import type { ServerRow } from "@/lib/community-db/schema"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
-import { isServerOwner,UNCATEGORIZED_CATEGORY_ID, type CommunityRole } from "@alook/shared"
+import { isServerOwner, type CommunityRole } from "@alook/shared"
import type { Server,Category,Channel } from "@/lib/community/models/navigation"
import { useCommunityWsStore } from "@/stores/community/ws"
import { useCommunityRuntime } from "@/stores/community/runtime"
@@ -75,12 +77,8 @@ export const serversQueryFn = async (
if (!context?.client) throw new DOMException("Missing server query owner", "AbortError")
const token = captureCommunityLiveSnapshotToken(context.client)
const data = await apiFetch<{ servers: RawServerRow[] }>("/api/community/servers", communityRequestOptions(context.client, token, context.signal))
- const servers: Server[] = data.servers.map((s) => ({
- id: s.id,
- name: s.name,
- discriminator: s.discriminator,
- description: s.description ?? "",
- ownerId: s.ownerId,
+ const servers: Server[] = data.servers.map((s, position) => ({
+ ...serverSchema.parse({ id: s.id, position, name: s.name, discriminator: s.discriminator, description: s.description, ownerId: s.ownerId, icon: s.icon, official: s.official, isOwner: isServerOwner(s.role) }),
initial: avatarInitial(s.name),
active: false,
unread: false,
@@ -88,8 +86,8 @@ export const serversQueryFn = async (
isOwner: isServerOwner(s.role),
...(["owner", "admin", "member"].includes(s.role ?? "") ? { role: s.role as CommunityRole } : {}),
...(s.memberId ? { memberId: s.memberId } : {}),
- icon: s.icon ?? null,
- official: s.official === true,
+ icon: s.icon,
+ official: s.official,
}))
return { servers }
}
@@ -237,40 +235,21 @@ const serverQueryFn = (
queryClient: QueryClient,
serverId: string,
signal?: AbortSignal,
-) => async (): Promise<ServerDetail> => {
+) => async (): Promise<ServerDirectorySnapshot> => {
const token = captureCommunityLiveSnapshotToken(queryClient)
const options = communityRequestOptions(queryClient, token, signal)
const fetchResource = <T,>(path: string) => apiFetch<T>(path, options)
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<{ categories: CommunityCategoryResource[] }>(`/api/community/servers/${serverId}/categories`),
fetchResource<{ channels: RawChannel[] }>(`/api/community/servers/${serverId}/channels`),
])
if (!server) throw new Error("server not found")
- 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),
- }))
- const uncategorized = channels.filter((channel) => !channel.categoryId)
- if (uncategorized.length > 0) {
- categories.push({ id: UNCATEGORIZED_CATEGORY_ID, name: "", private: 0, channels: uncategorized })
- }
- return {
- id: server.id,
- name: server.name,
- discriminator: server.discriminator ?? "",
- description: server.description ?? "",
- icon: server.icon ?? null,
- official: server.official === true,
- ownerId: server.ownerId ?? "",
- categories,
- }
+ return ServerDirectorySnapshotSchema.parse({
+ server,
+ categories: categoryData.categories.map(category => CommunityCategoryResourceSchema.parse(category)),
+ channels: channelData.channels.map(row => CommunityChannelResourceSchema.parse(row)),
+ })
}
function serverDetailReadSuperseded(queryClient: QueryClient, serverId: string, token: CommunityLiveSnapshotToken, signal?: AbortSignal) {
@@ -311,7 +290,9 @@ export const serverProjectedQueryFn = (
snapshot: { kind: "server-detail", data },
proof: { kind: "structural", token: structuralToken, signal: readSignal },
})
- return data.id
+ const window = getServerDirectoryWindow(structuralToken.registry, serverId)
+ if (!window) throw new Error("Directory resource closure mismatch")
+ return window
})
} catch (error) {
if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {
@@ -331,7 +312,7 @@ export const serverProjectedQueryFn = (
*/
export function useServer(
serverId: string | null,
-): UseQueryResult<string> & { server: ServerDetail | null } {
+): UseQueryResult<ServerDirectoryWindow> & { server: ServerDetail | null } {
const dbServer = useServerTreeProjection(serverId)
const queryClient = useQueryClient()
const enabled = !!serverId
diff --git a/src/web/src/hooks/community/use-thread-participants.dom.test.ts b/src/web/src/hooks/community/use-thread-participants.dom.test.ts
index 89df0f9b0..16ed9a5a5 100644
--- a/src/web/src/hooks/community/use-thread-participants.dom.test.ts
+++ b/src/web/src/hooks/community/use-thread-participants.dom.test.ts
@@ -1,3 +1,6 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { readForumSidebarWindowResult } from "@/lib/community/forum-sidebar-window"
+import { serverDirectoryFixture, channelResourceFixture, messageResourceFixture, serverResourceFixture, fullResourceBundleFixture } from "@/test/community-resource-fixtures"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
@@ -28,15 +31,22 @@ function Owner({ children }: PropsWithChildren) {
return createElement(QueryClientProvider, { client }, createElement(CommunityDbProvider, { registry }, children))
}
function seedSidebar(parentType: "forum" | "text" = "forum") {
- ingestServerDetail(registry, { id: "server_1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer_1", categories: [{ id: "category", name: "Channels", channels: [{ id: "forum_1", name: "Forum", type: parentType, active: false, unread: false }] }] })
+ ingestServerDetail(registry, serverDirectoryFixture({ id: "server_1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer_1", categories: [{ id: "category", name: "Channels", channels: [{ id: "forum_1", name: "Forum", type: parentType, active: false, unread: false }] }] }))
const key = communityKeys.forumSidebarThreads("server_1")
- client.setQueryData(key, { ids: ["post_1"], serverNow: "2026-08-08T00:00:00.000Z", serverClockOffsetMs: 0 })
+ const now = new Date().toISOString()
+ const parent = channelResourceFixture({ id: "forum_1", serverId: "server_1", type: parentType })
+ const child = channelResourceFixture({ id: "post_1", serverId: "server_1", type: "thread", name: "Post", parentChannelId: parent.id, parentMessageId: "opener_1", lastMessageAt: now })
+ const opener = messageResourceFixture({ id: "opener_1", channelId: parent.id, authorId: "viewer_1", content: "Post" })
publishCommunityForumSidebar(client, {
- 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", participating: true }],
- openers: [{ id: "opener_1", channelId: "forum_1", content: "Post", type: "chat" }],
+ serverId: "server_1", resources: fullResourceBundleFixture("viewer_1", [serverResourceFixture({ id: "server_1", ownerId: "viewer_1" })], [parent, child], [opener]),
+ channels: [{ ...child, activityAt: now, unread: false, participating: true }], openers: [opener],
proof: { token: captureCommunityLiveSnapshotToken(client) },
})
+ const window = readForumSidebarWindowResult({ serverNow: now, serverClockOffsetMs: 0, window: {
+ version: BUSINESS_SCHEMA_VERSION, accountId: "viewer_1", serverId: "server_1", parents: [parent.id], base: [{ id: child.id, parentChannelId: parent.id, parentMessageId: opener.id }], retained: null,
+ } })
+ if (!window) throw new Error("Invalid current sidebar fixture window")
+ client.setQueryData(key, window)
return key
}
async function command<T>(run: () => Promise<T>) {
diff --git a/src/web/src/hooks/community/use-user-profile.test.ts b/src/web/src/hooks/community/use-user-profile.test.ts
index c0a37bf98..015ee70c5 100644
--- a/src/web/src/hooks/community/use-user-profile.test.ts
+++ b/src/web/src/hooks/community/use-user-profile.test.ts
@@ -71,3 +71,19 @@ describe("useUserProfile / userProfileQueryFn", () => {
expect(registry.collections.profiles.get(profile.id)).toBeUndefined()
})
})
+
+it.each(["missing-core", "wrong-target", "invalid-late-field"])("rejects a warm complete card %s before any canonical write", async defect => {
+ const { communityRegistrySnapshot } = await import("@/test/community-registry-snapshot")
+ const { client, registry } = await createCommunityQueryOwner()
+ const options = { queryKey: communityKeys.profile(profile.id), queryFn: userProfileQueryFn(profile.id) }
+ apiFetchMock.mockResolvedValueOnce(profile)
+ await client.query(options)
+ const before = communityRegistrySnapshot(registry)
+ const malformed: Record<string, unknown> = { ...profile, name: "Must not publish" }
+ if (defect === "missing-core") delete malformed.avatarVersion
+ if (defect === "wrong-target") malformed.id = "foreign-target"
+ if (defect === "invalid-late-field") malformed.mutualServers = -1
+ apiFetchMock.mockResolvedValueOnce(malformed)
+ await expect(client.query(options)).rejects.toThrow()
+ expect(communityRegistrySnapshot(registry)).toEqual(before)
+})
diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.ts
index 4b081302f..c12f986b5 100644
--- a/src/web/src/hooks/community/use-user-profile.ts
+++ b/src/web/src/hooks/community/use-user-profile.ts
@@ -1,9 +1,11 @@
"use client"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { parseCommunityUserCardRead, type CommunityUserCardRead } from "@alook/shared"
+import { apiFetch } from "@/lib/api/client"
import type { QueryFunctionContext } from "@tanstack/react-query"
-import { apiFetchProfiles } from "@/lib/community/profile-seed"
+import { loadAndSeedProfiles } from "@/lib/community/profile-seed"
/**
* Fetches a public user profile card (avatar, name, aboutMe, mutual-server
@@ -13,31 +15,12 @@ import { apiFetchProfiles } from "@/lib/community/profile-seed"
* returns viewer-relative bot ownership. The community query cache is cleared
* on logout, so this response remains scoped to the current viewer session.
*/
-type UserProfileBase = {
- id: string
- name: string
- discriminator: string
- image: string | null
- avatarVersion: number
- aboutMe: string
- bannerColor: string | null
- mutualServers: number
- statusEmoji: string | null
- statusText: string | null
-}
-
-export type UserProfile = UserProfileBase & (
- | { kind: "human" }
- | {
- kind: "bot"
- ownerProfile: { id: string; handle: string }
- ownedByViewer: boolean
- }
-)
+export type UserProfile = CommunityUserCardRead
export const userProfileQueryFn = (userId: string) => async (context: QueryFunctionContext) => {
- const profile = await apiFetchProfiles<UserProfile>(
- `/api/community/users/${userId}/profile`,
+ const registry = getCommunityDbRegistry(context.client)
+ const profile = await loadAndSeedProfiles(
+ async origin => parseCommunityUserCardRead(await apiFetch<unknown>(`/api/community/users/${userId}/profile`, { ...origin, signal: context.signal }), userId, registry!.accountId!),
(profile) => [{
id: profile.id,
identityAbout: {
@@ -61,7 +44,7 @@ export const userProfileQueryFn = (userId: string) => async (context: QueryFunct
ownerHandle: profile.kind === "bot" ? profile.ownerProfile.handle : null,
ownedByViewer: profile.kind === "bot" && profile.ownedByViewer,
},
- }], { signal: context.signal }, getCommunityDbRegistry(context.client),
+ }], registry, context.signal,
)
return { id: profile.id }
}
diff --git a/src/web/src/hooks/community/ws-live-query-config.dom.test.ts b/src/web/src/hooks/community/ws-live-query-config.dom.test.ts
index 6871c7d23..4bf1e88be 100644
--- a/src/web/src/hooks/community/ws-live-query-config.dom.test.ts
+++ b/src/web/src/hooks/community/ws-live-query-config.dom.test.ts
@@ -1,3 +1,4 @@
+import { serverMembersReadFixture, invitesReadFixture, serverRailResponseFixture } from "@/test/community-resource-fixtures"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { renderHook, waitFor } from "@/test/react-dom-harness"
@@ -13,11 +14,11 @@ vi.mock("@/lib/api/client", () => ({ apiFetch: api, toastApiError: vi.fn() }))
beforeEach(() => {
api.mockImplementation(async (path: string) => {
if (path.endsWith("/presence")) return { online: [] }
- if (path.endsWith("/invites")) return { invites: [] }
- if (path.includes("/members")) return { members: [], hasMore: false, limit: 100, total: 0 }
+ if (path.endsWith("/invites")) return invitesReadFixture("srv_1")
+ if (path.includes("/members")) return serverMembersReadFixture("srv_1", [])
if (path.endsWith("/categories")) return { categories: [] }
if (path.endsWith("/channels")) return { channels: [] }
- return { servers: [{ id: "srv_1", name: "Server", discriminator: "0001", ownerId: "viewer", role: "owner", icon: null }] }
+ return serverRailResponseFixture({ servers: [{ id: "srv_1", name: "Server", discriminator: "0001", ownerId: "viewer", role: "owner", memberId: "member-viewer", isOwner: true, icon: null }] })
})
})
diff --git a/src/web/src/lib/api.test.ts b/src/web/src/lib/api.test.ts
index 13149ffe3..51c2ab315 100644
--- a/src/web/src/lib/api.test.ts
+++ b/src/web/src/lib/api.test.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared";
+import { protectCommunityJsonResponse } from "./middleware/response-cache";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { ApiError } from "./errors";
import {
@@ -5,6 +7,11 @@ import {
cancelAccountDeletionAuthTransition,
} from "./api/client";
+async function currentReply(status: number, body: unknown): Promise<Response> {
+ const request = new Request("https://alook.test/api/community/bots", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } });
+ return protectCommunityJsonResponse(request, Response.json(body, { status }));
+}
+
// Mock window globals needed by apiFetch
Object.defineProperty(globalThis, "document", {
value: { cookie: "" },
@@ -68,11 +75,7 @@ async function getApiFetch() {
describe("apiFetch", () => {
it("returns ApiError on 400 with { error } JSON body", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 400,
- json: async () => ({ error: "name is required" }),
- });
+ mockFetch.mockResolvedValueOnce(await currentReply(400, { error: "name is required" }));
const { apiFetch } = await getApiFetch();
try {
@@ -85,14 +88,10 @@ describe("apiFetch", () => {
});
it("propagates details on 400 with details array", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 400,
- json: async () => ({
+ mockFetch.mockResolvedValueOnce(await currentReply(400, {
error: "validation error",
details: ["name: required", "email: invalid"],
- }),
- });
+ }));
const { apiFetch } = await getApiFetch();
try {
@@ -105,14 +104,10 @@ describe("apiFetch", () => {
});
it("turns validation details into a readable error message", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 400,
- json: async () => ({
+ mockFetch.mockResolvedValueOnce(await currentReply(400, {
error: "validation error",
details: ["runtime_id: runtime_id is required"],
- }),
- });
+ }));
const { apiFetch } = await getApiFetch();
try {
@@ -139,11 +134,7 @@ describe("apiFetch", () => {
});
it("returns ApiError with 'Please wait' on 429", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 429,
- json: async () => ({ error: "rate limited" }),
- });
+ mockFetch.mockResolvedValueOnce(await currentReply(429, { error: "rate limited" }));
const { apiFetch } = await getApiFetch();
try {
@@ -157,11 +148,7 @@ describe("apiFetch", () => {
});
it("returns generic message on 500 with non-JSON body", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 500,
- json: async () => { throw new Error("not json"); },
- });
+ mockFetch.mockResolvedValueOnce(new Response("gateway failure", { status: 500, headers: { "Content-Type": "text/plain" } }));
const { apiFetch } = await getApiFetch();
try {
@@ -174,11 +161,7 @@ describe("apiFetch", () => {
});
it("uses server error message on 500 with JSON body", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 500,
- json: async () => ({ error: "database connection failed" }),
- });
+ mockFetch.mockResolvedValueOnce(await currentReply(500, { error: "database connection failed" }));
const { apiFetch } = await getApiFetch();
try {
@@ -190,11 +173,7 @@ describe("apiFetch", () => {
});
it("returns generic message on 502 with empty body", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 502,
- json: async () => { throw new Error("empty"); },
- });
+ mockFetch.mockResolvedValueOnce(new Response("gateway failure", { status: 502, headers: { "Content-Type": "text/plain" } }));
const { apiFetch } = await getApiFetch();
try {
@@ -207,11 +186,7 @@ describe("apiFetch", () => {
});
it("redirects on 401 and throws ApiError", async () => {
- mockFetch.mockResolvedValueOnce({
- ok: false,
- status: 401,
- json: async () => ({ error: "unauthorized" }),
- });
+ mockFetch.mockResolvedValueOnce(await currentReply(401, { error: "unauthorized" }));
const { apiFetch } = await getApiFetch();
try {
@@ -226,11 +201,7 @@ describe("apiFetch", () => {
});
it("does not let an in-flight 401 replace the account-deletion navigation", async () => {
- mockFetch.mockResolvedValue({
- ok: false,
- status: 401,
- json: async () => ({ error: "unauthorized" }),
- });
+ mockFetch.mockResolvedValue(await currentReply(401, { error: "unauthorized" }));
const { apiFetch } = await getApiFetch();
beginAccountDeletionAuthTransition();
@@ -259,11 +230,7 @@ describe("apiFetch — mock network delay", () => {
process.env.NEXT_PUBLIC_MOCK_NETWORK = "true";
vi.resetModules();
- const localMockFetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: async () => [{ id: "a1" }],
- });
+ const localMockFetch = vi.fn().mockResolvedValue(await currentReply(200, [{ id: "a1" }]));
vi.stubGlobal("fetch", localMockFetch);
const { apiFetch } = await import("./api/client");
@@ -282,11 +249,7 @@ describe("apiFetch — mock network delay", () => {
vi.useFakeTimers();
vi.resetModules();
- const localMockFetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: async () => [{ id: "a1" }],
- });
+ const localMockFetch = vi.fn().mockResolvedValue(await currentReply(200, [{ id: "a1" }]));
vi.stubGlobal("fetch", localMockFetch);
const { apiFetch } = await import("./api/client");
@@ -306,11 +269,7 @@ describe("apiFetch — mock network delay", () => {
process.env.NEXT_PUBLIC_MOCK_NETWORK_DELAY_MS = "500";
vi.resetModules();
- const localMockFetch = vi.fn().mockResolvedValue({
- ok: true,
- status: 200,
- json: async () => [{ id: "a1" }],
- });
+ const localMockFetch = vi.fn().mockResolvedValue(await currentReply(200, [{ id: "a1" }]));
vi.stubGlobal("fetch", localMockFetch);
const { apiFetch } = await import("./api/client");
diff --git a/src/web/src/lib/api/client.body-eligibility.test.ts b/src/web/src/lib/api/client.body-eligibility.test.ts
new file mode 100644
index 000000000..f6f8866c4
--- /dev/null
+++ b/src/web/src/lib/api/client.body-eligibility.test.ts
@@ -0,0 +1,150 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityReadErrorSchema } from "@alook/shared"
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
+import { createApplicationOwner, captureApplicationOwner, assertApplicationOwner, retireApplicationOwner } from "@/lib/application-owner"
+import * as lifecycle from "@/lib/business-schema-lifecycle"
+import { apiFetch } from "./client"
+import { ApiError, CommunityApiError } from "@/lib/errors"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { conversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
+import { conversationEntryOptions } from "@/lib/community/conversation-entry"
+
+beforeEach(() => {
+ lifecycle.businessSchemaLifecycle.setState(() => ({ phase: "current", expectedVersion: BUSINESS_SCHEMA_VERSION }))
+ vi.stubGlobal("window", { location: { href: `https://alook.test/c/me?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}` } })
+ vi.stubGlobal("navigator", {})
+})
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
+
+const resource = () => ({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "channel", channel: channelResourceFixture({ id: "channel" }),
+ access: { channelId: "channel", canRead: true, canSend: true, canCreateDiscussion: true } })
+const kinds = ["json", "resource", "abort", "error-json", "error-resource", "error-abort"] as const
+
+async function bodyCase(kind: typeof kinds[number] | "valid" | "error-valid", mode: "active" | "retired" | "aborted") {
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ let start!: () => void
+ const started = new Promise<void>(resolve => { start = resolve })
+ const response = new Response(new ReadableStream<Uint8Array>({ start(value) { controller = value } }), {
+ status: kind === "error-valid" ? 403 : kind.startsWith("error-") ? 400 : 200,
+ headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
+ })
+ const text = response.text.bind(response)
+ vi.spyOn(response, "text").mockImplementation(() => { start(); return text() })
+ vi.stubGlobal("fetch", vi.fn(async () => response))
+ const original = createApplicationOwner("original"), next = createApplicationOwner("next")
+ const token = captureApplicationOwner(original), abort = new AbortController()
+ const upgrade = vi.spyOn(lifecycle, "requestBusinessSchemaUpdate")
+ const result = apiFetch("/api/community/channels/channel", { signal: abort.signal, assertActive: () => assertApplicationOwner(token, abort.signal) }).then(
+ value => ({ value, error: undefined }), error => ({ value: undefined, error: error as Error }),
+ )
+ await started
+ if (mode === "retired") retireApplicationOwner(original)
+ if (mode === "aborted") abort.abort()
+ const protectedOwner = mode === "active" ? original : next
+ const unregister = lifecycle.registerBusinessSchemaOwner(async () => { retireApplicationOwner(protectedOwner) })
+ try {
+ if (kind.endsWith("abort")) controller.error(new DOMException("Body cancelled", "AbortError"))
+ else {
+ const body = kind === "error-valid" ? JSON.stringify(CommunityReadErrorSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: "blocked", message: "blocked", retryable: false } })) : kind === "valid" ? JSON.stringify(resource()) : kind.endsWith("json") ? "{bad-json" : JSON.stringify({ ...resource(), channel: { id: "channel" } })
+ controller.enqueue(new TextEncoder().encode(body)); controller.close()
+ }
+ const completed = await result
+ const shouldUpgrade = mode === "active" && !kind.endsWith("abort") && kind !== "valid"
+ if (shouldUpgrade) {
+ await vi.waitFor(() => expect(lifecycle.businessSchemaLifecycle.get().phase).toBe("failed"))
+ expect(upgrade).toHaveBeenCalledOnce()
+ expect(completed.error?.name).toBe("BusinessSchemaMismatch")
+ expect(protectedOwner.lifecycle.get().active).toBe(false)
+ } else {
+ expect(completed.error?.name).toBe("AbortError")
+ expect(upgrade).not.toHaveBeenCalled()
+ expect(next.lifecycle.get().active).toBe(true)
+ expect(lifecycle.businessSchemaLifecycle.get().phase).toBe("current")
+ }
+ } finally { unregister(); original.queryClient.clear(); next.queryClient.clear() }
+}
+
+describe("actual API body eligibility before global update", () => {
+ it.each(kinds)("keeps a retired owner's late %s body cancelled without retiring its successor", kind => bodyCase(kind, "retired"))
+ it.each(kinds)("keeps a signalled late %s body cancelled without retiring its successor", kind => bodyCase(kind, "aborted"))
+ it.each(kinds)("calibrates an active owner's %s body against cancellation and protocol failure", kind => bodyCase(kind, "active"))
+ it("keeps the existing late valid-body retirement protection", () => bodyCase("valid", "retired"))
+})
+
+it("retains an active non-community JSON parse error without starting a business update", async () => {
+ const upgrade = vi.spyOn(lifecycle, "requestBusinessSchemaUpdate")
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("{bad-json", { headers: { "Content-Type": "application/json" } })))
+ await expect(apiFetch("/api/other-resource")).rejects.toBeInstanceOf(SyntaxError)
+ expect(upgrade).not.toHaveBeenCalled()
+ expect(lifecycle.businessSchemaLifecycle.get().phase).toBe("current")
+})
+
+it.each([["blocked",403],["not_allowed",403],["not_found",404],["temporarily_unavailable",503],["rate_limited",429]] as const)("keeps the actual current %s code through the API error boundary",async(code,status)=>{
+ const payload=CommunityReadErrorSchema.parse({contractVersion:BUSINESS_SCHEMA_VERSION,error:{code,message:code,retryable:status===429||status>=500,details:["reason detail"]}})
+ vi.stubGlobal("fetch",vi.fn(async()=>new Response(JSON.stringify(payload),{status,headers:{"content-type":"application/json",[COMMUNITY_CONTRACT_HEADER]:String(BUSINESS_SCHEMA_VERSION)}})))
+ const failure=await apiFetch("/api/community/channels/dm-a/messages?entry=1").catch(error=>error)
+ expect(failure).toBeInstanceOf(CommunityApiError)
+ expect(failure).toMatchObject({status,code,retryable:status===429||status>=500,details:["reason detail"]})
+})
+it.each(["retired","aborted"] as const)("rejects a valid late blocked error after its owner is %s",mode=>bodyCase("error-valid",mode))
+
+describe("HTTP body transport failure before complete JSON qualification", () => {
+ it.each([200, 403, 404, 503].flatMap(status =>
+ (["active", "retired", "aborted"] as const).map(mode => ({ status, mode })),
+ ))("keeps $status stream failure with $mode owner out of schema retirement", async ({ status, mode }) => {
+ let controller!: ReadableStreamDefaultController<Uint8Array>
+ let beginRead!: () => void
+ const reading = new Promise<void>(resolve => { beginRead = resolve })
+ const response = new Response(new ReadableStream<Uint8Array>({ start(value) { controller = value } }), {
+ status, headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
+ })
+ const text = response.text.bind(response)
+ vi.spyOn(response, "text").mockImplementation(() => { beginRead(); return text() })
+ vi.stubGlobal("fetch", vi.fn(async () => response))
+ const original = createApplicationOwner("stream-original"), next = createApplicationOwner("stream-next")
+ const token = captureApplicationOwner(original), signal = new AbortController()
+ const upgrade = vi.spyOn(lifecycle, "requestBusinessSchemaUpdate")
+ const result = apiFetch("/api/community/channels/channel", {
+ signal: signal.signal, assertActive: () => assertApplicationOwner(token, signal.signal),
+ }).then(value => ({ value, error: undefined }), error => ({ value: undefined, error: error as Error }))
+ await reading
+ if (mode === "retired") retireApplicationOwner(original)
+ if (mode === "aborted") signal.abort()
+ const protectedOwner = mode === "active" ? original : next
+ const unregister = lifecycle.registerBusinessSchemaOwner(async () => { retireApplicationOwner(protectedOwner) })
+ try {
+ controller.error(new TypeError("HTTP body transport disconnected"))
+ const { error } = await result
+ if (mode !== "active") expect(error?.name).toBe("AbortError")
+ else if (status === 200) expect(error).toBeInstanceOf(TypeError)
+ else {
+ expect(error).toBeInstanceOf(ApiError)
+ expect(error).not.toBeInstanceOf(CommunityApiError)
+ expect(error).toMatchObject({ status })
+ expect(error).not.toHaveProperty("code")
+ }
+ expect(upgrade).not.toHaveBeenCalled()
+ expect(protectedOwner.lifecycle.get().active).toBe(true)
+ expect(lifecycle.businessSchemaLifecycle.get().phase).toBe("current")
+ } finally { unregister(); original.queryClient.clear(); next.queryClient.clear() }
+ })
+
+ it.each([403, 404])("keeps actual entry revocation and removes old body when the %s stream fails", async status => {
+ const { client, registry } = await createCommunityQueryOwner()
+ await seedConversationEntry(client, conversationEntryFixture())
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new ReadableStream<Uint8Array>({
+ start(controller) { controller.error(new TypeError("Denied response body disconnected")) },
+ }), { status, headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })))
+ const upgrade = vi.spyOn(lifecycle, "requestBusinessSchemaUpdate")
+ const failure = await client.query({ ...conversationEntryOptions(client, { channelId: "c1", serverId: "s1" }),
+ retry: false, staleTime: 0, select: undefined }).catch(error => error)
+ expect(failure).toBeInstanceOf(ApiError)
+ expect(failure).not.toBeInstanceOf(CommunityApiError)
+ expect(failure).toMatchObject({ status })
+ expect(registry.runtime.ws.actions.isChannelAccessRevoked("c1", "s1")).toBe(true)
+ expect(registry.runtime.ws.get().channelAccessScopes.get("c1")?.denialCode).toBeUndefined()
+ expect(registry.collections.messages.has("m1")).toBe(false)
+ expect(upgrade).not.toHaveBeenCalled()
+ expect(lifecycle.businessSchemaLifecycle.get().phase).toBe("current")
+ })
+})
diff --git a/src/web/src/lib/api/client.ts b/src/web/src/lib/api/client.ts
index 885be345a..9de0bd8d3 100644
--- a/src/web/src/lib/api/client.ts
+++ b/src/web/src/lib/api/client.ts
@@ -1,7 +1,8 @@
-import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestedCommunityContract } from "@alook/shared"
-import { communityReadTarget, decodeCommunityReadResponse } from "@/lib/community/read-response"
+import { BusinessSchemaMismatch, requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, CommunityReadErrorSchema } from "@alook/shared"
+import { decodeCommunityReadResponse } from "@/lib/community/read-response"
import { createStore } from "@tanstack/store";
-import { ApiError, UnauthorizedError, isAbortError } from "@/lib/errors";
+import { ApiError, CommunityApiError, type CommunityApiErrorPayload, UnauthorizedError, isAbortError } from "@/lib/errors";
import { startRequest, requestHeaders, requestRejected, finishRequest, readObservedResponse, runObservedFetch, type RequestObservation } from "@/lib/observability/requests";
const API_BASE = "";
@@ -73,6 +74,18 @@ export function redirectToSignIn(accountId?: string | null) {
export type ApiRequestOptions = RequestInit & { assertActive?: () => void; onUnauthorized?: () => Promise<boolean>; authenticationAccount?: string; observation?: Parameters<typeof startRequest>[1] extends infer O ? O extends { observation?: infer P } ? P : never : never };
+async function readEligibleResponseText(response: Response, qualify: () => void): Promise<string> {
+ qualify();
+ try {
+ const text = await response.text();
+ qualify();
+ return text;
+ } catch (error) {
+ qualify();
+ throw error;
+ }
+}
+
export async function apiFetchResponse(path: string, options?: ApiRequestOptions, bodyExpected = false): Promise<Response> {
const observation = startRequest(path, options);
try {
@@ -106,7 +119,7 @@ async function fetchQualifiedResponse(path: string, options?: ApiRequestOptions,
try {
assertEligible();
const headers = new Headers(request.headers);
- if (communityReadTarget(path, request.method) && !headers.has(COMMUNITY_CONTRACT_HEADER)) headers.set(COMMUNITY_CONTRACT_HEADER, String(COMMUNITY_CONTRACT_VERSION));
+ if (path.startsWith("/api/community/")) headers.set(COMMUNITY_CONTRACT_HEADER, String(COMMUNITY_CONTRACT_VERSION));
if (!headers.has("Content-Type") && !(typeof FormData !== "undefined" && request.body instanceof FormData)) headers.set("Content-Type", "application/json");
res = await runObservedFetch(observation, () => fetch(API_BASE + path, {
...request,
@@ -132,36 +145,61 @@ async function fetchQualifiedResponse(path: string, options?: ApiRequestOptions,
throw new UnauthorizedError();
}
+ const contentType = res.headers.get("Content-Type") ?? "";
+ if (path.startsWith("/api/community/") && (contentType.includes("json") || res.status === 204)
+ && res.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(COMMUNITY_CONTRACT_VERSION)) {
+ throw requestBusinessSchemaUpdate(Number(res.headers.get(COMMUNITY_CONTRACT_HEADER)));
+ }
+
if (!res.ok) {
let serverError: string | undefined;
let details: string[] | undefined;
+ let communityError: CommunityApiErrorPayload | undefined;
+ const currentCommunityError = path.startsWith("/api/community/") && contentType.includes("json");
+ let text: string | undefined;
try {
- const body = (await res.json()) as { error?: string | { message?: string }; details?: string[] };
- serverError = typeof body.error === "string" ? body.error : body.error?.message;
- details = body.details;
- } catch {
- // non-JSON body (HTML from proxy, empty body, etc.)
+ text = await readEligibleResponseText(res, assertEligible);
+ } catch (error) {
+ assertEligible();
+ if (isAbortError(error)) throw error;
+ }
+ if (text !== undefined) try {
+ const body: unknown = JSON.parse(text);
+ assertEligible();
+ if (currentCommunityError) {
+ const parsed = CommunityReadErrorSchema.safeParse(body);
+ if (!parsed.success) throw parsed.error;
+ communityError = parsed.data.error;
+ serverError = parsed.data.error.message;
+ details = parsed.data.error.details;
+ } else if (typeof body === "object" && body !== null) {
+ if ("error" in body && typeof body.error === "string") serverError = body.error;
+ if ("details" in body && Array.isArray(body.details) && body.details.every(detail => typeof detail === "string")) details = body.details;
+ }
+ } catch (error) {
+ assertEligible();
+ if (isAbortError(error)) throw error;
+ if (currentCommunityError) throw error instanceof BusinessSchemaMismatch ? error : requestBusinessSchemaUpdate();
}
assertEligible();
+ const responseError = (message: string) => communityError
+ ? new CommunityApiError(communityError, res.status, message)
+ : new ApiError(message, res.status, details);
if (res.status === 429) {
- throw new ApiError("Please wait a moment before trying again", 429);
+ throw responseError("Please wait a moment before trying again");
}
if (res.status >= 500) {
- throw new ApiError(
+ throw responseError(
getReadableErrorMessage(serverError, details) ||
"Something went wrong — please try again",
- res.status,
- details,
);
}
- throw new ApiError(
+ throw responseError(
getReadableErrorMessage(serverError, details) || "Something went wrong",
- res.status,
- details,
);
}
@@ -169,13 +207,25 @@ async function fetchQualifiedResponse(path: string, options?: ApiRequestOptions,
}
export async function apiFetch<T>(path: string, options?: ApiRequestOptions): Promise<T> {
- const res = await apiFetchResponse(path, options, true);
- if (res.status === 204) return readObservedResponse(res, async () => undefined as T);
- const data = await readObservedResponse(res, async () => decodeCommunityReadResponse(path, options?.method, res, await res.json(), new Headers(options?.headers).has(COMMUNITY_CONTRACT_HEADER) ? requestedCommunityContract(new Headers(options?.headers)) ?? COMMUNITY_CONTRACT_VERSION : COMMUNITY_CONTRACT_VERSION) as T, () => {
+ const qualify = () => {
options?.assertActive?.();
if (options?.signal?.aborted) throw new DOMException("Cancelled request", "AbortError");
- });
- return data;
+ };
+ const res = await apiFetchResponse(path, options, true);
+ if (res.status === 204) return readObservedResponse(res, async () => undefined as T, qualify);
+ return readObservedResponse(res, async () => {
+ const text = await readEligibleResponseText(res, qualify);
+ try {
+ const body: unknown = JSON.parse(text);
+ qualify();
+ return decodeCommunityReadResponse(path, options?.method, res, body, COMMUNITY_CONTRACT_VERSION) as T;
+ } catch (error) {
+ qualify();
+ if (isAbortError(error)) throw error;
+ if (path.startsWith("/api/community/")) throw requestBusinessSchemaUpdate();
+ throw error;
+ }
+ }, qualify);
}
export function getErrorMessage(err: unknown, fallback: string): string {
diff --git a/src/web/src/lib/api/observability-consumers.test.ts b/src/web/src/lib/api/observability-consumers.test.ts
index ce736c70c..3171bbf96 100644
--- a/src/web/src/lib/api/observability-consumers.test.ts
+++ b/src/web/src/lib/api/observability-consumers.test.ts
@@ -1,3 +1,4 @@
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { afterEach, beforeEach, expect, it, vi } from "vitest"
import { apiFetch, readUploadError } from "./client"
import { configureTelemetry, installTelemetrySink, retireTelemetry } from "../observability/telemetry"
@@ -8,7 +9,7 @@ afterEach(() => { retireTelemetry(); vi.unstubAllGlobals() })
it("preserves live multipart JSON parsing, owner checks and sanitized diagnostics", async () => {
const result = { file: { id: "file-a" } }, assertActive = vi.fn()
- fetch.mockResolvedValue(Response.json(result))
+ fetch.mockResolvedValue(Response.json(result, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }))
const body = new FormData()
body.set("file", new File(["private-file-body"], "private.txt"))
expect(await apiFetch("/api/community/channels/channel-a/attachments", { method: "POST", body, assertActive })).toEqual(result)
diff --git a/src/web/src/lib/application-owner.anonymous.dom.test.tsx b/src/web/src/lib/application-owner.anonymous.dom.test.tsx
index 36e317cf1..e9ba5ee9c 100644
--- a/src/web/src/lib/application-owner.anonymous.dom.test.tsx
+++ b/src/web/src/lib/application-owner.anonymous.dom.test.tsx
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityReadErrorSchema } from "@alook/shared"
import "fake-indexeddb/auto"
import { createContext, useContext, useLayoutEffect } from "react"
import { afterEach, beforeEach, expect, it, vi } from "vitest"
@@ -41,7 +42,7 @@ beforeEach(async () => {
vi.stubGlobal("window", new Proxy(real, { get(target, key) { return key === "location" ? { origin: "https://alook.test", reload } : Reflect.get(target, key, target) } }))
vi.stubGlobal("fetch", vi.fn(async (url: string) => {
expect(url).toBe("/api/community/invites/not-a-real-token/info")
- return Response.json({ error: "Invite not found" }, { status: 404 })
+ return Response.json(CommunityReadErrorSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code: "not_found", message: "Invite not found", retryable: false } }), { status: 404, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
}))
})
afterEach(async () => {
diff --git a/src/web/src/lib/application-owner.tsx b/src/web/src/lib/application-owner.tsx
index 230192e19..c1b089658 100644
--- a/src/web/src/lib/application-owner.tsx
+++ b/src/web/src/lib/application-owner.tsx
@@ -11,6 +11,7 @@ import { createQueryClient } from "@/lib/query-client"
import type { ApiRequestOptions } from "@/lib/api/client"
import { captureTelemetryIdentityRetirement, setTelemetryUser } from "@/lib/observability/client"
import { disposeQueryDiagnostics } from "@/lib/observability/query-observer"
+import { registerBusinessSchemaOwner } from "@/lib/business-schema-lifecycle"
export function createApplicationOwner(userId: string, queryClient = createQueryClient()) {
const bindings = createStore({ retireDisk: () => clearPersistedCache(userId), sessionViewer: () => userId as string | null | undefined })
@@ -65,6 +66,11 @@ function ScopedPublicQueryProvider({ userId, children }: { userId: string; child
const [owner] = useState(() => createApplicationOwner(userId))
const [persister] = useState(() => createIdbPersister(accountId))
useLayoutEffect(() => { owner.bindAuthentication(currentSessionViewer, persister.retireAccount) }, [owner, persister])
+ useLayoutEffect(() => registerBusinessSchemaOwner(async () => {
+ retireApplicationOwner(owner)
+ owner.queryClient.clear()
+ await owner.retireDisk()
+ }), [owner])
const onRetired = useCallback(() => {
if (!owner.lifecycle.get().active) return
retireApplicationOwner(owner)
diff --git a/src/web/src/lib/broadcast.test.ts b/src/web/src/lib/broadcast.test.ts
index ac2ba702b..5da2d3812 100644
--- a/src/web/src/lib/broadcast.test.ts
+++ b/src/web/src/lib/broadcast.test.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, createLogger } from "@alook/shared"
+import { currentCommunityEventFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"
const mockInfo = vi.fn()
@@ -25,6 +27,8 @@ vi.mock("@alook/shared", async () => {
})
import { wsDoFetch, broadcastToUser, broadcastToUsers } from "./broadcast"
+import { handleCommunityUsersBroadcast } from "../../../ws-do/src/routes/broadcast"
+import { communityWsEventFixtures } from "../../../shared/test/community-ws-events.fixtures"
const communityEvent = {
type: "community:presence.update",
@@ -267,17 +271,17 @@ describe("broadcastToUser", () => {
expect(String(bindingFetch.mock.calls[0]?.[0])).toBe(
`http://internal/broadcast/community/user/u:${encodeURIComponent(target)}`,
)
- expect(JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))).toEqual(communityEvent)
+ expect(JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))).toEqual(currentCommunityEventFixture(communityEvent))
},
)
- it.each([undefined, "1", "2"])("projects committed membership for producer contract %s before transport", async contract => {
+ it("emits the sole current membership envelope before transport", async () => {
const bindingFetch = vi.fn(async () => Response.json({ sent: 1 }))
- mockGetCloudflareContext.mockReturnValue({ env: { ...makeEnv(bindingFetch), COMMUNITY_EVENT_CONTRACT: contract }, ctx: { waitUntil: mockCtxWaitUntil } })
+ mockGetCloudflareContext.mockReturnValue({ env: makeEnv(bindingFetch), ctx: { waitUntil: mockCtxWaitUntil } })
const event = { type: "community:channel.membership.change", channelId: "thread", serverId: "server", userId: "viewer", relation: "notify", present: true } as const
await broadcastToUser("viewer", event)
- expect(JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))).toEqual(contract === "2" ? event
- : { type: "community:channel.member_add", channelId: "thread", serverId: "server", userId: "viewer" })
+ expect(JSON.parse(String(bindingFetch.mock.calls[0]?.[1]?.body))).toEqual(currentCommunityEventFixture(event))
+ expect(bindingFetch.mock.calls[0]?.[1]?.headers).toEqual({ "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) })
expect(bindingFetch).toHaveBeenCalledTimes(1)
expect(mockFetch).not.toHaveBeenCalled()
})
@@ -370,6 +374,30 @@ describe("broadcastToUsers", () => {
return { promise, resolve, reject }
}
+ it.each([
+ "community:channel.delete", "community:channel.child_update", "community:identity.update", "community:reaction.remove",
+ ] as const)("passes actual %s bulk producer bytes through strict receiver admission", async type => {
+ const forwarded: Request[] = []
+ const stubFetch = vi.fn(async (request: Request) => { forwarded.push(request); return Response.json({ sent: 1 }) })
+ const receiverEnv = { WS_DO: { idFromName: vi.fn((name: string) => name), get: vi.fn(() => ({ fetch: stubFetch })) } }
+ const logger = { ...createLogger({ service: "bulk-contract-test" }), child: () => logger }
+ const bindingFetch = vi.fn(async (input: unknown, init?: RequestInit) => {
+ const request = new Request(String(input), init)
+ const response = await handleCommunityUsersBroadcast({ request, url: new URL(request.url), traceId: undefined,
+ env: receiverEnv as unknown as Parameters<typeof handleCommunityUsersBroadcast>[0]["env"], log: logger })
+ if (!response) throw new Error("strict receiver route did not match")
+ expect(response.status).toBe(200)
+ return response
+ })
+ setBinding(bindingFetch)
+ const event = communityWsEventFixtures[type]
+ await broadcastToUsers(["bob", "alice", "bob", "excluded"], event, "excluded")
+ expect(receiverEnv.WS_DO.idFromName.mock.calls.map(([name]) => name)).toEqual(["user:bob", "user:alice"])
+ expect(forwarded).toHaveLength(2)
+ for (const request of forwarded) expect(await request.json()).toEqual(currentCommunityEventFixture(event))
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
+
it("keeps non-community bulk events on the generic bulk route unchanged", async () => {
const bindingFetch = vi.fn(async () => Response.json({ sent: 2 }))
setBinding(bindingFetch)
@@ -434,7 +462,7 @@ describe("broadcastToUsers", () => {
expect(bindingFetch.mock.calls.every((call) => (
String(call[0]) === "http://internal/broadcast/community/users"
&& call[1]?.method === "POST"
- && JSON.stringify(call[1]?.headers) === JSON.stringify({ "Content-Type": "application/json" })
+ && JSON.stringify(call[1]?.headers) === JSON.stringify({ "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) })
))).toBe(true)
expect(mockInfo).toHaveBeenCalledWith(
"broadcast_users_complete",
diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.ts
index 680528bff..97c8b2dd7 100644
--- a/src/web/src/lib/broadcast.ts
+++ b/src/web/src/lib/broadcast.ts
@@ -1,3 +1,4 @@
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import type { WsMessage, DaemonPushMessage } from "@alook/shared"
import {
@@ -11,21 +12,16 @@ import {
type CommunityContract,
} from "@alook/shared"
import { fetchViaBindingOrDevFallback } from "./dev-binding-fetch"
-import { communityProducerContract, projectCommunityProducerEvent } from "./community/producer-contract"
+import { communityProducerContract } from "./community/producer-contract"
const log = createLogger({ service: "broadcast" })
const bulkBroadcastMaxUserIds = 1000
const bulkBroadcastMaxActive = 3
function encodeCommunityProducerEvent(message: unknown) {
- const { env } = getCloudflareContext()
- const contract = communityProducerContract(env as Env)
- const encoded = encodeCommunityBrowserEvent(message, contract === 3 ? 3 : 2)
- if (!encoded.ok) return encoded
- const wire = encoded.event.type === "community:channel.membership.change"
- ? encodeCommunityBrowserEvent(projectCommunityProducerEvent(encoded.event, env as Env, contract === 3 ? 3 : 2), contract)
- : encoded
- return wire.ok ? { ...wire, contract } : wire
+ const contract = communityProducerContract()
+ const encoded = encodeCommunityBrowserEvent(message, contract)
+ return encoded.ok ? { ...encoded, contract } : encoded
}
/**
@@ -65,7 +61,7 @@ async function doSend(
const { env } = getCloudflareContext()
const res = await wsDoFetch(env as Env, url, {
method: "POST",
- headers: { "Content-Type": "application/json", ...(opts.contract === 3 ? { [COMMUNITY_CONTRACT_HEADER]: "3" } : {}) },
+ headers: { "Content-Type": "application/json", ...(opts.contract === COMMUNITY_RESOURCE_CONTRACT_VERSION ? { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) } : {}) },
body,
}, opts)
if (!res.ok) {
@@ -152,7 +148,7 @@ async function runBroadcastToUsers(
}
const encoded = community ? encodeCommunityProducerEvent(message) : null
if (encoded && !encoded.ok) throw new Error(`invalid community event: ${encoded.reason}`)
- const wireMessage = encoded?.event ?? message
+ const wireMessage = encoded?.envelope ?? message
const chunks: string[][] = []
for (let start = 0; start < targetUserIds.length; start += bulkBroadcastMaxUserIds) {
diff --git a/src/web/src/lib/business-schema-lifecycle.test.ts b/src/web/src/lib/business-schema-lifecycle.test.ts
new file mode 100644
index 000000000..d8022e1e1
--- /dev/null
+++ b/src/web/src/lib/business-schema-lifecycle.test.ts
@@ -0,0 +1,104 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { CURRENT_DOCUMENT_REQUEST, WORKER_VERSION_PROBE } from "./service-worker/business-upgrade"
+import { businessSchemaLifecycle, registerBusinessSchemaOwner, requestBusinessSchemaUpdate, retryBusinessSchemaUpdate } from "./business-schema-lifecycle"
+
+beforeEach(() => businessSchemaLifecycle.setState(() => ({ phase: "current", expectedVersion: BUSINESS_SCHEMA_VERSION })))
+afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers() })
+
+describe("business protocol retirement", () => {
+ it("retires owners and stops after an already attempted document fails again", async () => {
+ const replace = vi.fn()
+ vi.stubGlobal("window", { location: { href: `https://alook.test/c/me?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}`, replace } })
+ vi.stubGlobal("navigator", {})
+ const retire = vi.fn().mockResolvedValue(undefined)
+ const unregister = registerBusinessSchemaOwner(retire)
+ try {
+ expect(requestBusinessSchemaUpdate().name).toBe("BusinessSchemaMismatch")
+ await vi.waitFor(() => expect(businessSchemaLifecycle.get().phase).toBe("failed"))
+ requestBusinessSchemaUpdate()
+ expect(retire).toHaveBeenCalledTimes(1)
+ expect(replace).not.toHaveBeenCalled()
+ } finally { unregister() }
+ })
+
+ it("bounds an unavailable worker and only retries on an explicit action", async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal("window", { location: { href: "https://alook.test/c/me" } })
+ const getRegistration = vi.fn(() => new Promise<ServiceWorkerRegistration>(() => {}))
+ vi.stubGlobal("navigator", { serviceWorker: { getRegistration } })
+ requestBusinessSchemaUpdate(BUSINESS_SCHEMA_VERSION + 1)
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(businessSchemaLifecycle.get()).toEqual({ phase: "failed", expectedVersion: BUSINESS_SCHEMA_VERSION + 1 })
+ requestBusinessSchemaUpdate()
+ expect(getRegistration).toHaveBeenCalledTimes(1)
+ retryBusinessSchemaUpdate()
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(getRegistration).toHaveBeenCalledTimes(2)
+ expect(businessSchemaLifecycle.get().phase).toBe("failed")
+ })
+ it("checks the new controller when it changes during the old version probe", async () => {
+ vi.useFakeTimers()
+ class FakeChannel {
+ port1 = { onmessage: null as ((event: { data: unknown }) => void) | null, close: vi.fn() }
+ port2 = { postMessage: (data: unknown) => this.port1.onmessage?.({ data }), close: vi.fn() }
+ }
+ vi.stubGlobal("MessageChannel", FakeChannel)
+ vi.stubGlobal("window", { location: { href: "https://alook.test/c/me" } })
+ let oldReply: { postMessage(data: unknown): void } | undefined
+ const old = { postMessage: vi.fn((_message: unknown, ports: Array<{ postMessage(data: unknown): void }>) => { oldReply = ports[0] }) }
+ const next = { postMessage: vi.fn((message: { type: string }, ports: Array<{ postMessage(data: unknown): void }>) => {
+ if (message.type === WORKER_VERSION_PROBE) ports[0].postMessage({ schemaVersion: BUSINESS_SCHEMA_VERSION + 1 })
+ if (message.type === CURRENT_DOCUMENT_REQUEST) ports[0].postMessage({ navigating: true })
+ }) }
+ const serviceWorker = Object.assign(new EventTarget(), { controller: old as typeof old | typeof next,
+ getRegistration: vi.fn(async () => registration) })
+ const registration = Object.assign(new EventTarget(), { update: vi.fn(async () => undefined), active: old, installing: null, waiting: null })
+ vi.stubGlobal("navigator", { serviceWorker })
+ requestBusinessSchemaUpdate(BUSINESS_SCHEMA_VERSION + 1)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(oldReply).toBeDefined()
+ serviceWorker.controller = next
+ serviceWorker.dispatchEvent(new Event("controllerchange"))
+ oldReply!.postMessage({ schemaVersion: BUSINESS_SCHEMA_VERSION })
+ await vi.advanceTimersByTimeAsync(0)
+ expect(next.postMessage.mock.calls.map(call => call[0].type)).toEqual([WORKER_VERSION_PROBE, CURRENT_DOCUMENT_REQUEST])
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+})
+
+it.each(["normal", "storage-denied", "public-path"])("bounds the no-worker document fallback: %s", async mode => {
+ const replace = vi.fn()
+ vi.stubGlobal("window", { location: { href: mode === "public-path" ? "https://alook.test/blog" : "https://alook.test/c/me", replace } })
+ vi.stubGlobal("navigator", {})
+ const stored = new Map<string, string>()
+ vi.stubGlobal("sessionStorage", { getItem: (key: string) => { if (mode === "storage-denied") throw new Error("denied"); return stored.get(key) ?? null }, setItem: (key: string, value: string) => { if (mode === "storage-denied") throw new Error("denied"); stored.set(key, value) } })
+ requestBusinessSchemaUpdate()
+ if (mode === "public-path") await vi.waitFor(() => expect(businessSchemaLifecycle.get().phase).toBe("failed"))
+ else await vi.waitFor(() => expect(replace).toHaveBeenCalledWith(`https://alook.test/c/me?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}`))
+ if (mode === "normal") expect(stored.get("alook:business-schema-update-attempt")).toBe(String(BUSINESS_SCHEMA_VERSION))
+ if (mode === "public-path") expect(replace).not.toHaveBeenCalled()
+})
+
+it("fails when a current worker explicitly refuses navigation and closes both reply ports", async () => {
+ vi.useFakeTimers()
+ const closed: ReturnType<typeof vi.fn>[] = []
+ class Channel {
+ port1 = { onmessage: null as ((event: { data: unknown }) => void) | null, close: vi.fn() }
+ port2 = { postMessage: (data: unknown) => this.port1.onmessage?.({ data }), close: vi.fn() }
+ constructor() { closed.push(this.port1.close, this.port2.close) }
+ }
+ const worker = { postMessage: (message: { type: string }, ports: Array<{ postMessage(data: unknown): void }>) => ports[0]!.postMessage(message.type === WORKER_VERSION_PROBE ? { schemaVersion: BUSINESS_SCHEMA_VERSION + 1 } : { navigating: false }) }
+ vi.stubGlobal("MessageChannel", Channel)
+ vi.stubGlobal("window", { location: { href: "https://alook.test/c/me" } })
+ vi.stubGlobal("sessionStorage", { getItem: () => null, setItem: vi.fn() })
+ const registration = Object.assign(new EventTarget(), { update: vi.fn(async () => {}), active: worker, waiting: null, installing: null })
+ vi.stubGlobal("navigator", { serviceWorker: Object.assign(new EventTarget(), { controller: worker, getRegistration: vi.fn(async () => registration) }) })
+ requestBusinessSchemaUpdate(BUSINESS_SCHEMA_VERSION + 1)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(businessSchemaLifecycle.get()).toEqual({ phase: "failed", expectedVersion: BUSINESS_SCHEMA_VERSION + 1 })
+ expect(closed.length).toBeGreaterThan(0)
+ expect(closed.every(close => close.mock.calls.length > 0)).toBe(true)
+ expect(vi.getTimerCount()).toBe(0)
+})
diff --git a/src/web/src/lib/business-schema-lifecycle.ts b/src/web/src/lib/business-schema-lifecycle.ts
new file mode 100644
index 000000000..72cb8349f
--- /dev/null
+++ b/src/web/src/lib/business-schema-lifecycle.ts
@@ -0,0 +1,124 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { createStore } from "@tanstack/store"
+import { BUSINESS_UPDATE_MARKER, CURRENT_DOCUMENT_REQUEST, WORKER_VERSION_PROBE, businessUpdateUrl, probeBusinessVersion } from "./service-worker/business-upgrade"
+
+type UpdateState = { phase: "current" | "updating" | "failed"; expectedVersion: number }
+export const businessSchemaLifecycle = createStore<UpdateState>({ phase: "current", expectedVersion: BUSINESS_SCHEMA_VERSION })
+const owners = new Set<() => Promise<void>>()
+const attemptKey = "alook:business-schema-update-attempt"
+
+export class BusinessSchemaMismatch extends Error {
+ constructor(public expectedVersion = BUSINESS_SCHEMA_VERSION as number) {
+ super("This page needs an update")
+ this.name = "BusinessSchemaMismatch"
+ }
+}
+
+export function registerBusinessSchemaOwner(retire: () => Promise<void>) {
+ owners.add(retire)
+ if (businessSchemaLifecycle.get().phase !== "current") void retire()
+ return () => { owners.delete(retire) }
+}
+
+export function rememberBusinessUpdateAttempt() {
+ const marker = new URL(window.location.href).searchParams.get(BUSINESS_UPDATE_MARKER)
+ if (marker) try { sessionStorage.setItem(attemptKey, marker) } catch { }
+}
+
+export function requestBusinessSchemaUpdate(expectedVersion: number = BUSINESS_SCHEMA_VERSION) {
+ const expected = Number.isSafeInteger(expectedVersion) && expectedVersion > 0 ? Math.max(BUSINESS_SCHEMA_VERSION, expectedVersion) : BUSINESS_SCHEMA_VERSION
+ const error = new BusinessSchemaMismatch(expected)
+ if (typeof window !== "undefined" && businessSchemaLifecycle.get().phase === "current") void updateDocument(expected, false)
+ return error
+}
+
+export function retryBusinessSchemaUpdate() {
+ if (businessSchemaLifecycle.get().phase === "failed") void updateDocument(businessSchemaLifecycle.get().expectedVersion, true)
+}
+
+async function updateDocument(expectedVersion: number, explicitRetry: boolean) {
+ businessSchemaLifecycle.setState(() => ({ phase: "updating", expectedVersion }))
+ await withDeadline(Promise.allSettled([...owners].map(async retire => retire())), 3000).catch(() => undefined)
+ try {
+ const marker = new URL(window.location.href).searchParams.get(BUSINESS_UPDATE_MARKER)
+ let previous: string | null = marker
+ try { previous = sessionStorage.getItem(attemptKey) ?? marker } catch { }
+ if (!explicitRetry && previous === String(expectedVersion)) throw new BusinessSchemaMismatch(expectedVersion)
+ if (!("serviceWorker" in navigator)) {
+ const next = businessUpdateUrl(window.location.href, expectedVersion)
+ if (!next) throw new BusinessSchemaMismatch(expectedVersion)
+ try { sessionStorage.setItem(attemptKey, String(expectedVersion)) } catch { }
+ window.location.replace(next)
+ return
+ }
+ const registration = await withDeadline(navigator.serviceWorker.getRegistration(), 10_000)
+ if (!registration) throw new BusinessSchemaMismatch(expectedVersion)
+ await withDeadline(registration.update(), 10_000)
+ registration.waiting?.postMessage({ type: "SKIP_WAITING" })
+ const worker = await currentWorker(registration, expectedVersion)
+ const next = new URL(window.location.href)
+ if (explicitRetry) next.searchParams.delete(BUSINESS_UPDATE_MARKER)
+ if (!businessUpdateUrl(next.href, expectedVersion)) throw new BusinessSchemaMismatch(expectedVersion)
+ try { sessionStorage.setItem(attemptKey, String(expectedVersion)) } catch { }
+ const channel = new MessageChannel()
+ await withDeadline(new Promise<void>((resolve, reject) => {
+ channel.port1.onmessage = event => {
+ channel.port1.close()
+ channel.port2.close()
+ if (event.data?.navigating === true) resolve()
+ else reject(new BusinessSchemaMismatch(expectedVersion))
+ }
+ worker.postMessage({ type: CURRENT_DOCUMENT_REQUEST, schemaVersion: expectedVersion, explicitRetry }, [channel.port2])
+ }), 10_000).finally(() => { channel.port1.close(); channel.port2.close() })
+ } catch {
+ businessSchemaLifecycle.setState(() => ({ phase: "failed", expectedVersion }))
+ }
+}
+
+async function currentWorker(registration: ServiceWorkerRegistration, expectedVersion: number): Promise<ServiceWorker> {
+ return new Promise((resolve, reject) => {
+ let checking = false
+ let pending = false
+ let finished = false
+ let installing: ServiceWorker | null = null
+ const cleanup = () => {
+ finished = true
+ clearTimeout(timer)
+ navigator.serviceWorker.removeEventListener("controllerchange", check)
+ registration.removeEventListener("updatefound", watchInstalling)
+ installing?.removeEventListener("statechange", check)
+ }
+ const check = async () => {
+ if (finished) return
+ if (checking) { pending = true; return }
+ checking = true
+ do {
+ pending = false
+ registration.waiting?.postMessage({ type: "SKIP_WAITING" })
+ const worker = navigator.serviceWorker.controller ?? registration.active
+ const version = worker ? await probeBusinessVersion(worker, WORKER_VERSION_PROBE) : null
+ if (finished) return
+ if (worker && version === expectedVersion && worker === (navigator.serviceWorker.controller ?? registration.active)) {
+ cleanup(); resolve(worker); return
+ }
+ } while (pending)
+ checking = false
+ }
+ const watchInstalling = () => {
+ installing?.removeEventListener("statechange", check)
+ installing = registration.installing
+ installing?.addEventListener("statechange", check)
+ void check()
+ }
+ const timer = setTimeout(() => { cleanup(); reject(new Error("Update unavailable")) }, 10_000)
+ navigator.serviceWorker.addEventListener("controllerchange", check)
+ registration.addEventListener("updatefound", watchInstalling)
+ watchInstalling()
+ })
+}
+
+async function withDeadline<T>(promise: Promise<T>, milliseconds: number): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try { return await Promise.race([promise, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Update unavailable")), milliseconds) })]) }
+ finally { clearTimeout(timer) }
+}
diff --git a/src/web/src/lib/business-schema-response-recovery.test.ts b/src/web/src/lib/business-schema-response-recovery.test.ts
new file mode 100644
index 000000000..1b645fba7
--- /dev/null
+++ b/src/web/src/lib/business-schema-response-recovery.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { apiFetch } from "./api/client"
+import { businessSchemaLifecycle, retryBusinessSchemaUpdate } from "./business-schema-lifecycle"
+import { CURRENT_DOCUMENT_REQUEST, WORKER_VERSION_PROBE } from "./service-worker/business-upgrade"
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ businessSchemaLifecycle.setState(() => ({ phase: "current", expectedVersion: BUSINESS_SCHEMA_VERSION }))
+})
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.useRealTimers() })
+
+function install(version: number, initiallyAvailable: boolean) {
+ class Channel {
+ port1 = { onmessage: null as ((event: { data: unknown }) => void) | null, close: vi.fn() }
+ port2 = { postMessage: (data: unknown) => this.port1.onmessage?.({ data }), close: vi.fn() }
+ }
+ const messages: Array<{ type: string; schemaVersion?: number }> = []
+ const worker = { postMessage: vi.fn((message: { type: string; schemaVersion?: number }, ports?: Array<{ postMessage(data: unknown): void }>) => {
+ messages.push(message)
+ if (message.type === WORKER_VERSION_PROBE) ports![0].postMessage({ schemaVersion: BUSINESS_SCHEMA_VERSION })
+ if (message.type === CURRENT_DOCUMENT_REQUEST) ports![0].postMessage({ navigating: true })
+ }) }
+ const registration = Object.assign(new EventTarget(), { update: vi.fn(async () => undefined), active: worker, waiting: null, installing: null })
+ let available = initiallyAvailable, header = version
+ const getRegistration = vi.fn(async () => available ? registration : undefined)
+ const serviceWorker = Object.assign(new EventTarget(), { getRegistration, controller: worker })
+ const storage = new Map<string, string>()
+ const replace = vi.fn()
+ vi.stubGlobal("MessageChannel", Channel)
+ vi.stubGlobal("window", { location: { href: "https://alook.test/c/me", replace } })
+ vi.stubGlobal("navigator", { serviceWorker })
+ vi.stubGlobal("sessionStorage", { getItem: (key: string) => storage.get(key) ?? null, setItem: (key: string, value: string) => storage.set(key, value) })
+ const fetch = vi.fn(async () => Response.json({ contractVersion: header }, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(header) } }))
+ vi.stubGlobal("fetch", fetch)
+ return { messages, getRegistration, replace, fetch, recover: () => { available = true; header = BUSINESS_SCHEMA_VERSION } }
+}
+
+describe("actual confirmation rejection and document lifecycle", () => {
+ it("recovers an old confirmation through explicit Retry to the available current worker", async () => {
+ const h = install(BUSINESS_SCHEMA_VERSION - 1, false)
+ const error = await apiFetch("/api/community/channels/channel").catch(error => error)
+ expect(error.name).toBe("BusinessSchemaMismatch")
+ await vi.advanceTimersByTimeAsync(0)
+ const selected = businessSchemaLifecycle.get().expectedVersion
+ expect(businessSchemaLifecycle.get().phase).toBe("failed")
+ h.recover()
+ retryBusinessSchemaUpdate()
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect({ selected, finalExpected: businessSchemaLifecycle.get().expectedVersion,
+ phase: businessSchemaLifecycle.get().phase,
+ documents: h.messages.filter(message => message.type === CURRENT_DOCUMENT_REQUEST).map(message => message.schemaVersion) })
+ .toEqual({ selected: BUSINESS_SCHEMA_VERSION, finalExpected: BUSINESS_SCHEMA_VERSION, phase: "updating", documents: [BUSINESS_SCHEMA_VERSION] })
+ expect(h.getRegistration).toHaveBeenCalledTimes(2)
+ expect(h.fetch).toHaveBeenCalledOnce()
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it("fails finitely for an unavailable actual future confirmation without choosing the current document", async () => {
+ const expected = BUSINESS_SCHEMA_VERSION + 1
+ const h = install(expected, true)
+ await expect(apiFetch("/api/community/channels/channel")).rejects.toMatchObject({ name: "BusinessSchemaMismatch", expectedVersion: expected })
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(businessSchemaLifecycle.get()).toEqual({ phase: "failed", expectedVersion: expected })
+ retryBusinessSchemaUpdate()
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(businessSchemaLifecycle.get()).toEqual({ phase: "failed", expectedVersion: expected })
+ expect(h.messages.filter(message => message.type === CURRENT_DOCUMENT_REQUEST)).toEqual([])
+ expect(h.getRegistration).toHaveBeenCalledTimes(2)
+ expect(h.replace).not.toHaveBeenCalled()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/src/web/src/lib/cache.test.ts b/src/web/src/lib/cache.test.ts
index 89dc7f2f1..f58e7648e 100644
--- a/src/web/src/lib/cache.test.ts
+++ b/src/web/src/lib/cache.test.ts
@@ -1,5 +1,10 @@
+import { z } from "zod";
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared";
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { cached, invalidate, invalidateMany, bindCacheKV, cacheKeys, getKV, throttled } from "./cache";
+import { businessCacheKey, cached, invalidate, invalidateMany, bindCacheKV, cacheKeys, getKV, throttled } from "./cache";
+
+const dataSchema = z.strictObject({ data: z.string() });
+const envelope = (cacheKey: string, value: unknown) => JSON.stringify({ schemaVersion: BUSINESS_SCHEMA_VERSION, cacheKey, value });
function createMockKV() {
const store = new Map<string, { value: string; expiration?: number }>();
@@ -22,11 +27,29 @@ describe("cache", () => {
});
describe("cached()", () => {
+ it.each([
+ { schemaVersion: BUSINESS_SCHEMA_VERSION - 1, cacheKey: "scoped", value: { data: "old" } },
+ { schemaVersion: BUSINESS_SCHEMA_VERSION, cacheKey: "other", value: { data: "wrong scope" } },
+ { schemaVersion: BUSINESS_SCHEMA_VERSION, cacheKey: "scoped", value: {} },
+ { data: "unversioned" },
+ ])("rejects an invalid cache envelope and writes only the checked D1 value", async bad => {
+ mockKV._store.set(businessCacheKey("scoped"), { value: JSON.stringify(bad) });
+ const load = vi.fn(async () => ({ data: "D1" }));
+ expect(await cached("scoped", 300, load, dataSchema)).toEqual({ data: "D1" });
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(mockKV._store.get(businessCacheKey("scoped"))?.value).toBe(envelope("scoped", { data: "D1" }));
+ });
+
+ it("does not publish a malformed D1 result", async () => {
+ await expect(cached("invalid-db", 300, async () => ({}), dataSchema)).rejects.toThrow();
+ expect(mockKV.put).not.toHaveBeenCalled();
+ });
+
it("returns cached value on KV hit", async () => {
- mockKV._store.set("test-key", { value: JSON.stringify({ data: "from-kv" }) });
+ mockKV._store.set(businessCacheKey("test-key"), { value: envelope("test-key", { data: "from-kv" }) });
const fn = vi.fn(async () => ({ data: "from-db" }));
- const result = await cached("test-key", 300, fn);
+ const result = await cached("test-key", 300, fn, dataSchema);
expect(result).toEqual({ data: "from-kv" });
expect(fn).not.toHaveBeenCalled();
@@ -35,13 +58,13 @@ describe("cache", () => {
it("calls fn and stores to KV on cache miss", async () => {
const fn = vi.fn(async () => ({ data: "from-db" }));
- const result = await cached("miss-key", 600, fn);
+ const result = await cached("miss-key", 600, fn, dataSchema);
expect(result).toEqual({ data: "from-db" });
expect(fn).toHaveBeenCalledOnce();
expect(mockKV.put).toHaveBeenCalledWith(
- "miss-key",
- JSON.stringify({ data: "from-db" }),
+ businessCacheKey("miss-key"),
+ envelope("miss-key", { data: "from-db" }),
{ expirationTtl: 600 },
);
});
@@ -51,7 +74,7 @@ describe("cache", () => {
const fn = vi.fn(async () => ({ data: "fallback" }));
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- const result = await cached("error-key", 300, fn);
+ const result = await cached("error-key", 300, fn, dataSchema);
expect(result).toEqual({ data: "fallback" });
expect(fn).toHaveBeenCalledOnce();
@@ -66,7 +89,7 @@ describe("cache", () => {
const fn = vi.fn(async () => ({ data: "ok" }));
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
- const result = await cached("write-fail-key", 300, fn);
+ const result = await cached("write-fail-key", 300, fn, dataSchema);
expect(result).toEqual({ data: "ok" });
await new Promise((r) => setTimeout(r, 10));
@@ -79,11 +102,11 @@ describe("cache", () => {
it("clamps TTL to minimum 60s for KV write", async () => {
const fn = vi.fn(async () => "val");
- await cached("ttl-key", 5, fn);
+ await cached("ttl-key", 5, fn, z.string());
expect(mockKV.put).toHaveBeenCalledWith(
- "ttl-key",
- JSON.stringify("val"),
+ businessCacheKey("ttl-key"),
+ envelope("ttl-key", "val"),
{ expirationTtl: 60 },
);
});
@@ -91,7 +114,7 @@ describe("cache", () => {
it("does not store null values to KV", async () => {
const fn = vi.fn(async () => null);
- const result = await cached("null-key", 300, fn as () => Promise<unknown>);
+ const result = await cached("null-key", 300, fn, z.null());
expect(result).toBeNull();
expect(mockKV.put).not.toHaveBeenCalled();
@@ -101,7 +124,7 @@ describe("cache", () => {
bindCacheKV(null);
const fn = vi.fn(async () => ({ data: "no-kv" }));
- const result = await cached("no-kv-key", 300, fn);
+ const result = await cached("no-kv-key", 300, fn, dataSchema);
expect(result).toEqual({ data: "no-kv" });
expect(fn).toHaveBeenCalledOnce();
@@ -112,7 +135,7 @@ describe("cache", () => {
it("deletes key from KV", async () => {
mockKV._store.set("del-key", { value: "x" });
await invalidate("del-key");
- expect(mockKV.delete).toHaveBeenCalledWith("del-key");
+ expect(mockKV.delete).toHaveBeenCalledWith(businessCacheKey("del-key"));
});
it("logs warning on KV delete failure", async () => {
@@ -139,9 +162,9 @@ describe("cache", () => {
it("deletes all specified keys", async () => {
await invalidateMany(["k1", "k2", "k3"]);
expect(mockKV.delete).toHaveBeenCalledTimes(3);
- expect(mockKV.delete).toHaveBeenCalledWith("k1");
- expect(mockKV.delete).toHaveBeenCalledWith("k2");
- expect(mockKV.delete).toHaveBeenCalledWith("k3");
+ expect(mockKV.delete).toHaveBeenCalledWith(businessCacheKey("k1"));
+ expect(mockKV.delete).toHaveBeenCalledWith(businessCacheKey("k2"));
+ expect(mockKV.delete).toHaveBeenCalledWith(businessCacheKey("k3"));
});
it("does not throw when some deletes fail", async () => {
@@ -165,9 +188,9 @@ describe("cache", () => {
describe("cacheKeys", () => {
it("generates correct key formats", () => {
- expect(cacheKeys.member("ws1", "usr1")).toBe("mem:ws1:usr1");
- expect(cacheKeys.user("usr1")).toBe("usr:usr1");
- expect(cacheKeys.allEmailAccounts("ws1")).toBe("ea:ws1");
+ expect(cacheKeys.member("ws1", "usr1")).toBe("task-payload:member-instruction:ws1:usr1");
+ expect(cacheKeys.user("usr1")).toBe("task-payload:user-identity:usr1");
+ expect(cacheKeys.allEmailAccounts("ws1")).toBe("task-payload:email-addresses:ws1");
expect(cacheKeys.allHandles("ws1")).toBe("handles:ws1");
expect(cacheKeys.machineToken("al_1234567890abcdefghij_rest")).toBe("mt:al_1234567890abcdefg");
expect(cacheKeys.runtimeIds("ws1", "d1")).toBe("rt:ws1:d1");
@@ -263,7 +286,7 @@ describe("cache", () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
// cached() should fall through to fn
- const result = await cached("key", 300, async () => "db-value");
+ const result = await cached("key", 300, async () => "db-value", z.string());
expect(result).toBe("db-value");
// invalidate() should not throw
diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.ts
index 244fecdc1..9d298a626 100644
--- a/src/web/src/lib/cache.ts
+++ b/src/web/src/lib/cache.ts
@@ -50,6 +50,9 @@
* update is genuinely harmless) → KV via this module is fine.
*/
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared";
+import { z } from "zod";
+
const log = {
warn(msg: string, ctx: Record<string, unknown>) {
console.log(JSON.stringify({ level: "warn", service: "cache", msg, ...ctx, ts: new Date().toISOString() }));
@@ -68,25 +71,36 @@ export function getKV(): KVNamespace | null {
const MIN_KV_TTL = 60;
+export function businessCacheKey(key: string) {
+ return `business:${BUSINESS_SCHEMA_VERSION}:${key}`;
+}
+
export async function cached<T>(
key: string,
ttlSeconds: number,
fn: () => Promise<T>,
+ schema: z.ZodType<T>,
): Promise<T> {
const kv = getKV();
+ const physicalKey = businessCacheKey(key);
if (kv) {
try {
- const raw = await kv.get(key);
- if (raw) return JSON.parse(raw) as T;
+ const raw = await kv.get(physicalKey);
+ if (raw) {
+ const decoded = z.strictObject({ schemaVersion: z.literal(BUSINESS_SCHEMA_VERSION), cacheKey: z.literal(key), value: schema }).safeParse(JSON.parse(raw));
+ if (decoded.success) return decoded.data.value;
+ await kv.delete(physicalKey);
+ }
+ await kv.delete(key);
} catch (err) {
log.warn("KV read failed", { key, err });
}
}
- const value = await fn();
+ const value = schema.parse(await fn());
if (value != null && kv) {
- kv.put(key, JSON.stringify(value), { expirationTtl: Math.max(ttlSeconds, MIN_KV_TTL) }).catch((err) => {
+ await kv.put(physicalKey, JSON.stringify({ schemaVersion: BUSINESS_SCHEMA_VERSION, cacheKey: key, value }), { expirationTtl: Math.max(ttlSeconds, MIN_KV_TTL) }).catch((err) => {
log.warn("KV write failed", { key, err });
});
}
@@ -138,7 +152,7 @@ export async function throttled(
export async function invalidate(key: string): Promise<void> {
const kv = getKV();
- if (kv) await kv.delete(key).catch((err) => {
+ if (kv) await kv.delete(key.startsWith("mt:") ? key : businessCacheKey(key)).catch((err) => {
log.warn("KV invalidate failed", { key, err });
});
}
@@ -146,17 +160,17 @@ export async function invalidate(key: string): Promise<void> {
export async function invalidateMany(keys: string[]): Promise<void> {
const kv = getKV();
if (!kv || keys.length === 0) return;
- await Promise.all(keys.map((key) => kv.delete(key).catch((err) => {
+ await Promise.all(keys.map((key) => kv.delete(key.startsWith("mt:") ? key : businessCacheKey(key)).catch((err) => {
log.warn("KV invalidate failed", { key, err });
})));
}
export const cacheKeys = {
machineToken: (token: string) => `mt:${token.slice(0, 20)}`,
- member: (workspaceId: string, userId: string) => `mem:${workspaceId}:${userId}`,
+ member: (workspaceId: string, userId: string) => `task-payload:member-instruction:${workspaceId}:${userId}`,
runtimeIds: (workspaceId: string, daemonId: string) => `rt:${workspaceId}:${daemonId}`,
- user: (userId: string) => `usr:${userId}`,
- allEmailAccounts: (workspaceId: string) => `ea:${workspaceId}`,
+ user: (userId: string) => `task-payload:user-identity:${userId}`,
+ allEmailAccounts: (workspaceId: string) => `task-payload:email-addresses:${workspaceId}`,
allHandles: (workspaceId: string) => `handles:${workspaceId}`,
overviewEmailAccounts: (workspaceId: string) => `ov_ea:${workspaceId}`,
overviewEmailStats: (workspaceId: string) => `ov_email:${workspaceId}`,
diff --git a/src/web/src/lib/community-db/projections-unowned.dom.test.ts b/src/web/src/lib/community-db/projections-unowned.dom.test.ts
index aed5197f7..3c133359b 100644
--- a/src/web/src/lib/community-db/projections-unowned.dom.test.ts
+++ b/src/web/src/lib/community-db/projections-unowned.dom.test.ts
@@ -1,3 +1,5 @@
+import { createElement, type PropsWithChildren } from "react"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { expect, it, vi } from "vitest"
import { renderHook } from "@/test/react-dom-harness"
import { configureTelemetry, retireTelemetry } from "@/lib/observability/telemetry"
@@ -10,8 +12,10 @@ it("does not attribute an upstream cached tree snapshot to an absent community o
const { useServerTreeProjection } = await import("./projections")
configureTelemetry({ session_id: "snapshot-session" }, true)
try {
- const rendered = renderHook(() => useServerTreeProjection("server-a"))
- expect(rendered.result.current).toMatchObject({ id: "server-a", name: "Unowned snapshot", categories: [] })
+ const client = new QueryClient()
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client }, children)
+ const rendered = renderHook(() => useServerTreeProjection("server-a"), { wrapper })
+ expect(rendered.result.current).toBeUndefined()
rendered.unmount()
} finally { retireTelemetry() }
})
diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.ts
index 2865f75f1..5009aa463 100644
--- a/src/web/src/lib/community-db/projections.dom.test.ts
+++ b/src/web/src/lib/community-db/projections.dom.test.ts
@@ -1,3 +1,7 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { channelResourceFixture, categoryResourceFixture, serverResourceFixture, messageSeedFixture } from "@/test/community-resource-fixtures"
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
+import { serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { dehydrate, QueryClient, QueryClientProvider } from "@tanstack/react-query"
import React, { type ReactNode } from "react"
import { describe, expect, it, vi } from "vitest"
@@ -36,7 +40,7 @@ describe("community DB projections", () => {
const rendered = renderHook(() => {
const profiles = useCanonicalProfilesProjection(["peer"])
const disabled = useServerMemberProjection(null, [])
- return { profiles, disabled, state: getMemberReadState(true, { pending: false, failed: false }, [profiles], ["peer"], profiles.data) }
+ return { profiles, disabled, state: getMemberReadState(true, { pending: false, failed: false }, [profiles], ["peer"], profiles.resourceProfiles) }
}, { wrapper })
try {
await waitFor(() => expect(rendered.result.current.profiles.isLoading).toBe(true))
@@ -45,7 +49,7 @@ describe("community DB projections", () => {
await act(async () => reject(new Error("controlled profile restore failure")))
await waitFor(() => expect(rendered.result.current.profiles.isError).toBe(true))
expect(rendered.result.current.state).toEqual({ loading: false, failed: true })
- await act(async () => client.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ identityComplete: false, id: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 1 })]))
+ await act(async () => client.setQueryData(communityKeys.communityDbCollection(registry.scopeId, "profiles"), [profileSchema.parse({ id: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 1 })]))
await waitFor(() => expect(rendered.result.current.state).toEqual({ loading: false, failed: false }))
expect(rendered.result.current.profiles.data.get("peer")?.discriminator).toBe("0042")
} finally { rendered.unmount(); await registry.cleanup(); client.clear() }
@@ -62,10 +66,10 @@ describe("community DB projections", () => {
await waitFor(() => expect(rendered.result.current.profiles.isReady).toBe(true))
const { profiles, disabled } = rendered.result.current
expect(profiles.data.get("peer")).toMatchObject({ id: "peer", presence: "online" })
- expect(getMemberReadState(true, { pending: false, failed: false }, [profiles], ["peer"], profiles.data)).toEqual({ loading: false, failed: true })
- expect(getMemberReadState(true, { pending: false, failed: false }, [profiles], [], profiles.data)).toEqual({ loading: false, failed: false })
- expect(getMemberReadState(true, { pending: false, failed: false }, [disabled], [], profiles.data)).toEqual({ loading: true, failed: false })
- expect(getMemberReadState(false, { pending: true, failed: true }, [disabled], ["peer"], profiles.data)).toEqual({ loading: false, failed: false })
+ expect(getMemberReadState(true, { pending: false, failed: false }, [profiles], ["peer"], profiles.resourceProfiles)).toEqual({ loading: false, failed: true })
+ expect(getMemberReadState(true, { pending: false, failed: false }, [profiles], [], profiles.resourceProfiles)).toEqual({ loading: false, failed: false })
+ expect(getMemberReadState(true, { pending: false, failed: false }, [disabled], [], profiles.resourceProfiles)).toEqual({ loading: true, failed: false })
+ expect(getMemberReadState(false, { pending: true, failed: true }, [disabled], ["peer"], profiles.resourceProfiles)).toEqual({ loading: false, failed: false })
} finally { rendered.unmount(); await registry.cleanup(); client.clear() }
})
it("keeps disabled channel arrays unresolved and active empty selections empty while restore is pending", async () => {
@@ -95,8 +99,8 @@ describe("community DB projections", () => {
const client = new QueryClient()
const registry = createCommunityDbRegistry(client, "viewer")
await registry.preload()
- ingestMessages(registry, "c1", [{ id: "selected", type: "chat", content: "Before" }])
- ingestMessages(registry, "other", [{ id: "unrelated", type: "chat", content: "Foreign" }])
+ ingestMessages(registry, "c1", messageSeedFixture("c1", [{ id: "selected", type: "chat", content: "Before" }]))
+ ingestMessages(registry, "other", messageSeedFixture("other", [{ id: "unrelated", type: "chat", content: "Foreign" }]))
const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children),
)
@@ -105,7 +109,7 @@ describe("community DB projections", () => {
})
try {
await waitFor(() => expect([...rendered.result.current?.keys() ?? []]).toEqual(["selected"]))
- act(() => ingestMessages(registry, "c1", [{ id: "selected", type: "chat", content: "After" }]))
+ act(() => ingestMessages(registry, "c1", messageSeedFixture("c1", [{ id: "selected", type: "chat", content: "After" }])))
await waitFor(() => expect(rendered.result.current?.get("selected")?.content).toBe("After"))
expect(registry.collections.messages.get("unrelated")?.content).toBe("Foreign")
rendered.rerender({ ids: [] })
@@ -116,7 +120,7 @@ describe("community DB projections", () => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const registry = createCommunityDbRegistry(client, "viewer")
await registry.preload()
- const seed = (name: string) => ingestServers(registry, { servers: [{ id: "s1", name, initial: "S", active: false, unread: false, mentions: 0, ownerId: "viewer" }] })
+ const seed = (name: string) => ingestServers(registry, serverRailResponseFixture({ servers: [{ id: "s1", name, initial: "S", active: false, unread: false, mentions: 0, ownerId: "viewer" }] }, (registry)!.accountId))
seed("Before")
const wrapper = ({ children }: { children: ReactNode }) => React.createElement(React.StrictMode, null,
React.createElement(QueryClientProvider, { client }, React.createElement(CommunityDbProvider, { registry }, children)))
@@ -148,7 +152,7 @@ describe("community DB projections", () => {
id: "s1", name, initial: "S", active: false, unread: false,
mentions: 0, ownerId: "viewer",
}] })
- ingestServers(registry, servers("Server"))
+ ingestServers(registry, serverRailResponseFixture(servers("Server"), (registry)!.accountId))
const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
QueryClientProvider,
{ client: queryClient },
@@ -164,14 +168,14 @@ describe("community DB projections", () => {
const before = rendered.result.current
const beforeRenders = renders
await act(async () => {
- ingestMessages(registry, "unrelated-channel", [{ id: "m1", type: "chat", content: "First" }])
- ingestMessages(registry, "unrelated-channel", [{ id: "m1", type: "chat", content: "Changed" }])
+ ingestMessages(registry, "unrelated-channel", messageSeedFixture("unrelated-channel", [{ id: "m1", type: "chat", content: "First" }]))
+ ingestMessages(registry, "unrelated-channel", messageSeedFixture("unrelated-channel", [{ id: "m1", type: "chat", content: "Changed" }]))
})
expect(registry.collections.messages.get("m1")?.content).toBe("Changed")
expect(rendered.result.current).toBe(before)
expect(renders).toBe(beforeRenders)
- await act(async () => ingestServers(registry, servers("Renamed")))
+ await act(async () => ingestServers(registry, serverRailResponseFixture(servers("Renamed"), (registry)!.accountId)))
await waitFor(() => expect(rendered.result.current?.servers[0]?.name).toBe("Renamed"))
} finally {
rendered.unmount()
@@ -180,6 +184,8 @@ describe("community DB projections", () => {
})
it("keeps every projection unresolved without a registry owner", () => {
+ const client = new QueryClient()
+ const wrapper = ({ children }: { children: ReactNode }) => React.createElement(QueryClientProvider, { client }, children)
const rendered = renderHook(() => ({
restored: useTrustedRestoredPrimary(),
rail: useServerRailProjection(),
@@ -190,7 +196,7 @@ describe("community DB projections", () => {
messagesById: useCanonicalMessagesById(),
notifications: useNotificationSettingsProjection(),
directory: useChannelRefDirectoryProjection(),
- }))
+ }), { wrapper })
expect(rendered.result.current).toEqual({
restored: false,
@@ -225,7 +231,7 @@ describe("community DB projections", () => {
const queryClient = new QueryClient()
const registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
- ingestServers(registry, {
+ ingestServers(registry, serverRailResponseFixture({
servers: [{
id: "s1",
name: "Server",
@@ -235,7 +241,7 @@ describe("community DB projections", () => {
mentions: 0,
ownerId: "viewer",
}],
- })
+ }, (registry)!.accountId))
const wrapper = ({ children }: { children: ReactNode }) => React.createElement(
QueryClientProvider,
{ client: queryClient },
@@ -244,7 +250,7 @@ describe("community DB projections", () => {
const rendered = renderHook(() => useServerTreeProjection("s1"), { wrapper })
expect(rendered.result.current).toBeUndefined()
- act(() => ingestServerDetail(registry, {
+ act(() => ingestServerDetail(registry, serverDirectoryFixture({
id: "s1",
name: "Server",
discriminator: "0001",
@@ -252,13 +258,13 @@ describe("community DB projections", () => {
icon: null,
ownerId: "viewer",
categories: [],
- }))
+ })))
await waitFor(() => expect(rendered.result.current).toMatchObject({
id: "s1",
categories: [],
}))
- act(() => ingestServers(registry, {
+ act(() => ingestServers(registry, serverRailResponseFixture({
servers: [{
id: "s1",
name: "Server renamed",
@@ -268,7 +274,7 @@ describe("community DB projections", () => {
mentions: 0,
ownerId: "viewer",
}],
- }))
+ }, (registry)!.accountId)))
await waitFor(() => expect(rendered.result.current?.name).toBe("Server renamed"))
rendered.unmount()
@@ -279,7 +285,7 @@ describe("community DB projections", () => {
const queryClient = new QueryClient()
const legacyServers = [
{
- id: "z-first",
+ id: "z-first", position: 0,
name: "First",
discriminator: "0001",
description: "",
@@ -287,12 +293,9 @@ describe("community DB projections", () => {
icon: null,
official: false,
isOwner: true,
- unread: false,
- mentions: 0,
- detailComplete: false,
},
{
- id: "a-second",
+ id: "a-second", position: 1,
name: "Second",
discriminator: "0001",
description: "",
@@ -300,9 +303,6 @@ describe("community DB projections", () => {
icon: null,
official: false,
isOwner: true,
- unread: false,
- mentions: 0,
- detailComplete: false,
},
]
queryClient.setQueryData(
@@ -315,7 +315,7 @@ describe("community DB projections", () => {
id: `${server.id}:viewer`,
serverId: server.id,
userId: "viewer",
- role: "owner",
+ role: "owner", memberId: `member-${server.id}`,
viewer: true,
})),
)
@@ -334,10 +334,10 @@ describe("community DB projections", () => {
await waitFor(() => expect(rendered.result.current?.servers.map((server) => server.id))
.toEqual(["z-first", "a-second"]))
- act(() => ingestServers(registry, {
+ act(() => ingestServers(registry, serverRailResponseFixture({
servers: [
{
- id: "z-first",
+ id: "z-first", position: 0,
name: "First",
initial: "F",
active: false,
@@ -346,7 +346,7 @@ describe("community DB projections", () => {
ownerId: "viewer",
},
{
- id: "a-second",
+ id: "a-second", position: 1,
name: "Second",
initial: "S",
active: false,
@@ -355,7 +355,7 @@ describe("community DB projections", () => {
ownerId: "viewer",
},
],
- }))
+ }, (registry)!.accountId)))
await waitFor(() => expect(rendered.result.current?.servers.map((server) => server.id))
.toEqual(["z-first", "a-second"]))
@@ -370,20 +370,19 @@ describe("community DB projections", () => {
communityKeys.communityDbCollection("viewer", name),
rows,
)
- collection("servers", [{
+ collection("servers", [serverResourceFixture({
id: "s1", position: 0, name: "Server", discriminator: "0001", description: "desc",
- ownerId: "owner", icon: null, official: true, isOwner: false, unread: true,
- mentions: 2, detailComplete: true,
- }])
+ ownerId: "owner", icon: null, official: true, isOwner: false,
+ })])
collection("serverMemberships", [{
- id: "s1:viewer", serverId: "s1", userId: "viewer", role: "member", viewer: true,
+ id: "s1:viewer", serverId: "s1", userId: "viewer", role: "member", viewer: true, memberId: "member-s1",
}])
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 },
+ { ...categoryResourceFixture({ id: "cat2", serverId: "s1", name: "Later", position: 2 }), pending: false },
+ { ...categoryResourceFixture({ id: "cat1", serverId: "s1", name: "General", position: 1 }), pending: false },
])
const channelBase = {
- position: 1, archived: false, muted: false, unread: false, tags: [], pending: false,
+ ...channelResourceFixture({ serverId: "s1", position: 1 }), muted: false, tags: [], pending: false,
}
collection("channels", [
{ ...channelBase, id: "c2", serverId: "s1", categoryId: "cat1", name: "later", type: "text", position: 2 },
@@ -391,26 +390,26 @@ describe("community DB projections", () => {
{ ...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, lastMessageAt: "2026-09-25T00:00:00.000Z" },
+ { ...channelBase, id: "dm1", serverId: null, categoryId: null, name: "Peer", type: "dm", preview: "hello", lastMessageAt: "2026-09-25T00:00:00.000Z" },
{ ...channelBase, id: "dm-no-read-state", serverId: null, categoryId: null, name: "Quiet", type: "dm", lastMessageAt: "2026-09-25T00:00:01.000Z" },
{ ...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" },
+ { id: "dm1:viewer:access", channelId: "dm1", userId: "viewer", relation: "access", source: "added" },
+ { id: "dm1:peer:access", channelId: "dm1", userId: "peer", relation: "access", source: "added" },
+ { id: "dm-no-read-state:quiet:access", channelId: "dm-no-read-state", userId: "quiet", relation: "access", source: "added" },
+ { id: "dm-no-profile:ghost:access", channelId: "dm-no-profile", userId: "ghost", relation: "access", source: "added" },
])
collection("profiles", [
- { identityComplete: true, id: "viewer", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 1 },
- { identityComplete: true, id: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 2 },
- { identityComplete: true, id: "quiet", name: "Quiet", discriminator: "0003", avatar: "Q", avatarVersion: 1 },
+ { id: "viewer", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 1 },
+ { id: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 2 },
+ { id: "quiet", name: "Quiet", discriminator: "0003", avatar: "Q", avatarVersion: 1 },
])
- collection("messages", [
+ collection("messages", messageSeedFixture("c1", [
{ 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,
@@ -424,8 +423,8 @@ describe("community DB projections", () => {
])
collection("readStateClock", [{ id: "account", revision: 1 }])
collection("folders", [
- { id: "f2", name: "Later", position: 2 },
- { id: "f1", name: "Folder", position: 1 },
+ { id: "f2", name: "Later" },
+ { id: "f1", name: "Folder" },
])
collection("folderItems", [
{ id: "f1:missing", folderId: "f1", serverId: "missing", position: 2 },
@@ -435,6 +434,9 @@ describe("community DB projections", () => {
{ id: "server:s1", serverId: "s1", level: "all" },
{ id: "channel:c1", channelId: "c1", level: "mentions" },
])
+ queryClient.setQueryData(communityKeys.server("s1"), {
+ schemaVersion: BUSINESS_SCHEMA_VERSION, accountId: "viewer", serverId: "s1", categoryIds: ["cat1", "cat2"], channelIds: ["c1", "c2", "forum1", "forum2"],
+ })
const input = readCommunityRestoredCollections({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(queryClient) }, "viewer")
const registry = createCommunityDbRegistry(queryClient, "viewer")
await registry.preload()
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 6c51dd5c1..41cf3b36c 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -1,5 +1,10 @@
"use client"
+import type { CommunityResourceProfile } from "@alook/shared"
+
+import { getServerDirectoryWindow, readServerDirectoryWindow, serverDirectoryWindowComplete } from "@/lib/community/server-directory-window"
+import { communityKeys } from "@/lib/query-keys"
+import { useQuery } from "@tanstack/react-query"
import { forumSidebarWindowComplete, type ForumSidebarWindow } from "@/lib/community/forum-sidebar-window"
import { createContext, createElement, useContext, useMemo, type Context, type ReactNode } from "react"
@@ -17,7 +22,7 @@ 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 { presentCanonicalMessage } from "@/lib/community/message-wire"
-import type { CommunityMessagePreview } from "@alook/shared"
+import type { CommunityMessageResource } from "@alook/shared"
import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
import type { CommunityDbRegistry } from "./collections"
import { communityCollectionQuery, communityJoinedMessagesQuery } from "./queries"
@@ -35,7 +40,7 @@ import type {
ServerRow,
} from "./schema"
-function projectedCanonicalMessage(message: MessageRow, child?: ChannelRow): CommunityMessagePreview & { resourceComplete: boolean } {
+function projectedCanonicalMessage(message: MessageRow, child?: ChannelRow): CommunityMessageResource {
return { ...message, ...(child ? { thread: { id: child.id, name: child.name ?? "", messageCount: child.messageCount ?? 0, lastReplyAt: child.lastMessageAt ?? undefined, tags: child.tags, preview: child.preview, participantCount: child.participantCount } } : {}) }
}
@@ -196,6 +201,8 @@ export function useServerRailProjection() {
}
export function useServerTreeProjection(serverId: string | null) {
+ const registry = useOptionalCommunityDbRegistry()
+ const directory = useQuery({ queryKey: communityKeys.server(serverId ?? "__none__"), enabled: false, select: readServerDirectoryWindow }).data
const servers = useCollectionQuery("servers", ({ row }) => eq(row.id, serverId ?? ""))
const categories = useCollectionQuery("categories", ({ row }) => eq(row.serverId, serverId ?? ""))
const channels = useCollectionQuery("channels", ({ row }) => eq(row.serverId, serverId ?? ""))
@@ -205,9 +212,9 @@ export function useServerTreeProjection(serverId: string | null) {
return useMemo(() => {
if (!ready || !serverId || !rows.servers || !rows.categories || !rows.channels) return undefined
const server = rows.servers.find((candidate) => candidate.id === serverId)
- if (!server?.detailComplete) return undefined
+ if (!server || !registry || !directory || !serverDirectoryWindowComplete(directory, { servers: [...registry.collections.servers.base.values()], categories: [...registry.collections.categories.base.values()], channels: [...registry.collections.channels.base.values()] }, registry.accountId, serverId)) return undefined
const channels = rows.channels.filter((channel) => (
- channel.serverId === serverId && channel.type !== "thread"
+ channel.serverId === serverId && channel.type !== "thread" && (directory.channelIds.includes(channel.id) || channel.pending)
))
const channelView = (channel: ChannelRow): Category["channels"][number] => ({
id: channel.id,
@@ -221,7 +228,7 @@ export function useServerTreeProjection(serverId: string | null) {
pending: channel.pending,
})
const categories: Category[] = rows.categories
- .filter((category) => category.serverId === serverId)
+ .filter((category) => category.serverId === serverId && (directory.categoryIds.includes(category.id) || category.pending))
.sort((a, b) => a.position - b.position)
.map((category) => ({
id: category.id,
@@ -247,7 +254,7 @@ export function useServerTreeProjection(serverId: string | null) {
ownerId: server.ownerId, categories,
}
return view
- }, [attention, ready, rows.servers, rows.categories, rows.channels, serverId])
+ }, [attention, ready, rows.servers, rows.categories, rows.channels, serverId, directory, registry])
}
export function useDmProjection() {
@@ -386,6 +393,7 @@ export function useCanonicalProfilesProjection(userIds?: readonly string[]) {
const previewProfiles = useCommunityPreviewProfiles()
const projection = useCollectionQuery("profiles", ({ row }) => userIds === undefined ? eq(1, 1) : inArray(row.id, [...userIds]))
const { registry } = projection
+ const resourceProfiles: ReadonlyMap<string, CommunityResourceProfile> = useMemo(() => new Map((projection.data ?? []).map(profile => [profile.id, profile])), [projection.data])
const livePresence = useSelector(registry?.runtime.ws ?? absentPresence, (state) => previewProfiles ? null : userIds === undefined ? [...state.presenceByUserId] : userIds.map((id) => [id, state.presenceByUserId.get(id)] as const), { compare: (left, right) => left === right || (!!left && !!right && left.length === right.length && left.every(([id, presence], index) => id === right[index]?.[0] && presence === right[index]?.[1])) })
const data: ReadonlyMap<string, CommunityProfile> = useMemo(() => {
if (previewProfiles) return previewProfiles
@@ -401,7 +409,7 @@ export function useCanonicalProfilesProjection(userIds?: readonly string[]) {
}
return merged
}, [projection.data, livePresence, previewProfiles])
- return { ...projection, data, isReady: !!previewProfiles || projection.isReady, isError: !previewProfiles && projection.isError, isEnabled: !!previewProfiles || projection.isEnabled }
+ return { ...projection, data, resourceProfiles, isReady: !!previewProfiles || projection.isReady, isError: !previewProfiles && projection.isError, isEnabled: !!previewProfiles || projection.isEnabled }
}
export function useCanonicalProfilesByUserId(userIds?: readonly string[]): ReadonlyMap<string, CommunityProfile> {
@@ -413,12 +421,12 @@ export function getMemberReadState(
transport: { pending: boolean; failed: boolean },
projections: readonly { isReady: boolean; isError: boolean; isEnabled: boolean }[],
userIds: readonly string[],
- profiles: ReadonlyMap<string, CommunityProfile>,
+ profiles: ReadonlyMap<string, CommunityResourceProfile>,
) {
if (!enabled) return { loading: false, failed: false }
const failed = transport.failed || projections.some((projection) => projection.isError)
const loading = !failed && (transport.pending || projections.some((projection) => !projection.isEnabled || !projection.isReady))
- const missingProfile = !loading && userIds.some((id) => !profiles.get(id)?.name || !profiles.get(id)?.discriminator)
+ const missingProfile = !loading && userIds.some((id) => !profiles.has(id))
return { loading, failed: failed || missingProfile }
}
@@ -514,7 +522,7 @@ export function useServerSidebarProjection(
return { server, projection: undefined, status: failed ? "error" as const : "pending" as const, needsRead: false }
}
const complete = !!server && (!channels.some(row => supportsSidebarThreads(row.type))
- || !!window && forumSidebarWindowComplete(window, { servers, channels, channelMemberships, messages }, registry.accountId, serverId, retainId, serverNowMs))
+ || !!window && forumSidebarWindowComplete(window, { directory: getServerDirectoryWindow(registry, serverId), servers, channels, channelMemberships, messages }, registry.accountId, serverId, retainId, serverNowMs))
const projection = projectForumSidebar(channels, channelMemberships, messages, registry.accountId, serverId, retainId, serverNowMs, attention)
return { server, projection, status: complete ? "ready" as const : failed ? "error" as const : "pending" as const,
needsRead: !!server && !!window && !complete }
diff --git a/src/web/src/lib/community-db/restore.test.ts b/src/web/src/lib/community-db/restore.test.ts
index b6752e8ea..7f207a1e0 100644
--- a/src/web/src/lib/community-db/restore.test.ts
+++ b/src/web/src/lib/community-db/restore.test.ts
@@ -1,3 +1,5 @@
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { serverDirectoryFixture, messageResourceFixture, serverResourceFixture, channelResourceFixture } from "@/test/community-resource-fixtures"
import { afterEach, describe, expect, it, vi } from "vitest"
import { dehydrate, QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
@@ -31,8 +33,9 @@ function input(rows: Partial<Record<CommunityCollectionName, object[]>>) {
return restored
}
-const message = (id: string, channelId = "c1", content = "Disk") => ({ id, channelId, resourceComplete: false as const, type: "chat" as const, content, seq: 1, createdAt: "2026-10-01T00:00:00.000Z" })
-const server = (id: string) => ({ id, position: 0, name: id, discriminator: "0001", description: "", ownerId: "viewer", icon: null, official: false, isOwner: true, unread: false, mentions: 0, detailComplete: false })
+const message = (id: string, channelId = "c1", content = "Disk") => messageResourceFixture({ id, channelId, authorId: "viewer", content, seq: 1, createdAt: "2026-10-01T00:00:00.000Z" })
+const server = (id: string) => serverResourceFixture({ id, name: id, discriminator: "0001" })
+const profile = (id: string, name: string, avatarVersion = 0) => ({ id, name, discriminator: "0042", avatar: null, avatarVersion })
afterEach(async () => {
for (const { registry, release } of owners.splice(0)) {
@@ -47,15 +50,15 @@ describe("canonical disk input precedence", () => {
it("keeps fresh RSC fields and fills uncovered rows before releasing the single restore gate", async () => {
const { client, registry, release } = owner()
const profileKey = communityKeys.communityDbCollection("viewer", "profiles")
- client.setQueryData(profileKey, [{ id: "viewer", identityComplete: false, name: "RSC", avatarVersion: 4 }])
+ client.setQueryData(profileKey, [profile("viewer", "RSC", 4)])
const disk = input({
- profiles: [{ id: "viewer", identityComplete: false, name: "Disk", avatarVersion: 1, aboutMe: "Uncovered" }, { id: "peer", identityComplete: false, name: "Peer" }],
+ profiles: [{ ...profile("viewer", "Disk", 1), aboutMe: "Uncovered" }, profile("peer", "Peer")],
messages: [message("old-other-scope", "other")],
})
await restoreCommunityCollections(registry, disk)
expect(client.getQueryData(profileKey)).toEqual([
- { id: "viewer", identityComplete: false, name: "RSC", avatarVersion: 4, aboutMe: "Uncovered" },
- { id: "peer", identityComplete: false, name: "Peer" },
+ { ...profile("viewer", "RSC", 4), aboutMe: "Uncovered" },
+ profile("peer", "Peer"),
])
expect(client.getQueryData(communityKeys.communityDbCollection("viewer", "messages"))).toEqual(disk.messages!.rows)
registry.captureRestoredCollections(disk)
@@ -68,7 +71,7 @@ describe("canonical disk input precedence", () => {
it("preserves a WS patch that arrived before its disk row and a current message over old disk", async () => {
const { client, registry } = owner()
- publishCommunityMessages(client, { channelId: "c1", messages: [message("current", "c1", "RSC")], proof: { token: captureCommunityLiveSnapshotToken(client) } })
+ publishCommunityMessages(client, { profiles: messageProfilesFixture([message("current", "c1", "RSC")]), channelId: "c1", messages: [message("current", "c1", "RSC")], proof: { token: captureCommunityLiveSnapshotToken(client) } })
projectCommunityWsEventToDb(client, { type: "community:reaction.add", serverId: "s1", channelId: "c1", messageId: "pending", emoji: "👍", userId: "peer" })
await restoreCommunityCollections(registry, input({ messages: [message("current"), message("pending"), message("uncovered", "other")] }))
const rows = client.getQueryData<Array<ReturnType<typeof message>>>(communityKeys.communityDbCollection("viewer", "messages"))!
@@ -82,7 +85,7 @@ describe("canonical disk input precedence", () => {
registry.runtime.ws.actions.revokeChannelAccess("s1", "revoked")
projectCommunityWsEventToDb(client, { type: "community:channel.delete", serverId: "s1", channelId: "deleted" })
const disk = input({
- channels: ["revoked", "deleted", "kept"].map((id) => canonicalChannelRow({ id, type: "text", serverId: "s1" })),
+ channels: ["revoked", "deleted", "kept"].map((id) => canonicalChannelRow(channelResourceFixture({ id, type: "text", serverId: "s1" }))),
messages: [message("revoked-message", "revoked"), message("deleted-message", "deleted"), message("kept-message", "kept")],
})
await restoreCommunityCollections(registry, disk)
@@ -93,16 +96,16 @@ describe("canonical disk input precedence", () => {
it("preserves authoritative empty scopes and still restores an unrelated server", async () => {
const { client, registry } = owner()
publishCommunityLiveSnapshot(client, {
- snapshot: { kind: "server-detail", data: { id: "s1", name: "Fresh", discriminator: "0001", description: "", icon: null, ownerId: "viewer", categories: [] } },
+ snapshot: { kind: "server-detail", data: serverDirectoryFixture({ id: "s1", name: "Fresh", discriminator: "0001", description: "", icon: null, ownerId: "viewer", categories: [] }) },
proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
publishCommunityLiveSnapshot(client, { snapshot: { kind: "folders", data: { folders: [] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
const disk = input({
servers: [server("s1"), server("s2")],
- categories: [{ id: "old-category", serverId: "s1", name: "Old", position: 0, private: false, pending: false }],
- channels: [canonicalChannelRow({ id: "omitted", type: "text", serverId: "s1" }), canonicalChannelRow({ id: "other", type: "text", serverId: "s2" })],
+ categories: [{ id: "old-category", serverId: "s1", name: "Old", position: 0, private: false, creatorId: null, pending: false }],
+ channels: [canonicalChannelRow(channelResourceFixture({ id: "omitted", type: "text", serverId: "s1" })), canonicalChannelRow(channelResourceFixture({ id: "other", type: "text", serverId: "s2" }))],
messages: [message("omitted-message", "omitted"), message("other-message", "other")],
- folders: [{ id: "old-folder", name: "Old", position: 0 }],
+ folders: [{ id: "old-folder", name: "Old" }],
folderItems: [{ id: "old-folder:s1", folderId: "old-folder", serverId: "s1", position: 0 }],
})
await restoreCommunityCollections(registry, disk)
@@ -115,7 +118,7 @@ describe("canonical disk input precedence", () => {
it("classifies only this restore input, including confirmed empty, regardless of current Query timestamps", () => {
const { client, registry } = owner()
- client.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [{ id: "viewer", identityComplete: false, name: "RSC" }])
+ client.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [profile("viewer", "RSC")])
registry.captureRestoredCollections(input({ messages: [] }))
expect(registry.hasRestoredCollection("profiles")).toBe(false)
expect(registry.hasRestoredCollection("messages")).toBe(true)
diff --git a/src/web/src/lib/community-db/schema.test.ts b/src/web/src/lib/community-db/schema.test.ts
index 43afe8766..be6ab7b2f 100644
--- a/src/web/src/lib/community-db/schema.test.ts
+++ b/src/web/src/lib/community-db/schema.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture, serverResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { describe, expect, it } from "vitest"
import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"
import { AttentionScopeSchema, AttentionItemSchema } from "@alook/shared"
@@ -99,46 +100,33 @@ describe("community DB schemas", () => {
)
})
- 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")
+ it("requires actual full server position without accepting a detail marker", () => {
+ const server = serverResourceFixture()
+ expect(serverSchema.parse(server)).toEqual(server)
+ const { position: _position, ...missing } = server
+ expect(serverSchema.safeParse(missing).success).toBe(false)
+ expect(serverSchema.safeParse({ ...server, detailComplete: true }).success).toBe(false)
})
})
-describe("canonical completeness", () => {
- const full = { id: "channel", type: "text" as const, serverId: "server", categoryId: null, name: "Channel", topic: "Preserve topic", parentChannelId: null, parentMessageId: null, creatorId: "author", position: 3, archived: false, createdAt: "created", lastMessageAt: null, messageCount: 0, resourceComplete: true as const }
- it("keeps full fields through sparse deltas and rejects an invalid full claim before merging", () => {
+describe("canonical full resource admission", () => {
+ it("keeps actual full fields through a valid current field patch", () => {
+ const full = channelResourceFixture({ topic: "Preserve topic" })
const loaded = canonicalChannelRow(full)
expect(canonicalChannelRow({ id: full.id, type: full.type, name: "Renamed", topic: undefined }, loaded)).toEqual({ ...loaded, name: "Renamed" })
- const stub = canonicalChannelRow({ id: "stub", type: "thread", name: "Preview" })
- expect(stub.resourceComplete).toBe(false)
- expect(stub).not.toHaveProperty("topic")
- expect(canonicalChannelRow({ ...full, id: "stub" }, stub).resourceComplete).toBe(true)
- const { topic: _topic, ...incomplete } = full
- expect(() => canonicalChannelRow(incomplete, loaded)).toThrow()
+ expect(() => canonicalChannelRow({ id: "stub", type: "thread", name: "Preview" })).toThrow()
expect(channelSchema.safeParse({ ...loaded, topic: undefined }).success).toBe(false)
})
- it("uses profile id without relationship aliases and distinguishes incomplete identity", () => {
- const profile = { id: "author", name: "Author", discriminator: "12345", avatar: null, avatarVersion: 0, identityComplete: true }
+ it("requires profile identity facts and accepts actual nullable fields without markers", () => {
+ const profile = { id: "author", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }
expect(profileSchema.parse(profile)).toEqual(profile)
- expect(profileSchema.parse({ id: "author", name: "Author", identityComplete: false })).toEqual({ id: "author", name: "Author", identityComplete: false })
expect(profileSchema.safeParse({ ...profile, discriminator: null }).success).toBe(false)
+ expect(profileSchema.safeParse({ id: "author", name: "Author" }).success).toBe(false)
+ expect(profileSchema.safeParse({ ...profile, identityComplete: true }).success).toBe(false)
expect(profileSchema.safeParse({ ...profile, avatarVersion: undefined }).success).toBe(false)
- const preview = { id: "message", channelId: "channel", type: "chat", resourceComplete: false }
- expect(messageSchema.parse(preview)).toEqual(preview)
- expect(messageSchema.safeParse({ ...preview, resourceComplete: true }).success).toBe(false)
+ expect(messageSchema.parse(messageResourceFixture())).toEqual(messageResourceFixture())
+ expect(messageSchema.safeParse({ id: "message", channelId: "channel", type: "chat" }).success).toBe(false)
+ expect(messageSchema.safeParse({ ...messageResourceFixture(), resourceComplete: true }).success).toBe(false)
})
})
diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.ts
index 7bef7f900..5b9531475 100644
--- a/src/web/src/lib/community-db/schema.ts
+++ b/src/web/src/lib/community-db/schema.ts
@@ -1,202 +1,17 @@
-import { z } from "zod"
-import { PARTICIPANT_SOURCE } from "@alook/shared/constants/community"
-import { serverRailEntrySchema, AttentionScopeSchema, AttentionItemSchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityMessagePreviewSchema, CommunityReadStateResourceSchema, CommunityMemberRelationSchema, CommunityResourceProfileSchema } from "@alook/shared"
-
-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(),
- 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 channelLocalSchema = z.object({
- muted: z.boolean(),
- tags: z.array(z.string()),
- pending: z.boolean(),
- openerSeq: z.number().int().nonnegative().optional(),
- openerUnread: z.boolean().optional(),
- preview: z.string().optional(),
- firstMessageId: z.string().min(1).nullable().optional(),
- participantCount: z.number().int().nonnegative().optional(),
-})
-
-export const channelSchema = z.discriminatedUnion("resourceComplete", [
- CommunityChannelResourceSchema.strip().extend({
- ...channelLocalSchema.shape,
- resourceComplete: z.literal(true),
- }),
- CommunityChannelResourceSchema.partial({
- serverId: true, categoryId: true, parentChannelId: true, parentMessageId: true,
- creatorId: true, lastMessageAt: true, createdAt: true, messageCount: true, topic: true,
- }).strip().extend({
- ...channelLocalSchema.shape,
- resourceComplete: z.literal(false).default(false),
- }),
-])
-
-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 = CommunityMemberRelationSchema.strip().partial({
- source: true, isCreator: true, role: true, memberId: true,
-}).extend({
- id: z.string().min(1),
- source: z.enum(["explicit", "inherited", "admin", PARTICIPANT_SOURCE.MENTION, PARTICIPANT_SOURCE.SPOKE, PARTICIPANT_SOURCE.ADDED]).optional(),
-})
-
-const incompleteProfileSchema = CommunityResourceProfileSchema.partial().required({ id: true }).strip().extend({
- identityComplete: z.literal(false),
-})
-
-export const profileSchema = z.discriminatedUnion("identityComplete", [
- CommunityResourceProfileSchema.strip().extend({
- discriminator: CommunityResourceProfileSchema.shape.discriminator.unwrap(),
- identityComplete: z.literal(true),
- }),
- incompleteProfileSchema,
-])
-
-export const messageSchema = z.discriminatedUnion("resourceComplete", [
- CommunityMessageResourceSchema.strip().extend({ resourceComplete: z.literal(true) }),
- CommunityMessagePreviewSchema.strip().required({ channelId: true }).extend({
- resourceComplete: z.literal(false).default(false),
- }),
-])
-
-export const readStateSchema = CommunityReadStateResourceSchema.strip().extend({ observedRevision: z.number().int().nonnegative().optional() })
-
-export const friendshipSchema = z.object({
- id: z.string().min(1),
- userId: z.string().min(1),
- kind: z.enum(["accepted", "incoming", "outgoing", "blocked"]),
- sub: z.string().optional(),
- needsOwnerApproval: optionalNullableString,
-})
-
-export const readStateClockSchema = z.object({
- id: z.literal("account"),
- revision: z.number().int().nonnegative(),
-})
-
-export const folderSchema = z.object({
- id: z.string().min(1),
- name: z.string(),
-})
-
-export const serverRailSchema = z.object({
- id: z.literal("account"),
- entries: z.array(serverRailEntrySchema),
-})
-
-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,
- friendships: friendshipSchema,
- readStates: readStateSchema,
- readStateClock: readStateClockSchema,
- attentionScopes: AttentionScopeSchema,
- attentionItems: AttentionItemSchema,
- serverRail: serverRailSchema,
- folders: folderSchema,
- folderItems: folderItemSchema,
- notificationSettings: notificationSettingSchema,
-} as const
-
-export type CommunityCollectionName = keyof typeof communityCollectionSchemas
-export type CommunityCollectionRows = { [N in CommunityCollectionName]: z.output<typeof communityCollectionSchemas[N]> }
-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 FriendshipRow = z.infer<typeof friendshipSchema>
-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>
+import { CommunityChannelResourceSchema, channelLocalSchema, channelSchema, type ChannelRow, type ChannelMembershipRow, type NotificationSettingRow } from "@alook/shared"
+export { serverSchema, categorySchema, channelLocalSchema, channelSchema, serverMembershipSchema, channelMembershipSchema, profileSchema, messageSchema, readStateSchema, friendshipSchema, readStateClockSchema, folderSchema, serverRailSchema, folderItemSchema, notificationSettingSchema, communityCollectionSchemas, type CommunityCollectionName, type CommunityCollectionRows, type ServerRow, type CategoryRow, type ChannelRow, type ServerMembershipRow, type ChannelMembershipRow, type ProfileRow, type MessageRow, type FriendshipRow, type ReadStateRow, type ReadStateClockRow, type AttentionScopeRow, type AttentionItemRow, type FolderRow, type FolderItemRow, type NotificationSettingRow } from "@alook/shared"
export function canonicalChannelRow(
input: Pick<ChannelRow, "id" | "type"> & Partial<Omit<ChannelRow, "id" | "type" | "name">> & { name?: string | null },
previous?: ChannelRow,
): ChannelRow {
- if (input.resourceComplete === true) CommunityChannelResourceSchema.strip().parse(input)
const fields = Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined))
- return channelSchema.parse({
- serverId: null,
- categoryId: null,
- parentChannelId: null,
- parentMessageId: null,
- creatorId: null,
- position: 0,
- archived: false,
- muted: false,
- tags: [],
- pending: false,
- lastMessageAt: null,
- ...previous,
- ...fields,
- name: input.name === undefined ? previous?.name ?? null : input.name,
- resourceComplete: input.resourceComplete === true || previous?.resourceComplete === true,
+ const resource = CommunityChannelResourceSchema.strip().parse({ ...previous, ...fields })
+ const local = channelLocalSchema.partial().strip().parse({ ...previous, ...fields })
+ return channelSchema.parse({ ...resource, ...local,
+ muted: input.muted ?? previous?.muted ?? false,
+ tags: input.tags ?? previous?.tags ?? [],
+ pending: input.pending ?? previous?.pending ?? false,
})
}
@@ -216,7 +31,7 @@ export function canonicalChannelMembershipRow(
channelId: string,
userId: string,
relation: ChannelMembershipRow["relation"],
- fields?: Omit<ChannelMembershipRow, "id" | "channelId" | "userId" | "relation">,
+ fields: Omit<ChannelMembershipRow, "id" | "channelId" | "userId" | "relation">,
): ChannelMembershipRow {
return { ...fields, id: channelMembershipKey(channelId, userId, relation), channelId, userId, relation }
}
diff --git a/src/web/src/lib/community-db/ssr.test.ts b/src/web/src/lib/community-db/ssr.test.ts
index 640b16a13..038cf25a1 100644
--- a/src/web/src/lib/community-db/ssr.test.ts
+++ b/src/web/src/lib/community-db/ssr.test.ts
@@ -19,7 +19,7 @@ describe("native DB server snapshot handoff", () => {
const errors = vi.spyOn(console, "error").mockImplementation(() => undefined)
const serverClient = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
const key = communityKeys.communityDbCollection("viewer", "profiles")
- const rows = [{ id: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 1, identityComplete: true }]
+ const rows = [{ id: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 1 }]
serverClient.setQueryData(key, rows)
const server = createCommunityDbRegistry(serverClient, "viewer")
await server.collections.profiles.preload()
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index d06f461c3..e59f7c15c 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -1,8 +1,14 @@
+import { profileResourceFixture } from "@/test/community-resource-fixtures"
+import { messageProfilesFixture } from "@/test/community-resource-fixtures"
+import { dmConversationEntryFixture, forumConversationEntryFixture, conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
+import { publishConversationEntry } from "@/lib/community/conversation-entry"
+import { dmListRowFixture, categoryResourceFixture, serverRailResponseFixture, serverResourceFixture, messageSeedFixture, channelResourceFixture, messageResourceFixture, fullResourceBundleFixture, resourceBundleFixture, serverDirectoryFixture } from "@/test/community-resource-fixtures"
import { seedCommunityAttentionScope } from "@/test/community-query-owner"
+import { normalizeThreadResources } from "@/hooks/community/forum-feed-window"
import { projectPostedMessage } from "@/lib/community/message-wire"
import { QueryClient } from "@tanstack/react-query"
import { afterEach, describe, expect, it, vi } from "vitest"
-import { AccountAttentionSnapshotSchema, CommunityMessageResourceSchema, communityMessagePreviewFromLegacy, type CommunityWsEvent } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, validateCommunityWsEvent, CommunityChannelResourceSchema, AccountAttentionSnapshotSchema, CommunityMessageResourceSchema, type CommunityWsEvent } from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
import { rememberMessageAccessScope } from "./message-access-scope"
import { getLastChannel, setLastChannel } from "@/lib/community/last-channel"
@@ -17,6 +23,8 @@ import {
type CommunityDbRegistry,
} from "./collections"
import {
+ publishCommunityResourceBundle,
+ publishCommunityForumFeed,
ingestDms,
ingestAttentionSnapshot,
ingestMessages,
@@ -75,7 +83,13 @@ async function registry(preload = true) {
function forumAttentionSnapshot(seq = 4) {
const at = "2026-10-08T00:00:00.000Z"
- return AccountAttentionSnapshotSchema.parse({
+ const server = serverResourceFixture({ id: "s1", name: "Server", discriminator: "0001" })
+ const channels = [channelResourceFixture({ id: "forum", serverId: "s1", type: "forum", name: "Forum", creatorId: "peer", lastMessageAt: at }),
+ channelResourceFixture({ id: "post", serverId: "s1", type: "thread", name: "Post", parentChannelId: "forum", parentMessageId: "opener", creatorId: "peer", lastMessageAt: at })]
+ const messages = [messageResourceFixture({ id: "opener", channelId: "forum", authorId: "peer", seq: 1, createdAt: at, content: "Title" }),
+ messageResourceFixture({ id: `m${seq}`, channelId: "post", authorId: "peer", seq, createdAt: at, content: "Reply" })]
+ const full = fullResourceBundleFixture("viewer", [server], channels, messages, [{ id: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0 }])
+ return AccountAttentionSnapshotSchema.parse({ resources: resourceBundleFixture({ ...full, memberships: full.memberships.filter(row => row.relation === "access") }),
scopes: [{ scopeId: "post", channelId: "post", serverId: "s1", parentChannelId: "forum", ordinaryUnread: true, lastUnreadSeq: seq, lastAttentionSeq: seq, attentionCount: 1 }],
items: [{ id: `reply:m${seq}`, kind: "reply", sourceId: `m${seq}`, scopeId: "post", messageId: `m${seq}`, actorUserId: "peer", createdAt: at }],
limit: 100, truncated: false,
@@ -141,7 +155,7 @@ describe("community DB sync", () => {
it("keeps a partial eligible count unknown until fresh authoritative readback, and restores it on rollback", async () => {
const db = await registry()
const scope = { scopeId: "dm", channelId: "dm", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 9, attentionCount: 0, lastAttentionSeq: null, unreadCount: 3 }
- const seed = (unreadCount: number) => ingestAttentionSnapshot(db, { scopes: [{ ...scope, unreadCount }], items: [], limit: 100, truncated: false })
+ const seed = (unreadCount: number) => ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }), scopes: [{ ...scope, unreadCount }], items: [], limit: 100, truncated: false })
seed(3)
const first = clearAttentionScopeOptimistically(db, "dm", 5)
expect(db.collections.attentionScopes.get("dm")?.unreadCount).toBeUndefined()
@@ -157,7 +171,7 @@ describe("community DB sync", () => {
it("keeps unloaded and partial member data unknown but prunes a fresh complete roster without requiring profiles", async () => {
const db = await registry()
publishCommunityChannelMetadata(db.queryClient, {
- metadata: { id: "c1", serverId: "s1", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null },
+ metadata: channelResourceFixture({ id: "c1", serverId: "s1", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
expect(getCanonicalCommunityTypingMembership(db.queryClient, "c1", "unknown")).toBeUndefined()
@@ -197,17 +211,17 @@ describe("community DB sync", () => {
it("prunes only the departed server's typing even with unloaded server members and restores qualification on join", async () => {
const db = await registry()
- ingestServerDetail(db, { id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
- categories: [{ id: "public-category", name: "Public", private: false, channels: [{ id: "c1", name: "Forum", type: "forum", active: false, unread: false }] }] })
+ ingestServerDetail(db, serverDirectoryFixture({ id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
+ categories: [{ id: "public-category", name: "Public", private: false, channels: [{ id: "c1", name: "Forum", type: "forum", active: false, unread: false }] }] }))
for (const [id, serverId, type] of [["c1", "s1", "forum"], ["c2", "s2", "text"], ["dm1", null, "dm"]] as const) {
publishCommunityChannelMetadata(db.queryClient, {
- metadata: { id, serverId, type, name: id, parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null },
+ metadata: channelResourceFixture({ id, serverId, type, name: id, parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
applyTypingIndicator(db.queryClient, `${type === "dm" ? "dm" : "ch"}:${id}`, "peer", null)
}
publishCommunityChannelMetadata(db.queryClient, {
- metadata: { id: "child", serverId: "s1", type: "thread", name: "Child", parentChannelId: "c1", parentMessageId: "opener", creatorId: "viewer", archived: false, lastMessageAt: null },
+ metadata: channelResourceFixture({ id: "child", serverId: "s1", type: "thread", name: "Child", parentChannelId: "c1", parentMessageId: "opener", creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
setCanonicalCommunityChannelMember(db.queryClient, "child", "peer", "notify", true, { event: true })
@@ -232,10 +246,10 @@ describe("community DB sync", () => {
it.each(["private", "unknown"])("does not grant %s channel typing from a server join against its access roster", async (visibility) => {
const db = await registry()
- if (visibility === "private") ingestServerDetail(db, { id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
- categories: [{ id: "private-category", name: "Private", private: true, channels: [{ id: "c1", name: "Channel", type: "text", active: false, unread: false }] }] })
+ if (visibility === "private") ingestServerDetail(db, serverDirectoryFixture({ id: "s1", name: "Server", discriminator: "0001", description: "", icon: null, ownerId: "viewer",
+ categories: [{ id: "private-category", name: "Private", private: true, channels: [{ id: "c1", name: "Channel", type: "text", active: false, unread: false }] }] }))
else publishCommunityChannelMetadata(db.queryClient, {
- metadata: { id: "c1", serverId: "s1", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null },
+ metadata: channelResourceFixture({ id: "c1", serverId: "s1", categoryId: "unloaded-category", type: "text", name: "Channel", parentChannelId: null, parentMessageId: null, creatorId: "viewer", archived: false, lastMessageAt: null }),
proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) },
})
db.queryClient.setQueryData(communityKeys.channelMembers("c1", "access"), { serverId: "s1", relation: "access", members: [] })
@@ -248,12 +262,12 @@ describe("community DB sync", () => {
it.each(["newer-ws", "original"])("preserves the named WS write %s while confirming independent server fields and rejecting the older whole snapshot", async (name) => {
const db = await registry()
const original = { id: "s1", name: "original", description: "before", initial: "O", active: false, unread: false, mentions: 0, ownerId: "viewer" }
- ingestServers(db, { servers: [original] })
+ ingestServers(db, serverRailResponseFixture({ servers: [original] }, db.accountId))
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, { type: "community:server.update", serverId: "s1", changes: { name } })
publishCommunityServerFields(db.queryClient, "s1", { name: "old-confirmation", description: "confirmed" }, { token, signal: undefined })
expect(db.collections.servers.get("s1")).toMatchObject({ name, description: "confirmed" })
- publishCommunityLiveSnapshotWithProof(db.queryClient, { snapshot: { kind: "servers", data: { servers: [original] } }, proof: { kind: "structural", token, signal: undefined } })
+ publishCommunityLiveSnapshotWithProof(db.queryClient, { snapshot: { kind: "servers", data: serverRailResponseFixture({ servers: [original] }, "viewer") }, proof: { kind: "structural", token, signal: undefined } })
expect(db.collections.servers.get("s1")).toMatchObject({ name, description: "confirmed" })
})
@@ -261,20 +275,20 @@ describe("community DB sync", () => {
const db = await registry()
const replyTo = { id: "reply", authorId: "peer", authorName: "Peer", text: "confirmed" }
const row = { id: "posted", channelId: "c1", type: "chat" as const, authorId: "viewer", clientNonce: "nonce", seq: 1, replyTo, replyToId: replyTo.id }
- ingestMessages(db, "c1", [row])
- ingestMessages(db, "c1", [{ ...row, replyTo: undefined }])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [row]))
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...row, replyTo: undefined }]))
expect(db.collections.messages.get(row.id)?.replyTo).toBeUndefined()
- ingestMessages(db, "c1", [row])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [row]))
const { replyTo: _reply, ...incomplete } = row
- ingestMessages(db, "c1", [incomplete])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [incomplete]))
expect(db.collections.messages.get(row.id)?.replyTo).toEqual(replyTo)
- const posted = projectPostedMessage({ id: row.id, seq: row.seq, authorId: row.authorId, authorName: "Viewer",
- authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-08T00:00:00Z", content: "posted", type: "default", embeds: null }, row.clientNonce, "c1")
- ingestMessages(db, "c1", [posted])
+ const posted = projectPostedMessage(messageResourceFixture({ id: row.id, channelId: "c1", seq: row.seq, authorId: row.authorId, authorName: "Viewer",
+ authorAvatar: null, authorAvatarVersion: 0, createdAt: "2026-10-08T00:00:00Z", content: "posted", clientNonce: row.clientNonce, replyToId: row.replyToId, embeds: [] }), row.clientNonce, "c1")
+ ingestMessages(db, "c1", messageSeedFixture("c1", [posted]))
expect(db.collections.messages.get(row.id)?.replyTo).toEqual(replyTo)
- ingestMessages(db, "c1", [{ ...row, replyTo: { id: replyTo.id, authorName: "Deleted user", text: "", deleted: true } }])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...row, replyTo: { id: replyTo.id, authorName: "Deleted user", text: "", deleted: true } }]))
expect(db.collections.messages.get(row.id)?.replyTo).toMatchObject({ deleted: true, text: "" })
- ingestMessages(db, "c1", [{ ...incomplete, replyToId: null }])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...incomplete, replyToId: null }]))
expect(db.collections.messages.get(row.id)?.replyTo).toBeUndefined()
expect(db.collections.messages.get(row.id)?.replyToId).toBeNull()
})
@@ -282,134 +296,127 @@ describe("community DB sync", () => {
it.each(["author", "nonce", "channel"])("does not retain a confirmed quote for a different %s owner", async (field) => {
const db = await registry()
const identity = { id: "owned-reply", channelId: "c1", type: "chat" as const, authorId: "viewer", clientNonce: "nonce", seq: 1 }
- ingestMessages(db, "c1", [{ ...identity, replyTo: { id: "target", authorName: "Peer", text: "private" }, replyToId: "target" }])
- ingestMessages(db, field === "channel" ? "c2" : "c1", [{ ...identity,
- ...(field === "author" ? { authorId: "other" } : field === "nonce" ? { clientNonce: "other" } : { channelId: "c2" }) }])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...identity, replyTo: { id: "target", authorId: "peer", authorName: "Peer", text: "private" }, replyToId: "target" }]))
+ ingestMessages(db, field === "channel" ? "c2" : "c1", messageSeedFixture(field === "channel" ? "c2" : "c1", [{ ...identity,
+ ...(field === "author" ? { authorId: "other" } : field === "nonce" ? { clientNonce: "other" } : { channelId: "c2" }) }]))
expect(db.collections.messages.get(identity.id)?.replyTo).toBeUndefined()
expect(db.collections.messages.get(identity.id)?.replyToId).toBeNull()
})
- it("keeps full raw facts across a weak preview and explicit full clearing", async () => {
- const db = await registry()
- const full = CommunityMessageResourceSchema.parse({ id: "raw", channelId: "c1", seq: 1, type: "chat", authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 4, content: "full", createdAt: "now", replyToId: "reply", replyTo: { id: "reply", authorName: "Peer", text: "prior" }, clientNonce: "nonce", attachments: [{ id: "a2", name: "raw", url: "/raw", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }], embeds: [null, { unsupported: true }], thread: { id: "thread", name: null, messageCount: 0, lastReplyAt: null, participants: [{ id: "peer", name: "Peer", avatar: null, avatarVersion: 4 }] } })
- ingestMessages(db, "c1", [{ ...full, resourceComplete: true }])
- const preview = communityMessagePreviewFromLegacy({ id: "raw", seq: 1, type: "chat", authorId: "peer", createdAt: "now", content: "preview" }, "c1")
- ingestMessages(db, "c1", [preview])
- expect(db.collections.messages.get(full.id)).toMatchObject({ ...full, content: "preview", resourceComplete: true })
- ingestMessages(db, "c1", [{ id: "raw", thread: { id: "thread", participants: [{ id: "peer", avatarVersion: 4 }, { id: "unknown" }] } }])
- expect(db.collections.messages.get(full.id)?.thread?.participants).toEqual(full.thread!.participants)
- expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer", avatar: null, avatarVersion: 4 })
- expect(db.collections.profiles.get("unknown")).toMatchObject({ id: "unknown", identityComplete: false })
- expect(db.collections.profiles.get("unknown")).not.toHaveProperty("name")
- ingestMessages(db, "c1", [{ ...full, resourceComplete: true, attachments: [], embeds: [], clientNonce: null, replyToId: null, replyTo: undefined }])
- expect(db.collections.messages.get(full.id)).toMatchObject({ resourceComplete: true, attachments: [], embeds: [], clientNonce: null, replyToId: null })
+ it("rejects a weak preview instead of mutating full canonical message facts", async () => {
+ const db = await registry()
+ const full = CommunityMessageResourceSchema.parse({ id: "raw", channelId: "c1", seq: 1, type: "chat", authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 4, content: "full", createdAt: "now", replyToId: "reply", replyTo: { id: "reply", authorId: "peer", authorName: "Peer", text: "prior" }, clientNonce: "nonce", attachments: [{ id: "a2", name: "raw", url: "/raw", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }], embeds: [null, { unsupported: true }], thread: { id: "thread", name: null, messageCount: 0, lastReplyAt: null, participants: [{ id: "peer", name: "Peer", avatar: null, avatarVersion: 4 }] } })
+ ingestMessages(db, "c1", messageSeedFixture("c1", [full]))
+ const preview = { id: "raw", seq: 1, type: "chat", authorId: "peer", createdAt: "now", content: "preview" }
+ expect(() => ingestMessages(db, "c1", [preview])).toThrow()
+ expect(db.collections.messages.get(full.id)).toMatchObject(full)
+ expect(() => ingestMessages(db, "c1", [{ id: "raw", thread: { id: "thread", participants: [{ id: "unknown" }] } }])).toThrow()
+ expect(db.collections.profiles.get("unknown")).toBeUndefined()
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{ ...full, attachments: [], embeds: [], clientNonce: null, replyToId: null, replyTo: undefined }]))
+ expect(db.collections.messages.get(full.id)).toMatchObject({ attachments: [], embeds: [], clientNonce: null, replyToId: null })
expect(db.collections.messages.get(full.id)?.replyTo).toBeUndefined()
})
- it.each([
- ["legacy", "empty"], ["legacy", "incomplete"],
- ["confirmed2", "empty"], ["confirmed2", "incomplete"],
- ] as const)("preserves full attachments through %s %s read publication", async (contract, shape) => {
- const db = await registry()
- const full = CommunityMessageResourceSchema.parse({
- id: "attachment-read", channelId: "c1", seq: 1, type: "chat", authorId: "peer",
- createdAt: "now", content: "full", replyToId: null, clientNonce: null,
- attachments: [
- { id: "a2", name: "unknown", url: "/a2", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
- { id: "a1", name: "photo", url: "/a1", thumbnailUrl: "/thumb", contentType: "image/png", sizeBytes: 12, width: 2, height: 3 },
- ],
- })
- const legacy = { ...full, content: "read preview", attachments: shape === "empty" ? [] : [{ kind: "file", name: "old", url: "/old" }] }
- const body = contract === "legacy" ? { messages: [legacy] } : {
- contractVersion: 2, channelId: "c1", messages: [legacy],
- page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 1 },
- surfaceReceipt: { channelId: "c1", surfaceKind: "channel" },
+ it.each([["legacy", "empty"], ["legacy", "incomplete"], ["confirmed2", "empty"], ["confirmed2", "incomplete"]] as const)("rejects obsolete %s %s read input and handles current attachment truth", async (contract, shape) => {
+ const db = await registry()
+ const full = messageResourceFixture({ id: "attachment-read", channelId: "c1", authorId: "peer", content: "full",
+ attachments: [{ id: "a1", name: "photo", url: "/a1", thumbnailUrl: "/thumb", contentType: "image/png", sizeBytes: 12, width: 2, height: 3 }] })
+ ingestMessages(db, "c1", [full])
+ const candidate = { ...full, content: "read preview", attachments: shape === "empty" ? [] : [{ kind: "file", name: "old", url: "/old" }] }
+ const page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 1 }
+ const body = contract === "legacy" ? { messages: [candidate] } : { contractVersion: 2, channelId: "c1", messages: [candidate], page, surfaceReceipt: { channelId: "c1", surfaceKind: "channel" } }
+ const obsoleteResponse = new Response(null, { headers: contract === "legacy" ? {} : { "X-Alook-Community-Contract": "2" } })
+ expect(() => decodeCommunityReadResponse("/api/community/channels/c1/messages", "GET", obsoleteResponse, body, 2)).toThrow()
+ expect(db.collections.messages.get(full.id)?.attachments).toEqual(full.attachments)
+ const currentResponse = new Response(null, { headers: { "X-Alook-Community-Contract": String(BUSINESS_SCHEMA_VERSION) } })
+ const currentBody = { profiles: messageProfilesFixture([full]), contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", messages: [candidate], page, surfaceReceipt: { channelId: "c1", surfaceKind: "channel" } }
+ if (shape === "incomplete") {
+ expect(() => decodeCommunityReadResponse("/api/community/channels/c1/messages", "GET", currentResponse, currentBody)).toThrow()
+ expect(db.collections.messages.get(full.id)?.attachments).toEqual(full.attachments)
+ } else {
+ const decoded = decodeCommunityReadResponse("/api/community/channels/c1/messages", "GET", currentResponse, currentBody) as { messages: unknown[] }
+ ingestMessages(db, "c1", decoded.messages)
+ expect(db.collections.messages.get(full.id)?.attachments).toEqual([])
}
- const response = new Response(null, { headers: contract === "legacy" ? {} : { "X-Alook-Community-Contract": "2" } })
- const read = decodeCommunityReadResponse("/api/community/channels/c1/messages", "GET", response, body, 2) as { messages: MessageInput[] }
- expect(read.messages[0]).toMatchObject({ resourceComplete: false, attachments: shape === "empty" ? [] : [{ name: "old", url: "/old" }] })
- ingestMessages(db, "c1", [{ ...read.messages[0]!, id: "weak-only" }])
- expect(db.collections.messages.get("weak-only")).toMatchObject({ resourceComplete: false, attachments: read.messages[0]!.attachments })
- ingestMessages(db, "c1", [{ ...full, resourceComplete: true }])
- expect(() => ingestMessages(db, "c1", read.messages)).not.toThrow()
- expect(db.collections.messages.get(full.id)).toMatchObject({ content: "read preview", resourceComplete: true, attachments: full.attachments })
- ingestMessages(db, "c1", [{ ...full, resourceComplete: true, attachments: [...full.attachments].reverse() }])
- expect(db.collections.messages.get(full.id)?.attachments).toEqual([...full.attachments].reverse())
- ingestMessages(db, "c1", [{ ...full, resourceComplete: true, attachments: [] }])
- expect(db.collections.messages.get(full.id)?.attachments).toEqual([])
+ expect(() => ingestMessages(db, "c1", [{ ...full, resourceComplete: true }])).toThrow()
+ expect(db.collections.messages.get(full.id)).not.toHaveProperty("resourceComplete")
})
it.each([false, true])("does not canonicalize an Attention initial for a known full profile=%s", async known => {
const db = await registry()
if (known) {
- writeCommunityCollectionRows(db, "profiles", [{
+ await writeCommunityCollectionRows(db, "profiles", [{
id: "peer", name: "Peer", discriminator: "0002", aboutMe: "actual bio",
avatar: null, avatarVersion: 4, statusEmoji: "🌿", statusText: "Actual status",
- ownerHandle: "owner#12345", mutualServers: 2, ownedByViewer: false, identityComplete: true,
+ ownerHandle: "owner#12345", mutualServers: 2, ownedByViewer: false,
}], row => row.id)
- expect(db.collections.profiles.get("peer")).toMatchObject({ identityComplete: true, avatar: null, avatarVersion: 4 })
+ expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: null, avatarVersion: 4 })
}
const snapshot = forumAttentionSnapshot()
snapshot.included.profiles[0]!.avatarVersion = 4
+ snapshot.resources.profiles[0]!.avatarVersion = 4
+ snapshot.resources.profiles[0]!.avatar = null
ingestAttentionSnapshot(db, snapshot)
const profile = db.collections.profiles.get("peer")
- expect(profile).toMatchObject({ id: "peer", name: "Peer", discriminator: "0002", avatarVersion: 4, identityComplete: known })
+ expect(profile).toMatchObject({ id: "peer", name: "Peer", discriminator: "0002", avatarVersion: 4 })
if (known) expect(profile).toMatchObject({ avatar: null, aboutMe: "actual bio", statusEmoji: "🌿", statusText: "Actual status", ownerHandle: "owner#12345", mutualServers: 2, ownedByViewer: false })
- else expect(profile).not.toHaveProperty("avatar")
+ else expect(profile).toMatchObject({ avatar: null })
+ expect(profile).not.toHaveProperty("identityComplete")
snapshot.included.profiles[0]!.avatar = "https://cdn.example/peer.png"
snapshot.included.profiles[0]!.avatarVersion = 5
+ snapshot.resources.profiles[0]!.avatar = "https://cdn.example/peer.png"
+ snapshot.resources.profiles[0]!.avatarVersion = 5
ingestAttentionSnapshot(db, snapshot)
- expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: "https://cdn.example/peer.png", avatarVersion: 5, identityComplete: true })
+ expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: "https://cdn.example/peer.png", avatarVersion: 5 })
snapshot.included.profiles[0]!.avatar = "P"
snapshot.included.profiles[0]!.avatarVersion = 4
+ snapshot.resources.profiles[0]!.avatar = null
+ snapshot.resources.profiles[0]!.avatarVersion = 4
ingestAttentionSnapshot(db, snapshot)
- expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: "https://cdn.example/peer.png", avatarVersion: 5, identityComplete: true })
+ expect(db.collections.profiles.get("peer")).toMatchObject({ avatar: "https://cdn.example/peer.png", avatarVersion: 5 })
})
it("rejects invalid full batches before writing child rows", async () => {
const db = await registry()
- const good = { id: "good", channelId: "c1", seq: 1, type: "chat" as const, authorId: "peer", createdAt: "now", content: "body", clientNonce: null, replyToId: null, attachments: [], resourceComplete: true, thread: { id: "child", name: "Child", messageCount: 0 } }
+ const good = { id: "good", channelId: "c1", seq: 1, type: "chat" as const, authorId: "peer", createdAt: "now", content: "body", clientNonce: null, replyToId: null, attachments: [], thread: { id: "child", name: "Child", messageCount: 0 } }
expect(() => ingestMessages(db, "c1", [good, { ...good, id: "bad", attachments: undefined }])).toThrow()
expect(db.collections.messages.size).toBe(0)
expect(db.collections.channels.get("child")).toBeUndefined()
})
- it("keeps full topic and times through a later weak sidebar read", async () => {
+ it("keeps full facts through a named patch and rejects weak directory resources", async () => {
const db = await registry()
- const full = { id: "c1", type: "text" as const, serverId: "s1", categoryId: "cat1", name: "Channel", topic: "Full topic", parentChannelId: null, parentMessageId: null, creatorId: "peer", position: 2, archived: false, createdAt: "created", lastMessageAt: "last", messageCount: 7, resourceComplete: true }
- publishCommunityChannelMetadata(db.queryClient, { metadata: full, proof: { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined } })
- const detail = { id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat1", name: "Category", channels: [{ id: "c1", name: "Renamed", active: false, unread: false, archived: 0 }] }] }
+ const full = channelResourceFixture({ id: "c1", serverId: "s1", categoryId: "cat1", name: "Channel", topic: "Full topic", position: 2, createdAt: "created", lastMessageAt: "last", messageCount: 7 })
+ const detail = { server: serverResourceFixture({ id: "s1" }), categories: [categoryResourceFixture({ id: "cat1", serverId: "s1" })], channels: [full] }
ingestServerDetail(db, detail)
- expect(db.collections.channels.get(full.id)).toMatchObject({ topic: "Full topic", createdAt: "created", lastMessageAt: "last", messageCount: 7, archived: false, resourceComplete: true, name: "Renamed" })
- ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [{ ...detail.categories[0].channels[0], archived: 1 }] }] })
- expect(db.collections.channels.get(full.id)).toMatchObject({ archived: true, resourceComplete: true, topic: "Full topic", lastMessageAt: "last", messageCount: 7 })
- const { archived: _archived, ...omitted } = detail.categories[0].channels[0]
- ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [omitted] }] })
- expect(db.collections.channels.get(full.id)).toMatchObject({ archived: true, resourceComplete: true, topic: "Full topic", createdAt: "created", lastMessageAt: "last", messageCount: 7 })
+ publishCommunityChannelFields(db.queryClient, full.id, { name: "Renamed" }, { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ expect(db.collections.channels.get(full.id)).toMatchObject({ name: "Renamed", topic: "Full topic", createdAt: "created", lastMessageAt: "last", messageCount: 7 })
const before = db.collections.channels.get(full.id)
- expect(() => ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [{ ...detail.categories[0].channels[0], archived: false, resourceComplete: true }] }] })).toThrow()
- expect(() => ingestServerDetail(db, { ...detail, categories: [{ ...detail.categories[0], channels: [{ ...full, active: false, unread: false, archived: 0 }] }] })).toThrow()
+ expect(() => ingestServerDetail(db, { ...detail, channels: [{ id: full.id, name: "Weak" }] } as never)).toThrow()
+ expect(() => ingestServerDetail(db, { ...detail, channels: [{ ...full, resourceComplete: true }] } as never)).toThrow()
expect(db.collections.channels.get(full.id)).toEqual(before)
+ ingestServerDetail(db, { ...detail, channels: [{ ...full, name: "Renamed", archived: true }] })
+ expect(db.collections.channels.get(full.id)).toMatchObject({ archived: true, topic: "Full topic", createdAt: "created", lastMessageAt: "last", messageCount: 7 })
+ expect(db.collections.channels.get(full.id)).not.toHaveProperty("resourceComplete")
})
- it.each([{ archived: 2 }, { archived: "0" }, { archived: null }, { topic: null }, { messageCount: -1 }, { serverId: "foreign" }])("rejects an invalid later sidebar row before publication %j", async (fields) => {
+ it.each([{ archived: 2 }, { archived: "0" }, { archived: null }, { topic: null }, { messageCount: -1 }, { serverId: "foreign" }])("rejects an invalid later current directory row before any publication %j", async fields => {
const db = await registry()
- const original = { id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat1", name: "Category", channels: [{ id: "old", name: "Old", active: false, unread: false }] }] }
+ const original = { server: serverResourceFixture({ id: "s1" }), categories: [categoryResourceFixture({ id: "cat1", serverId: "s1" })],
+ channels: [channelResourceFixture({ id: "old", serverId: "s1", categoryId: "cat1", name: "Old" })] }
ingestServerDetail(db, original)
- const previousServer = db.collections.servers.get("s1")
- const previousChannel = db.collections.channels.get("old")
- const valid = { id: "new", name: "New", active: false, unread: false, archived: 0 }
- const invalid = { ...valid, id: "bad", ...fields }
- expect(() => ingestServerDetail(db, { ...original, name: "Changed", categories: [{ ...original.categories[0], channels: [valid, invalid] }] })).toThrow()
- expect(db.collections.servers.get("s1")).toEqual(previousServer)
- expect(db.collections.channels.get("old")).toEqual(previousChannel)
+ const beforeServer = db.collections.servers.get("s1"), beforeChannel = db.collections.channels.get("old")
+ const valid = channelResourceFixture({ id: "new", serverId: "s1", categoryId: "cat1", name: "New" })
+ expect(() => ingestServerDetail(db, { ...original, server: { ...original.server, name: "Changed" }, channels: [valid, { ...valid, id: "bad", ...fields }] } as never)).toThrow()
+ expect(db.collections.servers.get("s1")).toEqual(beforeServer)
+ expect(db.collections.channels.get("old")).toEqual(beforeChannel)
expect(db.collections.channels.has("new")).toBe(false)
expect(db.collections.channels.has("bad")).toBe(false)
})
it("cannot resurrect a deleted channel through a confirmed field patch or the older snapshot", async () => {
const db = await registry()
- const original = { id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat1", name: "General", channels: [{ id: "c1", name: "old", active: false, unread: false }] }] }
+ const original = serverDirectoryFixture({ id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, categories: [{ id: "cat1", name: "General", channels: [{ id: "c1", name: "old", active: false, unread: false }] }] })
ingestServerDetail(db, original)
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, { type: "community:channel.delete", serverId: "s1", channelId: "c1" })
@@ -422,20 +429,21 @@ 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: [{
+ ingestServers(db, serverRailResponseFixture({ servers: [{
id: "s1", name: "Server", initial: "S", active: false, unread: false,
mentions: 0, ownerId: "viewer",
- }] })
- ingestServerDetail(db, {
+ }] }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture({
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, {
+ resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "forum1", serverId: "s1", categoryId: "cat1", type: "forum", name: "Forum renamed" })]),
directory: [{
id: "s1",
name: "Server",
@@ -453,10 +461,11 @@ describe("community DB sync", () => {
})
})
- it("ingests an unknown legacy directory channel as text", async () => {
+ it("uses explicit full resource type for a new directory channel", async () => {
const db = await registry()
expect(publishCommunityChannelDirectory(db.queryClient, {
+ resources: fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "c1", serverId: "s1", type: "text", name: "General" })]),
directory: [{
id: "s1",
name: "Server",
@@ -474,30 +483,22 @@ describe("community DB sync", () => {
})
})
- it.each(["directory", "attention"] as const)("preserves rich server rows and existing viewer roles when seeding $0 summaries", async (source) => {
+ it.each(["directory", "attention"] as const)("keeps explicit rich server facts and viewer roles in current $0 resources", async source => {
const db = await registry()
- ingestServers(db, { servers: [{ id: "s1", name: "Server", discriminator: "0001",
- initial: "S", active: false, unread: true, mentions: 3, ownerId: "viewer",
- isOwner: true, role: "admin", memberId: "member-1" }] })
- ingestServerDetail(db, { id: "s1", name: "Server", discriminator: "0001",
- description: "rich description", icon: "server.png", ownerId: "viewer", official: true, categories: [] })
- const original = db.collections.servers.get("s1")!
- const membership = [...db.collections.serverMemberships.values()].find((row) => row.serverId === "s1")!
- const summaries = [{ id: "s1", name: "Updated", discriminator: "0002" },
- { id: "s2", name: "New", discriminator: "0003" }]
- if (source === "directory") publishCommunityChannelDirectory(db.queryClient, {
- directory: summaries.map((server) => ({ ...server, channels: [] })),
- proof: { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined },
- })
- else ingestAttentionSnapshot(db, { scopes: [], items: [], limit: 100, truncated: false,
- included: { servers: summaries } })
- expect(db.collections.servers.get("s1")).toStrictEqual({ ...original, name: "Updated", discriminator: "0002" })
- expect(db.collections.serverMemberships.get(membership.id)).toStrictEqual(membership)
- expect(db.collections.servers.get("s2")).toMatchObject({ id: "s2", position: 1,
- name: "New", discriminator: "0003", description: "", ownerId: "", icon: null,
- official: false, isOwner: false, detailComplete: false })
- expect([...db.collections.serverMemberships.values()].find((row) => row.serverId === "s2"))
- .toMatchObject({ serverId: "s2", userId: "viewer", role: "member", viewer: true })
+ const old = serverResourceFixture({ id: "s1", name: "Server", discriminator: "0001", description: "rich description", icon: "server.png", official: true })
+ ingestServers(db, serverRailResponseFixture({ servers: [{ ...old, role: "admin", memberId: "member-1" }] }, "viewer"))
+ const current = { ...old, name: "Updated", discriminator: "0002" }
+ const added = serverResourceFixture({ id: "s2", position: 1, name: "New", discriminator: "0003", ownerId: "peer", isOwner: false })
+ const resources = resourceBundleFixture({ viewerId: "viewer", servers: [current, added], serverMemberships: [
+ { serverId: "s1", userId: "viewer", memberId: "member-1", role: "admin" }, { serverId: "s2", userId: "viewer", memberId: "member-2", role: "member" }] })
+ const summaries = resources.servers.map(({ id, name, discriminator }) => ({ id, name, discriminator }))
+ if (source === "directory") publishCommunityChannelDirectory(db.queryClient, { resources, directory: summaries.map(server => ({ ...server, channels: [] })), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
+ else ingestAttentionSnapshot(db, AccountAttentionSnapshotSchema.parse({ resources, scopes: [], items: [], limit: 100, truncated: false, included: { servers: summaries, channels: [], dms: [], profiles: [], messages: [] } }))
+ expect(db.collections.servers.get("s1")).toMatchObject(current)
+ expect(db.collections.servers.get("s2")).toMatchObject(added)
+ expect(db.collections.serverMemberships.get("s1:viewer")).toMatchObject({ role: "admin", memberId: "member-1", viewer: true })
+ expect(db.collections.serverMemberships.get("s2:viewer")).toMatchObject({ role: "member", memberId: "member-2", viewer: true })
+ expect(db.collections.servers.get("s2")).not.toHaveProperty("detailComplete")
})
it("keeps anonymous canonical ingestion free of viewer access rows", async () => {
@@ -505,18 +506,18 @@ describe("community DB sync", () => {
registries.push(db)
await db.preload()
- ingestServers(db, { servers: [{
+ ingestServers(db, serverRailResponseFixture({ servers: [{
id: "s1", name: "Server", initial: "S", active: false, unread: false,
mentions: 0, ownerId: "owner",
- }] })
- ingestServerDetail(db, {
+ }] }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture({
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([])
@@ -528,7 +529,7 @@ describe("community DB sync", () => {
const db = await registry()
db.runtime.ws.actions.activateProfileAccount(`viewer-${race}`)
ingestDms(db, {
- conversations: [{
+ conversations: ([{
id: "dm-current",
userId: "peer",
name: "Peer",
@@ -536,7 +537,7 @@ describe("community DB sync", () => {
avatar: "P",
status: "offline",
preview: "",
- }],
+ }]).map(row => dmListRowFixture(row, db.accountId!)),
})
const token = captureCommunityLiveSnapshotToken(db.queryClient)
const controller = new AbortController()
@@ -569,9 +570,13 @@ describe("community DB sync", () => {
unread: false,
}
+ expect(publishCommunityDmSummary(db.queryClient, dm)).toBe("missing-resource")
+ expect(db.collections.channels.has(dm.id)).toBe(false)
+ const channel = channelResourceFixture({ id: dm.id, type: "dm", serverId: null, name: null })
+ publishConversationEntry(db.queryClient, { channelId: dm.id, serverId: null }, conversationEntryFromChannel(channel), { token: captureCommunityLiveSnapshotToken(db.queryClient, dm.id) })
expect(publishCommunityDmSummary(db.queryClient, dm)).toBe("published")
publishCommunityLiveSnapshotWithProof(db.queryClient, {
- snapshot: { kind: "dms", data: { conversations: [] } },
+ snapshot: { kind: "dms", data: { conversations: ([]).map(row => dmListRowFixture(row, "viewer")) } },
proof: { kind: "structural", token, signal: undefined },
})
@@ -590,7 +595,7 @@ describe("community DB sync", () => {
content: "stale HTTP",
createdAt: "2026-09-26T00:00:00.000Z",
}
- ingestMessages(db, "c1", [staleMessage])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [staleMessage]))
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, {
@@ -599,9 +604,9 @@ describe("community DB sync", () => {
messageId: "m1",
emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
- publishCommunityMessages(db.queryClient, {
+ publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [staleMessage])),
channelId: "c1",
- messages: [staleMessage],
+ messages: messageSeedFixture("c1", [staleMessage]),
proof: { token, signal: undefined },
})
@@ -618,16 +623,16 @@ describe("community DB sync", () => {
createdAt: "2026-09-26T00:00:00.000Z",
reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
}
- ingestMessages(db, "c1", [staleMessage])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [staleMessage]))
const token = captureCommunityLiveSnapshotToken(db.queryClient)
patchCanonicalCommunityMessage(db.queryClient, "m-local", (message) => ({
...message,
reactions: [{ emoji: "👍", count: 2, me: true, userIds: ["peer", "viewer"] }],
}))
- publishCommunityMessages(db.queryClient, {
+ publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [staleMessage])),
channelId: "c1",
- messages: [staleMessage],
+ messages: messageSeedFixture("c1", [staleMessage]),
proof: { token, signal: undefined },
})
@@ -646,15 +651,21 @@ describe("community DB sync", () => {
messageId: "m1",
emoji: "👍", userId: "viewer",
} as CommunityWsEvent)
- publishCommunityMessages(db.queryClient, {
+ publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ content: "stale HTTP",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }])),
channelId: "c1",
- messages: [{
+ messages: messageSeedFixture("c1", [{
id: "m1",
type: "chat",
seq: 1,
content: "stale HTTP",
createdAt: "2026-09-26T00:00:00.000Z",
- }],
+ }]),
proof: { token, signal: undefined },
})
@@ -665,15 +676,21 @@ describe("community DB sync", () => {
communityKeys.communityDbCollection("viewer", "messages"),
[],
)
- publishCommunityMessages(db.queryClient, {
+ publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ content: "stale HTTP replay",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }])),
channelId: "c1",
- messages: [{
+ messages: messageSeedFixture("c1", [{
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()
@@ -681,13 +698,13 @@ describe("community DB sync", () => {
it("does not retain pending closures for WS patches that hit an existing row", async () => {
const db = await registry()
- ingestMessages(db, "c1", [{
+ ingestMessages(db, "c1", messageSeedFixture("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, {
@@ -703,15 +720,21 @@ describe("community DB sync", () => {
communityKeys.communityDbCollection("viewer", "messages"),
[],
)
- publishCommunityMessages(db.queryClient, {
+ publishCommunityMessages(db.queryClient, { profiles: messageProfilesFixture(messageSeedFixture("c1", [{
+ id: "m1",
+ type: "chat",
+ seq: 1,
+ content: "stale HTTP",
+ createdAt: "2026-09-26T00:00:00.000Z",
+ }])),
channelId: "c1",
- messages: [{
+ messages: messageSeedFixture("c1", [{
id: "m1",
type: "chat",
seq: 1,
content: "stale HTTP",
createdAt: "2026-09-26T00:00:00.000Z",
- }],
+ }]),
proof: { token, signal: undefined },
})
@@ -745,11 +768,11 @@ describe("community DB sync", () => {
}],
}],
}
- ingestServers(db, { servers: [{
+ ingestServers(db, serverRailResponseFixture({ servers: [{
id: "s1", name: "Stale server", initial: "S", active: false,
unread: false, mentions: 0, ownerId: "viewer",
- }] })
- ingestServerDetail(db, detail)
+ }] }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture(detail))
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, {
@@ -764,7 +787,7 @@ describe("community DB sync", () => {
changes: { name: "fresh channel" },
} as CommunityWsEvent)
publishCommunityLiveSnapshotWithProof(db.queryClient, {
- snapshot: { kind: "server-detail", data: detail },
+ snapshot: { kind: "server-detail", data: serverDirectoryFixture(detail) },
proof: { kind: "structural", token, signal: undefined },
})
@@ -774,10 +797,10 @@ describe("community DB sync", () => {
it("promotes server detail completeness over a newer WS server update", async () => {
const db = await registry()
- ingestServers(db, { servers: [{
+ ingestServers(db, serverRailResponseFixture({ servers: [{
id: "s1", name: "Stale server", initial: "S", active: false,
unread: false, mentions: 0, ownerId: "viewer",
- }] })
+ }] }, db.accountId))
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, {
@@ -788,22 +811,20 @@ describe("community DB sync", () => {
publishCommunityLiveSnapshotWithProof(db.queryClient, {
snapshot: {
kind: "server-detail",
- data: {
+ data: serverDirectoryFixture({
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.servers.get("s1")).toMatchObject({ name: "Fresh server" })
+ expect(db.queryClient.getQueryData(communityKeys.server("s1"))).toMatchObject({ serverId: "s1", channelIds: ["c1"] })
expect(db.collections.channels.get("c1")?.name).toBe("general")
})
@@ -827,7 +848,7 @@ describe("community DB sync", () => {
changes: { name: "fresh channel" },
} as CommunityWsEvent)
publishCommunityLiveSnapshotWithProof(db.queryClient, {
- snapshot: { kind: "server-detail", data: detail },
+ snapshot: { kind: "server-detail", data: serverDirectoryFixture(detail) },
proof: { kind: "structural", token, signal: undefined },
})
@@ -845,11 +866,11 @@ describe("community DB sync", () => {
}],
}],
}
- ingestServers(db, { servers: [{
+ ingestServers(db, serverRailResponseFixture({ servers: [{
id: "s1", name: "Server", initial: "S", active: false,
unread: false, mentions: 0, ownerId: "viewer",
- }] })
- ingestServerDetail(db, detail)
+ }] }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture(detail))
const token = captureCommunityLiveSnapshotToken(db.queryClient)
projectCommunityWsEventToDb(db.queryClient, {
@@ -1071,7 +1092,7 @@ describe("community DB sync", () => {
status: "offline" as const,
preview: "",
})
- const detail = (channelIds: string[]) => ({
+ const detail = (channelIds: string[]) => (serverDirectoryFixture({
id: "merge-s1",
name: "Merge",
discriminator: "0001",
@@ -1088,11 +1109,11 @@ describe("community DB sync", () => {
unread: false,
})),
}],
- })
+ }))
publishCommunityLiveSnapshot(db.queryClient, {
kind: "servers",
- data: { servers: [server("merge-s1"), server("merge-s2")] },
+ data: serverRailResponseFixture({ servers: [server("merge-s1"), server("merge-s2")] }, "viewer"),
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "server-detail",
@@ -1100,7 +1121,7 @@ describe("community DB sync", () => {
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "dms",
- data: { conversations: [dm("merge-dm1", "peer1"), dm("merge-dm2", "peer2")] },
+ data: { conversations: ([dm("merge-dm1", "peer1"), dm("merge-dm2", "peer2")]).map(row => dmListRowFixture(row, "viewer")) },
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "folders",
@@ -1192,7 +1213,7 @@ describe("community DB sync", () => {
status: "offline" as const,
preview: "",
})
- const detail = (channelIds: string[]) => ({
+ const detail = (channelIds: string[]) => (serverDirectoryFixture({
id: "live-s1",
name: "Live",
discriminator: "0001",
@@ -1209,11 +1230,11 @@ describe("community DB sync", () => {
unread: false,
})),
}],
- })
+ }))
publishCommunityLiveSnapshot(db.queryClient, {
kind: "servers",
- data: { servers: [server("live-s1"), server("live-s2")] },
+ data: serverRailResponseFixture({ servers: [server("live-s1"), server("live-s2")] }, "viewer"),
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "server-detail",
@@ -1221,7 +1242,7 @@ describe("community DB sync", () => {
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "dms",
- data: { conversations: [dm("live-dm1", "peer1"), dm("live-dm2", "peer2")] },
+ data: { conversations: ([dm("live-dm1", "peer1"), dm("live-dm2", "peer2")]).map(row => dmListRowFixture(row, "viewer")) },
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "folders",
@@ -1268,7 +1289,7 @@ describe("community DB sync", () => {
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "dms",
- data: { conversations: [dm("live-dm1", "peer1")] },
+ data: { conversations: ([dm("live-dm1", "peer1")]).map(row => dmListRowFixture(row, "viewer")) },
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "folders",
@@ -1301,7 +1322,7 @@ describe("community DB sync", () => {
})
publishCommunityLiveSnapshot(db.queryClient, {
kind: "servers",
- data: { servers: [server("live-s1")] },
+ data: serverRailResponseFixture({ servers: [server("live-s1")] }, "viewer"),
})
expect(db.collections.servers.get("live-s2")).toBeUndefined()
@@ -1333,9 +1354,9 @@ describe("community DB sync", () => {
ownerId: "viewer",
}
- ingestServers(db, { servers: [rail] })
- expect(db.collections.servers.get("s1")?.detailComplete).toBe(false)
- ingestServerDetail(db, {
+ ingestServers(db, serverRailResponseFixture({ servers: [rail] }, db.accountId))
+ expect(db.queryClient.getQueryData(communityKeys.server("s1"))).toBeUndefined()
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Server",
discriminator: "0001",
@@ -1343,26 +1364,26 @@ describe("community DB sync", () => {
icon: null,
ownerId: "viewer",
categories: [],
- })
- expect(db.collections.servers.get("s1")?.detailComplete).toBe(true)
- ingestServerDetail(db, {
+ }))
+ expect(db.queryClient.getQueryData(communityKeys.server("s1"))).toMatchObject({ serverId: "s1" })
+ ingestServerDetail(db, serverDirectoryFixture({
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, {
+ }))
+ ingestServerDetail(db, serverDirectoryFixture({
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)
+ }))
+ ingestServers(db, serverRailResponseFixture({ servers: [rail] }, db.accountId))
+ expect(db.queryClient.getQueryData(communityKeys.server("s1"))).toMatchObject({ serverId: "s1" })
expect(getCommunityDbRegistry(db.queryClient)).toBe(db)
const originalGetQueryData = db.queryClient.getQueryData.bind(db.queryClient)
@@ -1372,13 +1393,13 @@ describe("community DB sync", () => {
? undefined
: originalGetQueryData(key)
))
- ingestServers(db, { servers: [rail] })
+ ingestServers(db, serverRailResponseFixture({ servers: [rail] }, db.accountId))
getQueryData.mockRestore()
})
it("normalizes server, tree, and DM relationships into canonical identities", async () => {
const db = await registry()
- ingestServers(db, {
+ ingestServers(db, serverRailResponseFixture({
servers: [{
id: "s1",
name: "Alook",
@@ -1391,8 +1412,8 @@ describe("community DB sync", () => {
mentions: 0,
isOwner: true,
}],
- })
- ingestServerDetail(db, {
+ }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Alook",
discriminator: "0001",
@@ -1410,9 +1431,9 @@ describe("community DB sync", () => {
type: "text",
}],
}],
- })
+ }))
ingestDms(db, {
- conversations: [{
+ conversations: ([{
id: "dm1",
userId: "peer",
name: "Peer",
@@ -1423,17 +1444,16 @@ describe("community DB sync", () => {
preview: "hello",
unread: true,
lastUnreadSeq: 7,
- }],
+ }]).map(row => dmListRowFixture(row, db.accountId!)),
})
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.channelMemberships.get("c1:viewer:access")).toBeUndefined()
+ publishCommunityChannelMetadata(db.queryClient, { metadata: CommunityChannelResourceSchema.strip().parse(db.collections.channels.get("c1")), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
+ expect(db.collections.channelMemberships.get("c1:viewer:access")).toMatchObject({ relation: "access", source: "explicit" })
expect(db.collections.channels.get("dm1")).toMatchObject({ type: "dm", serverId: null })
expect(db.collections.channelMemberships.get("dm1:viewer:access")).toBeDefined()
expect(db.collections.channelMemberships.get("dm1:peer:access")).toBeDefined()
@@ -1528,7 +1548,7 @@ describe("community DB sync", () => {
const newer = forumAttentionSnapshot(5)
const older = forumAttentionSnapshot(4)
const snapshot = AccountAttentionSnapshotSchema.parse({
- ...newer, scopes: newer.scopes.map((scope) => ({ ...scope, attentionCount: 2 })),
+ ...newer, resources: resourceBundleFixture({ ...newer.resources, messages: [...newer.resources.messages, ...older.resources.messages.filter(message => message.id === "m4")] }), scopes: newer.scopes.map((scope) => ({ ...scope, attentionCount: 2 })),
items: [...older.items, ...newer.items],
included: { ...newer.included, messages: [...newer.included.messages, ...older.included.messages.filter((message) => message.id === "m4")] },
})
@@ -1563,7 +1583,7 @@ describe("community DB sync", () => {
const base = forumAttentionSnapshot()
const at = base.included.messages[0]!.createdAt
const snapshot = AccountAttentionSnapshotSchema.parse({
- ...base,
+ ...base, resources: resourceBundleFixture({ ...base.resources, profiles: [...base.resources.profiles, { id: "requester", name: "Requester", discriminator: "0003", avatar: null, avatarVersion: 0 }] }),
items: [...base.items, { id: "friend_request:request", kind: "friend_request", sourceId: "request", actorUserId: "requester", createdAt: at }],
included: { ...base.included, profiles: [...base.included.profiles, { userId: "requester", name: "Requester", discriminator: "0003", avatar: "R", avatarVersion: 0 }] },
})
@@ -1575,13 +1595,13 @@ describe("community DB sync", () => {
expect(db.collections.friendships.get("request")).toMatchObject({ kind: "incoming", userId: "requester" })
})
- it("keeps an unknown-sequence cached item when another scope rebases confirmed attention", async () => {
+ it("keeps an item with an unloaded message when another scope rebases confirmed attention", async () => {
const db = await registry()
const snapshot = forumAttentionSnapshot()
ingestAttentionSnapshot(db, snapshot)
const key = communityKeys.communityDbCollection(db.scopeId, "messages")
- db.queryClient.setQueryData(key, (rows: Array<{ id: string; seq?: number }>) => rows.map((row) => row.id === "m4" ? { ...row, seq: undefined } : row))
- db.collections.messages.utils.writeUpsert({ ...db.collections.messages.get("m4")!, seq: undefined })
+ await writeCommunityCollectionRows(db, "messages", db.queryClient.getQueryData<Array<{ id: string }>>(key)!.filter(row => row.id !== "m4"), row => row.id)
+ expect(db.collections.messages.get("m4")).toBeUndefined()
ingestReadStateSnapshot(db, { revision: 1, readStates: [{ channelId: "post", lastReadMessageId: "m4", lastReadAt: snapshot.included.messages[0]!.createdAt, lastReadSeq: 4 }] })
const optimistic = clearAttentionScopeOptimistically(db, "other", 0)
expect(db.collections.attentionItems.get("reply:m4")).toBeDefined()
@@ -1602,7 +1622,7 @@ describe("community DB sync", () => {
lastAttentionSeq: 4,
attentionCount: 1,
}
- ingestAttentionSnapshot(db, {
+ ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }),
scopes: [scope],
items: [],
limit: 100,
@@ -1611,7 +1631,7 @@ describe("community DB sync", () => {
const token = captureCommunityLiveSnapshotToken(db.queryClient)
expect(publishAccountAttentionSnapshot(db.queryClient, {
- snapshot: { scopes: [], items: [], limit: 100, truncated: false },
+ snapshot: { resources: resourceBundleFixture(), scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
proof: { token, signal: undefined },
})).toBe("published")
expect(db.collections.attentionScopes.get("c1")).toBeUndefined()
@@ -1619,7 +1639,7 @@ describe("community DB sync", () => {
it("hydrates new DMs while preserving richer existing channel state", async () => {
const db = await registry()
- ingestDms(db, { conversations: [{
+ ingestDms(db, { conversations: ([{
id: "existing",
userId: "peer-existing",
name: "Existing",
@@ -1630,14 +1650,16 @@ describe("community DB sync", () => {
preview: "keep preview",
activityAt: "2026-09-27T00:00:01.000Z",
unread: false,
- }] })
+ }]).map(row => dmListRowFixture(row, db.accountId!)) })
const existing = db.collections.channels.get("existing")!
const patched = { ...existing, position: 7, muted: true }
- const channelKey = communityKeys.communityDbCollection(db.scopeId, "channels")
- db.collections.channels.utils.writeUpsert(patched)
- db.queryClient.setQueryData(channelKey, [patched])
+ await writeCommunityCollectionRows(db, "channels", [patched], row => row.id)
- ingestAttentionSnapshot(db, {
+ ingestAttentionSnapshot(db, { resources: fullResourceBundleFixture("viewer", [], [
+ { ...CommunityChannelResourceSchema.strip().parse(existing), position: 7, lastMessageAt: "2026-09-28T00:00:07.000Z" },
+ channelResourceFixture({ id: "new", type: "dm", serverId: null, name: null, position: 1, lastMessageAt: "2026-09-28T00:00:08.000Z" }),
+ ], [], [{ id: "peer-existing", name: "Existing", discriminator: "0002", avatar: null, avatarVersion: 2 },
+ { id: "peer-new", name: "New", discriminator: "0003", avatar: null, avatarVersion: 1 }]),
scopes: [],
items: [],
limit: 100,
@@ -1691,10 +1713,10 @@ describe("community DB sync", () => {
expect(db.collections.channels.get("new")).toMatchObject({
position: 1,
muted: false,
- preview: "",
lastMessageAt: "2026-09-28T00:00:08.000Z",
})
})
+ expect(db.collections.channels.get("new")?.preview).toBeUndefined()
})
it("updates every affected scope when attention items are removed", async () => {
@@ -1722,7 +1744,7 @@ describe("community DB sync", () => {
actorUserId: "actor",
createdAt: "2026-09-28T00:00:09.000Z",
})
- const snapshot = {
+ const snapshot = { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(),
scopes: [
scope("multiple", false, 2),
scope("attention-only", false, 1),
@@ -1776,22 +1798,22 @@ describe("community DB sync", () => {
lastAttentionSeq: 4,
attentionCount: 1,
}
- ingestAttentionSnapshot(db, { scopes: [scope], items: [], limit: 100, truncated: false })
+ ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }), 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 },
+ snapshot: { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(), 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 })
+ ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }), scopes: [scope], items: [], limit: 100, truncated: false })
const duringToken = captureCommunityLiveSnapshotToken(db.queryClient)
const during = clearAttentionOptimistically(db)
publishAccountAttentionSnapshot(db.queryClient, {
- snapshot: { scopes: [scope], items: [], limit: 100, truncated: false },
+ snapshot: { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(), scopes: [scope], items: [], limit: 100, truncated: false },
proof: { token: duringToken, signal: undefined },
})
expect(db.collections.attentionScopes.get("c1")).toBeUndefined()
@@ -1800,7 +1822,7 @@ describe("community DB sync", () => {
it("keeps a higher-seq scope and item through a target-seq attention reconcile", async () => {
const db = await registry()
- ingestMessages(db, "c1", [
+ ingestMessages(db, "c1", messageSeedFixture("c1", [
{
id: "m4",
type: "chat",
@@ -1815,7 +1837,7 @@ describe("community DB sync", () => {
seq: 5,
createdAt: "2026-09-27T01:01:00.000Z",
},
- ])
+ ]))
const oldItem = {
id: "mention:old",
kind: "mention" as const,
@@ -1844,7 +1866,7 @@ describe("community DB sync", () => {
lastAttentionSeq: 4,
attentionCount: 1,
}
- ingestAttentionSnapshot(db, {
+ ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }),
scopes: [{
...oldScope,
lastUnreadSeq: 5,
@@ -1866,7 +1888,7 @@ describe("community DB sync", () => {
expect(db.collections.attentionItems.get(oldItem.id)).toBeUndefined()
expect(db.collections.attentionItems.get(newItem.id)).toMatchObject(newItem)
- ingestAttentionSnapshot(db, {
+ ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }),
scopes: [{
...oldScope,
lastUnreadSeq: 5,
@@ -1892,7 +1914,7 @@ describe("community DB sync", () => {
"uses the exact aggregate baseline for a truncated target-seq %s",
async (terminal) => {
const db = await registry()
- ingestMessages(db, "c1", [{
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{
id: "m4",
type: "chat",
authorId: "u2",
@@ -1910,7 +1932,7 @@ describe("community DB sync", () => {
authorId: "u2",
seq: 6,
createdAt: "2026-09-27T01:02:00.000Z",
- }])
+ }]))
const newItem = {
id: "mention:new",
kind: "mention" as const,
@@ -1920,7 +1942,7 @@ describe("community DB sync", () => {
actorUserId: "u2",
createdAt: "2026-09-27T01:01:00.000Z",
}
- const truncatedSnapshot = {
+ const truncatedSnapshot = { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(),
scopes: [{
scopeId: "c1",
channelId: "c1",
@@ -1950,7 +1972,7 @@ describe("community DB sync", () => {
commitAttentionScopeOptimisticSnapshot(db, optimistic)
expect(db.collections.attentionScopes.get("c1")?.attentionCount).toBe(1)
} else {
- const newerSnapshot = {
+ const newerSnapshot = { resources: resourceBundleFixture(),
scopes: [{
...truncatedSnapshot.scopes[0]!,
lastUnreadSeq: 6,
@@ -1988,7 +2010,7 @@ describe("community DB sync", () => {
it("retires a completed attention transaction before a simultaneous canonical rebase", async () => {
const db = await registry()
- const snapshot = {
+ const snapshot = { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(),
scopes: ["c1", "c2"].map((scopeId) => ({ scopeId, channelId: scopeId, serverId: "s1", parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 5, lastAttentionSeq: null, attentionCount: 0 })),
items: [], limit: 100, truncated: false,
}
@@ -2009,7 +2031,7 @@ describe("community DB sync", () => {
nativeSetState(state)
if (state === "completed" && !rebased) {
rebased = true
- ingestAttentionSnapshot(db, { ...snapshot, scopes: [] })
+ ingestAttentionSnapshot(db, { resources: resourceBundleFixture({ viewerId: db.accountId! }), ...snapshot, scopes: [] })
}
})
await expect(Promise.all([commitAttentionScopeOptimisticSnapshot(db, first), commitAttentionScopeOptimisticSnapshot(db, second)])).resolves.toEqual([true, true])
@@ -2022,7 +2044,7 @@ describe("community DB sync", () => {
"does not double-subtract nested scope fences when %s settles",
async (settledFirst) => {
const db = await registry()
- ingestMessages(db, "c1", [{
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{
id: "m4",
type: "chat",
authorId: "u2",
@@ -2032,7 +2054,7 @@ describe("community DB sync", () => {
type: "chat",
authorId: "u2",
seq: 5,
- }])
+ }]))
const items = [4, 5].map((seq) => ({
id: `mention:${seq}`,
kind: "mention" as const,
@@ -2042,7 +2064,7 @@ describe("community DB sync", () => {
actorUserId: "u2",
createdAt: `2026-09-27T01:0${seq}:00.000Z`,
}))
- const snapshot = {
+ const snapshot = { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(),
scopes: [{
scopeId: "c1",
channelId: "c1",
@@ -2093,12 +2115,7 @@ describe("community DB sync", () => {
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,
- })))
+ ingestMessages(db, "c1", [4, 5, 6].map((seq) => messageResourceFixture({ id: `m${seq}`, channelId: "c1", authorId: "u2", seq, content: "Body" })))
const items = [4, 5, 6].map((seq) => ({
id: `mention:${seq}`,
kind: "mention" as const,
@@ -2109,7 +2126,7 @@ describe("community DB sync", () => {
createdAt: `2026-09-27T01:0${seq}:00.000Z`,
}))
const reconcileToken = captureCommunityLiveSnapshotToken(db.queryClient)
- publishAccountAttentionSnapshot(db.queryClient, { snapshot: {
+ publishAccountAttentionSnapshot(db.queryClient, { snapshot: { resources: resourceBundleFixture(),
scopes: [{
scopeId: "c1",
channelId: "c1",
@@ -2138,14 +2155,14 @@ describe("community DB sync", () => {
it("preserves a higher-seq authoritative scope and item when an older optimistic read fails", async () => {
const db = await registry()
- ingestMessages(db, "c1", [{
+ ingestMessages(db, "c1", messageSeedFixture("c1", [{
id: "m5",
type: "chat",
authorId: "u2",
seq: 5,
createdAt: "2026-09-27T01:01:00.000Z",
- }])
- ingestAttentionSnapshot(db, {
+ }]))
+ ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }),
scopes: [{
scopeId: "c1",
channelId: "c1",
@@ -2169,7 +2186,7 @@ describe("community DB sync", () => {
truncated: false,
})
const optimistic = clearAttentionScopeOptimistically(db, "c1", 4)
- const newerSnapshot = {
+ const newerSnapshot = { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture(),
scopes: [{
scopeId: "c1",
channelId: "c1",
@@ -2207,65 +2224,85 @@ describe("community DB sync", () => {
expect(db.collections.attentionItems.get("mention:old")).toBeUndefined()
})
- it("merges partial attention hydration without erasing richer profile or message fields", async () => {
+ it("publishes complete Forum member facts into their separate canonical domains", 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: [{ name: "proof.png", url: "/proof.png", contentType: "image/png" }],
- replyTo: { id: "m0", authorId: "u3", authorName: "Bob", text: "earlier" },
- }])
+ const value = forumConversationEntryFixture()
+ const profile = { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 1 }
+ const page = normalizeThreadResources("c1", { ...value.forumFeed, included: { ...value.forumFeed!.included,
+ members: [{ channelId: "t1", userId: "peer", relation: "notify", source: "spoke", isCreator: false, role: "member", memberId: "member-peer" }], profiles: [profile] } })
+ publishCommunityForumFeed(db.queryClient, "c1", page, { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") })
+ expect(db.collections.channelMemberships.get("t1:peer:notify")).toMatchObject({ id: "t1:peer:notify", channelId: "t1", userId: "peer", relation: "notify", source: "spoke" })
+ expect(db.collections.channelMemberships.get("t1:peer:notify")).not.toHaveProperty("role")
+ expect(db.collections.serverMemberships.get("s1:peer")).toMatchObject({ serverId: "s1", userId: "peer", memberId: "member-peer", role: "member" })
+ expect(db.collections.profiles.get("peer")).toMatchObject(profile)
+ })
- 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",
- }],
- },
- })
+ it.each(["forum-empty", "forum-messages", "members"].flatMap(surface => ["missing-avatar", "later-invalid"].map(invalid => ({ surface, invalid }))))(
+ "rejects raw full profile $invalid atomically through $surface", async ({ surface, invalid }) => {
+ const db = await registry()
+ const profile = { id: "peer", name: "Original Name", discriminator: "0042", avatar: null, avatarVersion: 7 }
+ const channel = channelResourceFixture({ id: "c1", type: "forum" })
+ const child = channelResourceFixture({ id: "t1", type: "thread", parentChannelId: channel.id, parentMessageId: "m1" })
+ publishCommunityResourceBundle(db.queryClient, fullResourceBundleFixture("viewer", [serverResourceFixture()], [channel, child], [], [profile]), { token: captureCommunityLiveSnapshotToken(db.queryClient, channel.id) })
+ const collections = ["profiles", "channels", "channelMemberships", "serverMemberships", "messages"] as const
+ const before = new Map(collections.map(name => [name, db.queryClient.getQueryData(communityKeys.communityDbCollection(db.scopeId, name))]))
+ const { avatar: _avatar, ...incomplete } = profile
+ const profiles = invalid === "missing-avatar" ? [incomplete] : [{ ...profile, name: "Must Not Publish" }, { ...profile, id: "bad", avatarVersion: -1 }]
+ const proof = { token: captureCommunityLiveSnapshotToken(db.queryClient, channel.id) }
+ const publish = () => {
+ if (surface === "members") publishCommunityChannelMembersSnapshot(db.queryClient, "s1", child.id, "notify", [{ channelId: child.id, userId: profile.id, relation: "notify", source: "explicit", role: "member", memberId: "new-membership", isCreator: false }], proof, profiles as typeof profile[])
+ else {
+ const feed = forumConversationEntryFixture().forumFeed!
+ const included = { ...feed.included, profiles, messages: surface === "forum-empty" ? [] : [messageResourceFixture({ authorId: profile.id })], previews: [] }
+ publishCommunityForumFeed(db.queryClient, channel.id, { ...feed, threads: [{ ...child, name: "Must Not Publish" }], included } as Parameters<typeof publishCommunityForumFeed>[2], proof)
+ }
+ }
+ expect(publish).toThrow()
+ for (const name of collections) expect(db.queryClient.getQueryData(communityKeys.communityDbCollection(db.scopeId, name))).toBe(before.get(name))
+ },
+ )
- 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: [{ name: "proof.png", url: "/proof.png", contentType: "image/png" }],
- replyTo: { id: "m0", authorId: "u3" },
- })
+ it.each(["bundle", "dm-entry", "forum-feed"].flatMap(surface => [false, true].flatMap(warm => [6, 8].map(hintVersion => ({ surface, warm, hintVersion })))))(
+ "keeps full profile identity on $surface with warm=$warm and message avatar=$hintVersion", async ({ surface, warm, hintVersion }) => {
+ const db = await registry()
+ const profile = { id: "peer", name: "Current Name", discriminator: "0042", avatar: "current.png", avatarVersion: 7 }
+ if (warm) writeCommunityProfilePatches([{ id: profile.id, identityAbout: { name: "Previously Known", discriminator: "0042", aboutMe: "Retained bio" },
+ avatar: { avatar: "previous.png", avatarVersion: 5 } }], db)
+ const message = messageResourceFixture({ id: "m1", channelId: "c1", authorId: profile.id, authorName: "Historical Author", authorAvatar: "hint.png", authorAvatarVersion: hintVersion,
+ replyToId: "earlier", replyTo: { id: "earlier", authorId: profile.id, authorName: "Historical Reply", text: "Earlier" } })
+ const proof = { token: captureCommunityLiveSnapshotToken(db.queryClient, "c1") }
+ if (surface === "bundle") {
+ const resources = fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "c1", serverId: "s1" })], [message], [profile])
+ publishCommunityResourceBundle(db.queryClient, resources, proof)
+ } else if (surface === "dm-entry") {
+ const value = dmConversationEntryFixture()
+ publishConversationEntry(db.queryClient, { channelId: "c1", serverId: null }, { ...value, peer: profile, profiles: [profile], messages: [message] }, proof)
+ } else {
+ const value = forumConversationEntryFixture()
+ const page = normalizeThreadResources("c1", { ...value.forumFeed, included: { ...value.forumFeed!.included, messages: [message], profiles: [profile] } })
+ publishCommunityForumFeed(db.queryClient, "c1", page, proof)
+ }
+ expect(db.collections.profiles.get(profile.id)).toMatchObject({ ...profile,
+ avatar: hintVersion > profile.avatarVersion ? "hint.png" : profile.avatar, avatarVersion: Math.max(profile.avatarVersion, hintVersion),
+ ...(warm ? { aboutMe: "Retained bio" } : {}) })
+ expect(db.collections.messages.get(message.id)).toMatchObject({ authorName: "Historical Author", replyTo: message.replyTo, authorAvatarVersion: hintVersion })
+ },
+ )
+
+ it("uses full attention resources while preserving independent profile domains and complete 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: "Shipping", statusText: "Shipping" } }], db)
+ const rich = messageResourceFixture({ id: "m1", channelId: "c1", authorId: "u2", authorName: "Alice", content: "rich", replyToId: "m0",
+ attachments: [{ id: "proof", name: "proof.png", url: "/proof.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: null, width: null, height: null }],
+ replyTo: { id: "m0", authorId: "u3", authorName: "Bob", text: "earlier" } })
+ ingestMessages(db, "c1", [rich])
+ const profile = { id: "u2", name: "Alice Updated", discriminator: "0002", avatar: "base.png", avatarVersion: 2 }
+ const resources = fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1" })], [channelResourceFixture({ id: "c1", serverId: "s1" })], [{ ...rich, content: "new preview" }], [profile, profileResourceFixture({ id: "u3", name: "Bob" })])
+ ingestAttentionSnapshot(db, AccountAttentionSnapshotSchema.parse({ resources, scopes: [], items: [], limit: 100, truncated: false,
+ included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }))
+ expect(db.collections.profiles.get("u2")).toMatchObject({ name: "Alice Updated", aboutMe: "rich bio", ownerUserId: "owner", statusEmoji: "Shipping", statusText: "Shipping" })
+ expect(db.collections.messages.get("m1")).toMatchObject({ content: "new preview", attachments: rich.attachments, replyTo: { id: "m0", authorId: "u3" } })
})
it("cascades roots removed by authoritative server, tree, and DM replacement", async () => {
@@ -2278,13 +2315,13 @@ describe("community DB sync", () => {
removeItem: (key: string) => navigationMemory.delete(key),
})
- ingestServers(db, {
+ ingestServers(db, serverRailResponseFixture({
servers: [{
id: "s1", name: "Server", initial: "S", active: false, unread: false,
mentions: 0, ownerId: "viewer",
}],
- })
- ingestServerDetail(db, {
+ }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Server",
discriminator: "0001",
@@ -2296,20 +2333,20 @@ describe("community DB sync", () => {
name: "General",
channels: [{ id: "c1", name: "chat", active: false, unread: false }],
}],
- })
+ }))
projectCommunityWsEventToDb(db.queryClient, {
type: "community:channel.child_create",
parentChannelId: "c1",
parentMessageId: "opener",
- channel: {
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("c1")?.serverId ?? "s1", parentChannelId: "c1", parentMessageId: "opener", ...{
id: "thread1", name: "Thread", type: "thread",
createdAt: "2026-09-25T00:00:00.000Z",
- },
+ } }),
} as CommunityWsEvent)
- ingestMessages(db, "thread1", [{
+ ingestMessages(db, "thread1", messageSeedFixture("thread1", [{
id: "m1", type: "chat", authorId: "thread-author", authorName: "Thread Author",
content: "thread", createdAt: "2026-09-25T00:00:01.000Z",
- }])
+ }]))
seedCommunityAttentionScope(db.queryClient, { channelId: "c1", serverId: "s1", seq: 1 })
db.queryClient.setQueryData(communityKeys.inboxUnreads(), {
friendRequests: [],
@@ -2332,7 +2369,7 @@ describe("community DB sync", () => {
dms: [],
})
setLastChannel("s1", "c1")
- ingestServerDetail(db, {
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Server",
discriminator: "0001",
@@ -2340,7 +2377,7 @@ describe("community DB sync", () => {
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()
@@ -2353,15 +2390,15 @@ describe("community DB sync", () => {
expect(getLastChannel("s1")).toBeNull()
ingestDms(db, {
- conversations: [{
+ conversations: ([{
id: "dm1", userId: "peer", name: "Peer", discriminator: "0002",
avatar: "P", avatarVersion: 1, status: "offline", preview: "",
- }],
+ }]).map(row => dmListRowFixture(row, db.accountId!)),
})
- ingestMessages(db, "dm1", [{
+ ingestMessages(db, "dm1", messageSeedFixture("dm1", [{
id: "dm-message", type: "chat", authorId: "peer", authorName: "Peer",
content: "dm", createdAt: "2026-09-25T00:00:02.000Z",
- }])
+ }]))
seedCommunityAttentionScope(db.queryClient, { channelId: "dm1", seq: 2 })
db.queryClient.setQueryData(communityKeys.inboxUnreads(), {
friendRequests: [],
@@ -2369,7 +2406,7 @@ describe("community DB sync", () => {
dms: [{ channelId: "dm1" }],
})
setLastMeLocation("/c/me/dm1")
- ingestDms(db, { conversations: [] })
+ ingestDms(db, { conversations: ([]).map(row => dmListRowFixture(row, db.accountId!)) })
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()
@@ -2381,14 +2418,14 @@ describe("community DB sync", () => {
)?.dms).toEqual([])
expect(getLastMeLeaf()).toBeNull()
- ingestServers(db, { servers: [] })
+ ingestServers(db, serverRailResponseFixture({ servers: [] }, db.accountId))
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, {
+ ingestServers(db, serverRailResponseFixture({
servers: [
{
id: "s1", name: "Removed", initial: "R", active: false, unread: false,
@@ -2399,7 +2436,11 @@ describe("community DB sync", () => {
mentions: 0, ownerId: "owner-kept",
},
],
- })
+ }, db.accountId))
+ await writeCommunityCollectionRows(db, "profiles", [
+ { id: "owner-removed", name: "Removed", discriminator: "0001", avatar: null, avatarVersion: 0 },
+ { id: "owner-kept", name: "Kept", discriminator: "0001", avatar: null, avatarVersion: 0 },
+ ], row => row.id)
for (const [userId, name] of [["owner-removed", "Removed"], ["owner-kept", "Kept"]] as const) {
projectCommunityWsEventToDb(db.queryClient, {
type: "community:profile.update",
@@ -2413,18 +2454,18 @@ describe("community DB sync", () => {
} as CommunityWsEvent)
}
- ingestServers(db, {
+ ingestServers(db, serverRailResponseFixture({
servers: [{
id: "s2", name: "Kept", initial: "K", active: false, unread: false,
mentions: 0, ownerId: "owner-kept",
}],
- })
+ }, db.accountId))
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 () => {
+ it("ignores sparse unknown profiles then keeps full profile patches monotonic across sparse authors", async () => {
const db = await registry()
projectCommunityWsEventToDb(db.queryClient, {
type: "community:status.update",
@@ -2438,12 +2479,15 @@ describe("community DB sync", () => {
avatar: "/peer-v5.png",
avatarVersion: 5,
} as CommunityWsEvent)
+ expect(db.collections.profiles.has("peer")).toBe(false)
ingestDms(db, {
- conversations: [{
+ conversations: ([{
id: "dm1", userId: "peer", name: "Peer", discriminator: "0002",
avatar: "/stale.png", avatarVersion: 4, status: "offline", preview: "",
- }],
+ }]).map(row => dmListRowFixture(row, db.accountId!)),
})
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:status.update", userId: "peer", statusEmoji: "Growing", statusText: "Growing" })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:identity.update", userId: "peer", avatar: "/peer-v5.png", avatarVersion: 5 })
projectCommunityWsEventToDb(db.queryClient, {
type: "community:profile.update",
userId: "peer",
@@ -2454,11 +2498,11 @@ describe("community DB sync", () => {
kind: "human",
ownerUserId: null,
} as CommunityWsEvent)
- ingestMessages(db, "dm1", [{
+ ingestMessages(db, "dm1", messageSeedFixture("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",
@@ -2466,14 +2510,14 @@ describe("community DB sync", () => {
avatarVersion: 5,
aboutMe: "rich bio",
bannerColor: "#fff",
- statusEmoji: "🌱",
+ statusEmoji: "Growing",
statusText: "Growing",
})
})
it("purges the complete server closure while preserving DMs", async () => {
const db = await registry()
- ingestServers(db, {
+ ingestServers(db, serverRailResponseFixture({
servers: [{
id: "s1",
name: "Alook",
@@ -2483,8 +2527,8 @@ describe("community DB sync", () => {
mentions: 0,
ownerId: "viewer",
}],
- })
- ingestServerDetail(db, {
+ }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Alook",
discriminator: "0001",
@@ -2496,9 +2540,9 @@ describe("community DB sync", () => {
name: "General",
channels: [{ id: "c1", name: "chat", active: false, unread: false }],
}],
- })
+ }))
ingestDms(db, {
- conversations: [{
+ conversations: ([{
id: "dm1",
userId: "peer",
name: "Peer",
@@ -2507,9 +2551,9 @@ describe("community DB sync", () => {
avatarVersion: 1,
status: "offline",
preview: "",
- }],
+ }]).map(row => dmListRowFixture(row, db.accountId!)),
})
- ingestAttentionSnapshot(db, { scopes: [], items: [
+ ingestAttentionSnapshot(db, { included: { servers: [], channels: [], dms: [], profiles: [], messages: [] }, resources: resourceBundleFixture({ viewerId: db.accountId! }), scopes: [], items: [
{ id: "scope-item", kind: "mention", sourceId: "source-1", scopeId: "c1", messageId: "message-1", actorUserId: "peer", createdAt: "now" },
{ id: "child-item", kind: "forum_post", sourceId: "c1", scopeId: "forum", messageId: "opener-2", childChannelId: "c1", openerSeq: 2, readTarget: { channelId: "forum", seq: 2 }, createdAt: "now" },
{ id: "target-item", kind: "forum_post", sourceId: "other-child", scopeId: "other-forum", messageId: "opener-3", childChannelId: "other-child", openerSeq: 3, readTarget: { channelId: "c1", seq: 3 }, createdAt: "now" },
@@ -2525,8 +2569,8 @@ describe("community DB sync", () => {
it("keeps channel retirement fail-closed when native disk retirement rejects", async () => {
const db = await registry(), error = new Error("IDB unavailable")
- ingestMessages(db, "dm-A", [{ id: "retire-message", type: "chat", content: "old" }])
- ingestMessages(db, "dm-B", [{ id: "sibling-message", type: "chat", content: "keep" }])
+ ingestMessages(db, "dm-A", messageSeedFixture("dm-A", [{ id: "retire-message", type: "chat", content: "old" }]))
+ ingestMessages(db, "dm-B", messageSeedFixture("dm-B", [{ id: "sibling-message", type: "chat", content: "keep" }]))
db.bindAuthentication(() => "viewer", () => Promise.resolve(), () => Promise.reject(error))
const report = vi.spyOn(console, "error").mockImplementation(() => {})
retireCommunityChannelReading(db, "dm-A", { reason: "read-denied", serverId: null })
@@ -2562,7 +2606,7 @@ describe("community DB sync", () => {
it("purges only the selected child channel without removing its parent or siblings", async () => {
const db = await registry()
- ingestServerDetail(db, {
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Alook",
discriminator: "0001",
@@ -2574,28 +2618,28 @@ describe("community DB sync", () => {
name: "General",
channels: [{ id: "c1", name: "chat", active: false, unread: false }],
}],
- })
+ }))
projectCommunityWsEventToDb(db.queryClient, {
type: "community:channel.child_create",
parentChannelId: "c1",
parentMessageId: "m1",
- channel: {
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("c1")?.serverId ?? "s1", parentChannelId: "c1", parentMessageId: "m1", ...{
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: {
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("c1")?.serverId ?? "s1", parentChannelId: "c1", parentMessageId: "m2", ...{
id: "thread2",
name: "Thread two",
type: "thread",
createdAt: "2026-09-25T00:00:01.000Z",
- },
+ } }),
} as CommunityWsEvent)
purgeCommunityChannel(db, "thread1")
@@ -2615,7 +2659,7 @@ describe("community DB sync", () => {
removeItem: (key: string) => navigationMemory.delete(key),
})
const uninstall = installCommunityDbSync(db.queryClient, db)
- ingestServerDetail(db, {
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1", name: "Server", discriminator: "0001", description: "",
icon: null, ownerId: "owner",
categories: [{
@@ -2625,12 +2669,12 @@ describe("community DB sync", () => {
{ 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" },
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("c1")?.serverId ?? "s1", parentChannelId: "c1", parentMessageId: "opener", ...{ id: "thread1", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" } }),
} as CommunityWsEvent)
- ingestMessages(db, "c1", [{
+ ingestMessages(db, "c1", messageSeedFixture("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" },
@@ -2639,7 +2683,7 @@ describe("community DB sync", () => {
participants: [{ id: "participant", name: "Participant", avatar: "P", avatarVersion: 1 }],
},
approval: pendingApproval,
- }])
+ }]))
ingestReadStateSnapshot(db, {
revision: 1,
readStates: [{
@@ -2715,19 +2759,19 @@ describe("community DB sync", () => {
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: [{
+ ingestServers(idle, serverRailResponseFixture({ servers: [{
id: "idle", name: "Idle", initial: "I", active: false, unread: false,
mentions: 0, ownerId: "viewer",
- }] })
+ }] }, idle.accountId))
expect(idleClient.getQueryData(communityKeys.communityDbCollection("viewer", "servers"))).toBeDefined()
await idle["cleanup"]()
const anonymous = createCommunityDbRegistry(new QueryClient(), null)
await anonymous.preload()
- ingestDms(anonymous, { conversations: [{
+ ingestDms(anonymous, { conversations: ([{
id: "dm", userId: "peer", name: "Peer", discriminator: "0001",
avatar: "P", avatarVersion: 1, status: "offline", preview: "",
- }] })
+ }]).map(row => dmListRowFixture(row, "viewer")) })
expect(anonymous.collections.channels.size).toBe(0)
await anonymous["cleanup"]()
@@ -2738,7 +2782,7 @@ describe("community DB sync", () => {
it("leaves channel membership projection to the type-resolved handler", async () => {
const db = await registry()
- ingestServerDetail(db, {
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Alook",
discriminator: "0001",
@@ -2750,20 +2794,20 @@ describe("community DB sync", () => {
name: "General",
channels: [{ id: "c1", name: "chat", active: false, unread: false }],
}],
- })
+ }))
projectCommunityWsEventToDb(db.queryClient, {
type: "community:channel.child_create",
parentChannelId: "c1",
parentMessageId: "m1",
- channel: {
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("c1")?.serverId ?? "s1", parentChannelId: "c1", parentMessageId: "m1", ...{
id: "thread1",
name: "Thread one",
type: "thread",
createdAt: "2026-09-25T00:00:00.000Z",
- },
+ } }),
} as CommunityWsEvent)
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:channel.member_add",
+ type: "community:channel.membership.change", present: true, relation: "notify",
serverId: "s1",
channelId: "thread1",
userId: "viewer",
@@ -2771,7 +2815,7 @@ describe("community DB sync", () => {
expect(db.collections.channelMemberships.get("thread1:viewer:notify")).toBeUndefined()
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:channel.member_remove",
+ type: "community:channel.membership.change", present: false, relation: "notify",
serverId: "s1",
channelId: "thread1",
userId: "viewer",
@@ -2782,7 +2826,7 @@ describe("community DB sync", () => {
expect(db.collections.channels.get("c1")).toBeDefined()
projectCommunityWsEventToDb(db.queryClient, {
- type: "community:channel.member_remove",
+ type: "community:channel.membership.change", present: false, relation: "notify",
serverId: "s1",
channelId: "c1",
userId: "viewer",
@@ -2793,7 +2837,7 @@ describe("community DB sync", () => {
it("projects structural, message, and profile websocket deltas into canonical rows", async () => {
const db = await registry()
- ingestServers(db, {
+ ingestServers(db, serverRailResponseFixture({
servers: [{
id: "s1",
name: "Alook",
@@ -2803,9 +2847,9 @@ describe("community DB sync", () => {
mentions: 0,
ownerId: "viewer",
}],
- })
+ }, db.accountId))
ingestDms(db, {
- conversations: [{
+ conversations: ([{
id: "dm1",
userId: "peer",
name: "Peer",
@@ -2814,33 +2858,34 @@ describe("community DB sync", () => {
avatarVersion: 1,
status: "offline",
preview: "",
- }],
+ }]).map(row => dmListRowFixture(row, db.accountId!)),
})
projectCommunityWsEventToDb(db.queryClient, {
type: "community:channel.create",
serverId: "s1",
- channel: {
+ channel: channelResourceFixture({ serverId: "s1", ...{
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",
+ profiles: [profileResourceFixture({ id: "peer", name: "Peer" })],
channelId: "c1",
serverId: "s1",
- message: {
+ message: messageResourceFixture({ channelId: "c1", ...{
id: "m1", seq: 1, authorAvatarVersion: 0,
type: "chat",
authorId: "peer",
authorName: "Peer",
content: "hello",
createdAt: "2026-09-25T00:00:01.000Z",
- },
+ } }),
} as CommunityWsEvent)
projectCommunityWsEventToDb(db.queryClient, {
type: "community:status.update",
@@ -2872,53 +2917,28 @@ describe("community DB sync", () => {
})
})
- it("normalizes raw websocket attachments once at canonical DB ingress", async () => {
+ it("rejects legacy WS attachment fields then stores exact current resource attachments", 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([
- { id: "image", name: "photo.png", url: "/photo.png", contentType: "image/png", sizeBytes: 2048, width: null, height: 480, thumbnailUrl: undefined },
- { id: "file", name: "notes.txt", url: "/notes.txt", contentType: undefined, sizeBytes: undefined, width: undefined, height: undefined, thumbnailUrl: undefined },
- ])
+ const message = messageResourceFixture({ id: "m-attachment", channelId: "c1", authorId: "peer", authorName: "Peer", content: "files" })
+ const event = { type: "community:message.create" as const, channelId: "c1", serverId: "s1", message, profiles: messageProfilesFixture([message]) }
+ const legacy = { ...event, message: { ...message, attachments: [{ id: "image", filename: "photo.png", url: "/photo.png", contentType: "image/png", size: 2048 }] } }
+ expect(() => projectCommunityWsEventToDb(db.queryClient, legacy as never)).toThrow()
+ expect(db.collections.messages.has(message.id)).toBe(false)
+ const attachments = [
+ { id: "image", name: "photo.png", url: "/photo.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: 2048, width: null, height: 480 },
+ { id: "file", name: "notes.txt", url: "/notes.txt", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
+ ]
+ projectCommunityWsEventToDb(db.queryClient, { ...event, message: { ...message, attachments } })
+ expect(db.collections.messages.get(message.id)?.attachments).toEqual(attachments)
})
it("projects every canonical websocket delta family", async () => {
const db = await registry()
- ingestServers(db, { servers: [{
+ ingestServers(db, serverRailResponseFixture({ servers: [{
id: "s1", name: "Server", initial: "S", active: false, unread: false,
mentions: 0, ownerId: "viewer",
- }] })
- ingestServerDetail(db, {
+ }] }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1", name: "Server", discriminator: "0001", description: "",
icon: null, ownerId: "viewer",
categories: [{
@@ -2928,25 +2948,25 @@ describe("community DB sync", () => {
{ id: "c2", name: "two", active: false, unread: false },
],
}],
- })
- ingestMessages(db, "c1", [{
+ }))
+ ingestMessages(db, "c1", messageSeedFixture("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({
+ expect(validateCommunityWsEvent({
type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: null,
channel: { id: "missing-opener", name: "Missing", type: "thread", createdAt: "2026-09-25T00:00:00.000Z" },
- })
+ }).ok).toBe(false)
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" },
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("missing")?.serverId ?? "s1", parentChannelId: "missing", parentMessageId: "m1", ...{ 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: pendingApproval })
@@ -2955,7 +2975,7 @@ describe("community DB sync", () => {
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.create", serverId: "s1", category: categoryResourceFixture({ serverId: "s1", ...{ 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({
@@ -2970,8 +2990,8 @@ describe("community DB sync", () => {
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:channel.membership.change", present: true, relation: "access", serverId: "s1", channelId: "c1", userId: "peer" })
+ event({ type: "community:channel.membership.change", present: false, relation: "access", 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",
@@ -2980,9 +3000,9 @@ describe("community DB sync", () => {
})
event({
type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "m1",
- channel: { id: "thread1", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:01.000Z" },
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("c1")?.serverId ?? "s1", parentChannelId: "c1", parentMessageId: "m1", ...{ id: "thread1", name: "Thread", type: "thread", createdAt: "2026-09-25T00:00:01.000Z" } }),
})
- event({
+ event({ parentChannelId: db.collections.channels.get("thread1")?.parentChannelId ?? "c1",
type: "community:channel.child_update", channelId: "thread1",
changes: { name: "Thread renamed", archived: false, tags: ["tag"], lastMessageAt: "2026-09-25T00:00:02.000Z" },
})
@@ -2998,7 +3018,7 @@ describe("community DB sync", () => {
expect(db.collections.serverMemberships.get("s1:peer")).toBeUndefined()
expect(db.collections.profiles.get("peer")).toMatchObject({ name: "Peer Two", aboutMe: "hello" })
- event({
+ event({ parentChannelId: db.collections.channels.get("thread1")?.parentChannelId ?? "c1",
type: "community:channel.child_update", channelId: "thread1",
changes: { archived: true },
})
@@ -3007,10 +3027,10 @@ describe("community DB sync", () => {
expect(db.collections.channels.get("c2")).toBeUndefined()
purgeCommunityServer(db, "s1")
expect(db.collections.servers.get("s1")).toBeUndefined()
- ingestServers(db, { servers: [{
+ ingestServers(db, serverRailResponseFixture({ servers: [{
id: "leave", name: "Leave", initial: "L", active: false, unread: false,
mentions: 0, ownerId: "viewer",
- }] })
+ }] }, db.accountId))
purgeCommunityServer(db, "leave")
expect(db.collections.servers.get("leave")).toBeUndefined()
event({ type: "community:unknown" })
@@ -3058,7 +3078,7 @@ describe("community DB sync", () => {
})
expect([...db.collections.messages.keys()]).toEqual([])
- ingestMessages(db, "c1", [message("pin", "pin")])
+ ingestMessages(db, "c1", messageSeedFixture("c1", [message("pin", "pin")]))
projectCommunityWsEventToDb(db.queryClient, {
type: "community:reaction.add",
channelId: "c1",
@@ -3086,13 +3106,13 @@ describe("community DB sync", () => {
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, {
+ ingestServers(db, serverRailResponseFixture({
servers: [{
id: "s1", name: "Server", initial: "S", active: false, unread: false,
mentions: 0, ownerId: "viewer",
}],
- })
- ingestServerDetail(db, {
+ }, db.accountId))
+ ingestServerDetail(db, serverDirectoryFixture({
id: "s1",
name: "Server",
discriminator: "0001",
@@ -3104,17 +3124,17 @@ describe("community DB sync", () => {
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: {
+ channel: channelResourceFixture({ serverId: db.collections.channels.get("forum1")?.serverId ?? "s1", parentChannelId: "forum1", parentMessageId: "opener", ...{
id: "thread1",
name: "Thread",
type: "thread",
createdAt: "2026-09-25T00:00:00.000Z",
- },
+ } }),
} as CommunityWsEvent)
db.queryClient.setQueryData(communityKeys.message("opener"), {
@@ -3129,7 +3149,7 @@ describe("community DB sync", () => {
})
expect(db.collections.messages.get("opener")).toBeUndefined()
- ingestMessages(db, "forum1", [{
+ ingestMessages(db, "forum1", messageSeedFixture("forum1", [{
id: "opener",
type: "chat",
authorId: "peer",
@@ -3138,7 +3158,7 @@ describe("community DB sync", () => {
authorAvatarVersion: 0,
content: "cold opener",
createdAt: "2026-09-25T00:00:00.000Z",
- }])
+ }]))
expect(db.collections.messages.get("opener")).toMatchObject({
channelId: "forum1",
content: "cold opener",
@@ -3166,13 +3186,98 @@ describe("community DB sync", () => {
describe("forum archive channel semantics", () => {
- it("keeps opener archive tags separate when publishing embedded thread previews", async () => {
+ it("keeps opener tags separate after full child admission and never invents a child from a message hint", async () => {
const db = await registry()
- const message = { id: "opener", type: "chat" as const, content: "Post", thread: { id: "post", name: "Post", messageCount: 1, tags: ["archived"], participants: [] } }
+ const message = messageResourceFixture({ id: "opener", channelId: "forum", content: "Post", thread: { id: "post", name: "Post", messageCount: 1, tags: ["archived"], participants: [] } })
+ ingestMessages(db, "forum", [message])
+ expect(db.collections.channels.get("post")).toBeUndefined()
+ publishCommunityChannelMetadata(db.queryClient, { metadata: channelResourceFixture({ id: "forum", serverId: "s1", type: "forum" }), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
+ publishCommunityChannelMetadata(db.queryClient, { metadata: channelResourceFixture({ id: "post", serverId: "s1", type: "thread", parentChannelId: "forum", parentMessageId: "opener" }), proof: { token: captureCommunityLiveSnapshotToken(db.queryClient) } })
ingestMessages(db, "forum", [message])
expect(db.collections.channels.get("post")).toMatchObject({ archived: false, tags: ["archived"] })
- db.collections.channels.utils.writeUpsert([{ ...db.collections.channels.get("post")!, archived: true }])
- ingestMessages(db, "forum", [{ ...message, thread: { ...message.thread, tags: [] } }])
+ publishCommunityChannelFields(db.queryClient, "post", { archived: true }, { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ ingestMessages(db, "forum", [{ ...message, thread: { ...message.thread!, tags: [] } }])
expect(db.collections.channels.get("post")).toMatchObject({ archived: true, tags: [] })
})
})
+
+
+describe("current message reference windows", () => {
+ it.each(["missing", "foreign", "duplicate", "extra"] as const)("rejects a %s reference before any canonical publication", async mode => {
+ const db = await registry()
+ const channel = channelResourceFixture({ id: "dm", type: "dm", serverId: null })
+ const message = messageResourceFixture({ id: "message", channelId: channel.id })
+ const resources = fullResourceBundleFixture("viewer", [], [channel], [message])
+ const references = [{ id: mode === "missing" ? "absent" : message.id, channelId: mode === "foreign" ? "foreign" : channel.id }]
+ if (mode === "duplicate") references.push({ ...references[0] })
+ if (mode === "extra") resources.messages.push({ ...message, id: "extra" })
+ expect(() => publishCommunityResourceBundle(db.queryClient, resources, { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined }, references)).toThrow()
+ expect(db.collections.messages.size).toBe(0)
+ expect(db.collections.channels.size).toBe(0)
+ })
+ it("publishes the complete current reference window under its query proof", async () => {
+ const db = await registry()
+ const channel = channelResourceFixture({ id: "dm", type: "dm", serverId: null })
+ const message = messageResourceFixture({ id: "message", channelId: channel.id })
+ publishCommunityResourceBundle(db.queryClient, fullResourceBundleFixture("viewer", [], [channel], [message]), { token: captureCommunityLiveSnapshotToken(db.queryClient), signal: undefined }, [{ id: message.id, channelId: channel.id }])
+ expect(db.collections.messages.get(message.id)).toMatchObject(message)
+ })
+})
+
+it.each(["warm", "cold", "normal"])("retains newer profile and status domains when an older complete message create is delivered later (%s)", async order => {
+ const { encodeCommunityBrowserEvent, decodeCommunityBrowserEvent } = await import("@alook/shared")
+ const db = await registry()
+ const oldProfile = profileResourceFixture({ id: "late-author", name: "Before", aboutMe: "Before about", bannerColor: null, statusEmoji: "old", statusText: "Before status" })
+ if (order === "warm") publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [oldProfile] }), { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ const delayed = encodeCommunityBrowserEvent({ type: "community:message.create", channelId: "c1", message: messageResourceFixture({ id: "late-create", authorId: oldProfile.id, authorName: oldProfile.name, authorAvatarVersion: oldProfile.avatarVersion }), profiles: [oldProfile] })
+ if (!delayed.ok) throw new Error(JSON.stringify(delayed))
+ if (order === "normal") projectCommunityWsEventToDb(db.queryClient, { type: "community:message.create", channelId: "c1", message: messageResourceFixture({ id: "late-create", authorId: oldProfile.id, authorName: oldProfile.name, authorAvatarVersion: oldProfile.avatarVersion }), profiles: [oldProfile] })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:profile.update", userId: oldProfile.id, name: "After", discriminator: "0042", aboutMe: "After about", bannerColor: "blue", kind: "human", ownerUserId: null })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:status.update", userId: oldProfile.id, statusEmoji: null, statusText: null })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:identity.update", userId: oldProfile.id, avatar: "/after.png", avatarVersion: 2 })
+ const received = decodeCommunityBrowserEvent(delayed.envelope)
+ if (!received.ok) throw new Error(JSON.stringify(received))
+ for (let delivery = 0; delivery < 3; delivery++) projectCommunityWsEventToDb(db.queryClient, received.event)
+ expect(db.collections.profiles.get(oldProfile.id)).toMatchObject({ name: "After", aboutMe: "After about", bannerColor: "blue", statusEmoji: null, statusText: null, avatar: "/after.png", avatarVersion: 2 })
+ expect(db.collections.messages.get("late-create")?.authorId).toBe(oldProfile.id)
+})
+
+it("does not let a message dependency seed fence an already in-flight valid HTTP profile read", async () => {
+ const { beginCommunityProfileSeed } = await import("@/lib/community/profile-seed")
+ const db = await registry()
+ const token = captureCommunityLiveSnapshotToken(db.queryClient)
+ const before = beginCommunityProfileSeed(db).revision
+ const profile = profileResourceFixture({ id: "seed-http", name: "Message snapshot", statusEmoji: null, statusText: "" })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:message.create", channelId: "c1", message: messageResourceFixture({ id: "seed-http-message", authorId: profile.id, authorName: profile.name, authorAvatarVersion: 0 }), profiles: [profile] })
+ expect(beginCommunityProfileSeed(db).revision).toBe(before)
+ publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [{ ...profile, name: "Current HTTP", aboutMe: "Actual current read", statusEmoji: "🎧", statusText: "Current" }] }), { token })
+ expect(db.collections.profiles.get(profile.id)).toMatchObject({ name: "Current HTTP", aboutMe: "Actual current read", statusEmoji: "🎧", statusText: "Current" })
+})
+
+it("drops unmaterialized profile fields across the actual profile account epoch", async () => {
+ const db = await registry()
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:profile.update", userId: "epoch-author", name: "Private prior account", discriminator: "9999", aboutMe: "Prior account", bannerColor: null, kind: "human", ownerUserId: null })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:status.update", userId: "epoch-author", statusEmoji: "old", statusText: "Prior account" })
+ expect(db.collections.profiles.has("epoch-author")).toBe(false)
+ db.runtime.ws.actions.activateProfileAccount("other")
+ db.runtime.ws.actions.activateProfileAccount("viewer")
+ const profile = profileResourceFixture({ id: "epoch-author", name: "Current owner", aboutMe: "Current", statusEmoji: null, statusText: "" })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:message.create", channelId: "c1", message: messageResourceFixture({ id: "epoch-message", authorId: profile.id, authorName: profile.name, authorAvatarVersion: 0 }), profiles: [profile] })
+ expect(db.collections.profiles.get(profile.id)).toMatchObject(profile)
+})
+
+it.each([
+ { image: "/api/community/users/other/avatar", currentVersion: 1, expected: "/api/community/users/other/avatar?v=2", expectedVersion: 2 },
+ { image: "/api/community/bots/other/avatar", currentVersion: 1, expected: "/api/community/bots/other/avatar?v=2", expectedVersion: 2 },
+ { image: null, currentVersion: 1, expected: null, expectedVersion: 2 },
+ { image: "https://images.example.test/other.png", currentVersion: 1, expected: "https://images.example.test/other.png", expectedVersion: 2 },
+ { image: "/api/community/users/other/avatar", currentVersion: 3, expected: "/current.png", expectedVersion: 3 },
+])("canonicalizes actual approval image values through the message writer ($image, current=$currentVersion)", async ({ image, currentVersion, expected, expectedVersion }) => {
+ const db = await registry()
+ const other = profileResourceFixture({ id: "other", name: "Current Other", avatar: "/current.png", avatarVersion: currentVersion })
+ publishCommunityResourceBundle(db.queryClient, resourceBundleFixture({ profiles: [other] }), { token: captureCommunityLiveSnapshotToken(db.queryClient) })
+ const author = profileResourceFixture({ id: "approval-bot", name: "Bot" })
+ projectCommunityWsEventToDb(db.queryClient, { type: "community:message.create", channelId: "c1", profiles: [author], message: messageResourceFixture({ id: "approval-image", authorId: author.id, authorName: author.name, authorAvatarVersion: 0,
+ approval: { friendshipId: "friendship", status: "pending", waitingOn: "you", otherProfile: { id: other.id, name: "Card label", discriminator: "0042", image, avatarVersion: 2 }, botProfile: { id: author.id, name: author.name, discriminator: author.discriminator, image: null, avatarVersion: 0 } } }) })
+ expect(db.collections.profiles.get(other.id)).toMatchObject({ name: "Current Other", avatar: expected, avatarVersion: expectedVersion })
+})
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 16afdfa48..53c9f608c 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -1,3 +1,11 @@
+import type { CommunityApiError } from "@/lib/errors"
+import { readForumSidebarWindowResult } from "@/lib/community/forum-sidebar-window"
+import { ZodError } from "zod"
+import { requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
+import type { DM } from "@/lib/community/models/people"
+import { parseCommunityDmsRead, CommunityResourceBundleSchema, type CommunityResourceBundle } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { ServerDirectorySnapshotSchema, recordServerDirectoryWindow, reconcileExistingServerDirectoryWindows, type ServerDirectorySnapshot } from "@/lib/community/server-directory-window"
import { serverRailTopOrder } from "@alook/shared"
import type { Transaction } from "@tanstack/react-db"
import { communityRequestOptions as qualifiedCommunityRequestOptions } from "@/lib/community/account-cache-lifecycle"
@@ -8,29 +16,13 @@ import { getCommunityRuntime, readCurrentCommunityChannelMeta } from "@/stores/c
import { notifyManager,type QueryClient } from "@tanstack/react-query"
import { createStore } from "@tanstack/store"
import type { Query } from "@tanstack/react-query"
-import {
-UNCATEGORIZED_CATEGORY_ID,
-FORUM_ARCHIVE_TAG,
-normalizeCommunityChannelIdentity,
-normalizeCommunityChannelResourcePreview,
-CommunityChannelResourceSchema,
-CommunityMessageResourceSchema,
-CommunityResourceProfileSchema,
-type CommunityChannelIdentity,
-type CommunityMemberRelation,
-type CommunityResourceProfile,
-type CommunityMessageResource,
-type AccountAttentionSnapshot,
-type CommunityWsEvent,
-type CommunityContract,
-type ServerRailProjection,
-} from "@alook/shared"
+import { FORUM_ARCHIVE_TAG, CommunityChannelResourceSchema, AttentionIncludedSchema, CommunityMessageResourceSchema, CommunityMessageResourcesSchema, communityMessageProfileIds, CommunityResourceProfileSchema, CommunityMemberRelationSchema, type CommunityChannelResource, type CommunityMemberRelation, type CommunityResourceProfile, type CommunityMessageResource, type AccountAttentionSnapshot, type CommunityWsEvent, type CommunityContract, type ServerRailProjection } 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 { ServersResponse } from "@/hooks/community/use-servers"
import { applyMessageReaction, messageProfileIds, type Msg, type MessageInput } from "@/lib/community/models/message"
import type { NotificationSettings } from "@/hooks/community/use-notification-settings"
import { communityKeys } from "@/lib/query-keys"
@@ -45,7 +37,7 @@ import type { CommunityProfilePatch } from "@/lib/community/models/people"
import type { ChannelRefDirectory } from "@/lib/community/channel-ref"
-import { avatarInitial } from "@/lib/community/avatar"
+
import { canonicalUserImage } from "@/lib/community/storage"
import { projectCommunityMessageCreate } from "@/lib/community/message-wire"
import { clearTypingIndicator } from "@/hooks/community/community-ws/typing"
@@ -56,39 +48,11 @@ import {
getCommunityDbRegistry,
type CommunityDbRegistry,
} from "./collections"
-import {
-channelMembershipKey,
-canonicalChannelMembershipRow,
-channelMembershipSchema,
-channelLocalSchema,
-canonicalChannelRow,
-folderItemKey,
-messageSchema,
-notificationSettingKey,
-serverMembershipKey,
-serverSchema,
-communityCollectionSchemas,
-type CommunityCollectionRows,
-type CategoryRow,
-type AttentionItemRow,
-type AttentionScopeRow,
-type ChannelMembershipRow,
-type ChannelRow,
-type FolderItemRow,
-type FolderRow,
-type MessageRow,
-type ProfileRow,
-type FriendshipRow,
-type NotificationSettingRow,
-type ReadStateClockRow,
-type ReadStateRow,
-type ServerMembershipRow,
-type ServerRow,
-} from "./schema"
+import { channelMembershipKey, canonicalChannelMembershipRow, channelLocalSchema, canonicalChannelRow, folderItemKey, messageSchema, notificationSettingKey, serverMembershipKey, serverMembershipSchema, serverSchema, communityCollectionSchemas, type CommunityCollectionRows, type CategoryRow, type AttentionItemRow, type AttentionScopeRow, type ChannelMembershipRow, type ChannelRow, type FolderItemRow, type FolderRow, type MessageRow, type ProfileRow, type FriendshipRow, type NotificationSettingRow, type ReadStateClockRow, type ReadStateRow, type ServerMembershipRow, type ServerRow } from "./schema"
import type { z } from "zod"
-import { writeCommunityCollectionRows } from "./write"
+import { communityRowData, writeCommunityCollectionRows } from "./write"
import type { CommunityRestoredCollections } from "@/lib/query-persister"
-import type { CommunityThreadResources } from "@/hooks/community/forum-feed-window"
+import { normalizeThreadResources, type CommunityThreadResources } from "@/hooks/community/forum-feed-window"
type CollectionName = keyof CommunityDbRegistry["collections"]
type SnapshotIngestMode = "authoritative" | "merge"
@@ -112,9 +76,9 @@ type CanonicalWriteContext =
const canonicalRevisionStates = new WeakMap<QueryClient, ReturnType<typeof createStore<CanonicalRevisionState>>>()
const canonicalWriteContexts = new WeakMap<QueryClient, CanonicalWriteContext>()
-function writeCanonicalProfilePatches(registry: CommunityDbRegistry, patches: readonly CommunityProfilePatch[]) {
+function writeCanonicalProfilePatches(registry: CommunityDbRegistry, patches: readonly CommunityProfilePatch[], resourceSeed = false) {
const context = canonicalWriteContexts.get(registry.queryClient)
- return writeCommunityProfilePatches(patches, registry, context?.kind === "query" ? { snapshot: context.profileSnapshot } : { event: context?.kind === "event" })
+ return writeCommunityProfilePatches(patches, registry, context?.kind === "query" ? { snapshot: context.profileSnapshot } : { event: context?.kind === "event", resourceSeed })
}
function canonicalRevisionStore(queryClient: QueryClient) {
@@ -180,7 +144,7 @@ export function getCanonicalCommunityTypingMembership(
const serverPresence = serverId ? canonicalMembershipPresence(registry, "serverMemberships", serverMembershipKey(serverId, userId)) : undefined
const anchor = parentChannelId ? channels.find((row) => row.id === parentChannelId) : channel
const category = anchor?.categoryId ? collectionRows(registry, "categories").find((row) => row.id === anchor.categoryId && row.serverId === serverId) : undefined
- const publicAnchor = !!serverId && !!anchor && ((anchor.resourceComplete && anchor.categoryId === null) || category?.private === false)
+ const publicAnchor = !!serverId && !!anchor && (anchor.categoryId === null || category?.private === false)
const accessPresence = publicAnchor && serverPresence !== undefined ? serverPresence
: parentChannelId ? relationPresence(parentChannelId, "access") : relationPresence(channelId, "access")
const membership = channel?.type === "thread" || parentChannelId
@@ -344,7 +308,7 @@ function collectionRows<N extends CollectionName>(registry: CommunityDbRegistry,
const values = registry.queryClient.getQueryData<unknown[]>(communityKeys.communityDbCollection(registry.scopeId, name))
?? Array.from<unknown>(registry.collections[name].values())
return values.flatMap((row) => {
- const parsed = schema.safeParse(row)
+ const parsed = schema.safeParse(communityRowData(row))
return parsed.success ? [parsed.data] : []
})
}
@@ -368,7 +332,7 @@ function replaceRows<N extends CollectionName>(
}
const schema = collectionSchema(name)
const getKey = collectionKey(registry, name)
- const parsedIncoming = incoming.map((row) => schema.parse(row))
+ const parsedIncoming = incoming.map((row) => schema.parse(communityRowData(row)))
const current = collectionRows(registry, name)
const nextByKey = new Map(current.flatMap((row) => {
const key = getKey(row)
@@ -396,6 +360,7 @@ function replaceRows<N extends CollectionName>(
const next = [...nextByKey.values()]
writeCommunityCollectionRows(registry, name, next, getKey)
if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)
+ if (name === "channels" || name === "categories") reconcileExistingServerDirectoryWindows(registry)
recordEventWrites(registry, name, [
...current.filter(owns).map(getKey),
...parsedIncoming.map(getKey),
@@ -486,21 +451,6 @@ export async function restoreCommunityCollections(registry: CommunityDbRegistry,
assertCommunityLiveSnapshotTokenCurrent(client, token, undefined)
}
-function promoteServerDetailComplete(
- registry: CommunityDbRegistry,
- serverId: string,
-) {
- const current = collectionRows(registry, "servers")
- 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
- writeCommunityCollectionRows(registry, "servers", next, (row) => row.id)
-}
-
function patchRows<N extends CollectionName>(
registry: CommunityDbRegistry,
name: N,
@@ -525,6 +475,7 @@ function patchRows<N extends CollectionName>(
if (changed) {
writeCommunityCollectionRows(registry, name, next, getKey)
if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)
+ if (name === "channels" || name === "categories") reconcileExistingServerDirectoryWindows(registry)
}
if (eventKeys) {
recordEventPatches(registry, name, eventKeys, patch, new Set(changedKeys), eventFields)
@@ -551,6 +502,7 @@ function deleteRows<N extends CollectionName>(
})
writeCommunityCollectionRows(registry, name, next, getKey)
if (name === "attentionScopes" || name === "attentionItems") rebaseAttentionTransactions(registry)
+ if (name === "channels" || name === "categories") reconcileExistingServerDirectoryWindows(registry)
if (eventKeys) recordEventDeletes(registry, name, eventKeys)
else recordEventWrites(registry, name, removedKeys)
if (name === "channelMemberships" || name === "serverMemberships") pruneCanonicalTypingMembership(registry)
@@ -676,7 +628,7 @@ function clearChannelTransientState(
if (remembered && channelIds.has(remembered)) clearLastChannel(serverId)
} else {
const remembered = getLastMeLeaf()
- if (remembered && channelIds.has(remembered)) clearLastMeLocation()
+ if (remembered && channelIds.has(remembered) && registry.runtime.ws.get().channelAccessScopes.get(remembered)?.denialCode !== "blocked") clearLastMeLocation()
}
let viewCurrent = true
try { options?.assertView?.() } catch { viewCurrent = false }
@@ -716,35 +668,18 @@ export function ingestServers(
response: ServersResponse,
) {
const currentServers = collectionRows(registry, "servers")
- 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,
-
- detailComplete: existingById.get(server.id)?.detailComplete ?? false,
+ const servers: ServerRow[] = response.servers.map((server, position) => serverSchema.parse({
+ id: server.id, position, name: server.name, discriminator: server.discriminator,
+ description: server.description, ownerId: server.ownerId, icon: server.icon, official: server.official, isOwner: server.isOwner,
}))
const viewerId = registry.accountId
- const memberships: ServerMembershipRow[] = viewerId
- ? response.servers.map((server) => ({
- id: serverMembershipKey(server.id, viewerId),
- serverId: server.id,
- userId: viewerId,
- role: server.role ?? (server.isOwner ? "owner" : "member"),
- ...(server.memberId ? { memberId: server.memberId } : {}),
- viewer: true,
- }))
- : []
+ const memberships: ServerMembershipRow[] = viewerId ? response.servers.map(server => serverMembershipSchema.parse({
+ id: serverMembershipKey(server.id, viewerId), serverId: server.id, userId: viewerId, memberId: server.memberId, role: server.role, viewer: true,
+ })) : []
notifyManager.batch(() => {
for (const serverId of removedServerIds) if (!isOwnerServerDeleteScopeEvictionBlocked(registry.queryClient, serverId)) purgeCommunityServer(registry, serverId)
replaceRows(registry, "servers", servers, (row) => !isOwnerServerDeleteScopeEvictionBlocked(registry.queryClient, row.id))
@@ -761,105 +696,23 @@ export function ingestServers(
export function ingestServerDetail(
registry: CommunityDbRegistry,
- detail: ServerDetail,
+ input: ServerDirectorySnapshot,
) {
- const existing = collectionRows(registry, "servers")
- .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,
-
- 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) => {
- const previous = registry.collections.channels.get(channel.id)
- const complete = "resourceComplete" in channel && channel.resourceComplete === true
- const resource = complete ? CommunityChannelResourceSchema.strip().parse(channel)
- : normalizeCommunityChannelResourcePreview(channel)
- if (resource.serverId !== undefined && resource.serverId !== detail.id) throw new Error("Channel resource scope mismatch")
- channels.push(canonicalChannelRow({
- ...resource,
- id: channel.id,
- serverId: detail.id,
- categoryId: uncategorized ? null : category.id,
- name: channel.name,
- type: channel.type ?? previous?.type ?? "text",
- parentChannelId: null,
- parentMessageId: null,
- creatorId: channel.creatorId,
- position: resource.position ?? channelIndex,
- archived: resource.archived ?? previous?.archived ?? false,
- muted: channel.muted === true,
- tags: channel.tags ?? [],
- pending: channel.pending === true,
- resourceComplete: complete,
- }, previous))
- })
- })
- const currentTopLevelIds = new Set(
- collectionRows(registry, "channels")
- .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) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "inherited" })))
- : []
- const authoritativeTopLevelIds = new Set([...currentTopLevelIds, ...incomingTopLevelIds])
+ const detail = ServerDirectorySnapshotSchema.parse(input)
+ const serverId = detail.server.id
+ if (detail.categories.some(row => row.serverId !== serverId)
+ || detail.channels.some(row => row.serverId !== serverId || row.parentChannelId !== null
+ || row.categoryId !== null && !detail.categories.some(category => category.id === row.categoryId))) throw new Error("Directory resource scope mismatch")
+ const categories = detail.categories.map(row => ({ ...row, pending: false }))
+ const channels = detail.channels.map(row => canonicalChannelRow({ ...row, pending: false }, registry.collections.channels.get(row.id)))
+ const previousIds = collectionRows(registry, "channels").filter(row => row.serverId === serverId && row.parentChannelId === null).map(row => row.id)
+ const nextIds = new Set(channels.map(row => row.id))
notifyManager.batch(() => {
- for (const channelId of removedTopLevelIds) purgeCommunityChannel(registry, channelId)
- upsertRows(registry, "servers", [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)
- replaceRows(
- registry,
- "categories",
- categories,
- (row) => row.serverId === detail.id,
- )
- replaceRows(
- registry,
- "channels",
- channels,
- (row) => row.serverId === detail.id && row.type !== "thread",
- )
- if (viewerId) {
- replaceRows(
- registry,
- "channelMemberships",
- accessMemberships,
- (row) => row.userId === viewerId
- && row.relation === "access"
- && authoritativeTopLevelIds.has(row.channelId),
- )
- }
+ for (const id of previousIds) if (!nextIds.has(id)) purgeCommunityChannel(registry, id)
+ upsertRows(registry, "servers", [detail.server])
+ replaceRows(registry, "categories", categories, row => row.serverId === serverId)
+ replaceRows(registry, "channels", channels, row => row.serverId === serverId && row.parentChannelId === null)
+ recordServerDirectoryWindow(registry, serverId)
})
}
@@ -868,11 +721,18 @@ function ingestChannelMetadata(
input: unknown,
proof?: CommunityFreshQueryProof,
) {
- const full = typeof input === "object" && input !== null && "resourceComplete" in input && input.resourceComplete === true
- const metadata = full ? CommunityChannelResourceSchema.strip().parse(input) : normalizeCommunityChannelIdentity(input)
- const hints = channelLocalSchema.pick({ openerSeq: true, openerUnread: true }).parse(input)
- const changes = { ...metadata, ...hints, ...(full ? { resourceComplete: true as const } : {}), pending: false }
+ const metadata = CommunityChannelResourceSchema.strip().parse(input)
+ const hints = channelLocalSchema.pick({ openerSeq: true, openerUnread: true }).strip().parse(input)
const existing = registry.collections.channels.get(metadata.id)
+ const sidebarKey = metadata.serverId ? communityKeys.forumSidebarThreads(metadata.serverId) : null
+ const sidebar = sidebarKey && !registry.queryClient.getQueryState(sidebarKey)?.isInvalidated
+ && readForumSidebarWindowResult(registry.queryClient.getQueryData(sidebarKey))
+ const openerArchived = sidebar && sidebar.window.accountId === registry.accountId && sidebar.window.serverId === metadata.serverId
+ && metadata.type === "thread" && metadata.parentChannelId !== null && sidebar.window.parents.includes(metadata.parentChannelId)
+ && sidebar.window.retained?.id === metadata.id && sidebar.window.retained.disposition === "opener-archived"
+ const changes = { ...metadata, ...hints, pending: false,
+ ...(openerArchived ? { tags: [...new Set([...(existing?.tags ?? []), FORUM_ARCHIVE_TAG])] } : {}),
+ }
if (proof && existing) {
publishConfirmedFields(registry.queryClient, "channels", metadata.id, changes, proof)
} else {
@@ -887,6 +747,7 @@ export function ingestDms(
) {
const viewerId = registry.accountId
if (!viewerId) return
+ response = parseCommunityDmsRead(response, viewerId)
const currentDmIds = new Set(
collectionRows(registry, "channels")
.filter((row) => row.type === "dm")
@@ -895,16 +756,17 @@ export function ingestDms(
const channels: ChannelRow[] = []
const memberships: ChannelMembershipRow[] = []
const profilePatches: CommunityProfilePatch[] = []
- for (const [position, dm] of response.conversations.entries()) {
- channels.push(canonicalChannelRow({
- id: dm.id, type: "dm", position,
- lastMessageAt: dm.activityAt ?? null, preview: dm.preview,
- }, registry.collections.channels.get(dm.id)))
- memberships.push(
- canonicalChannelMembershipRow(dm.id, viewerId, "access"),
- canonicalChannelMembershipRow(dm.id, dm.userId, "access"),
- )
- profilePatches.push(communityUserProfilePatch(dm.userId, dm, { legacyPresentation: true }))
+ for (const dm of response.conversations) {
+ const channel = CommunityChannelResourceSchema.parse(dm.channel)
+ const profile = CommunityResourceProfileSchema.parse(dm.profile)
+ if (channel.id !== dm.id || channel.type !== "dm" || profile.id !== dm.userId
+ || dm.memberships.length !== 2 || !dm.memberships.every(row => row.channelId === dm.id && row.relation === "access")
+ || !dm.memberships.some(row => row.userId === viewerId) || !dm.memberships.some(row => row.userId === dm.userId)) throw new Error("DM resource scope mismatch")
+ channels.push(canonicalChannelRow({ ...channel, preview: dm.preview }, registry.collections.channels.get(dm.id)))
+ memberships.push(...dm.memberships.map(row => canonicalChannelMembershipRow(row.channelId, row.userId, row.relation, {
+ source: row.source,
+ })))
+ profilePatches.push(communityUserProfilePatch(profile.id, profile))
}
const dmIds = new Set(channels.map((row) => row.id))
const authoritativeDmIds = new Set([...currentDmIds, ...dmIds])
@@ -939,12 +801,14 @@ export function ingestDms(
*/
export function publishCommunityDmSummary(
queryClient: QueryClient,
- dm: DmsResponse["conversations"][number],
+ dm: DM,
) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry) return "no-registry" as const
return withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
- ingestDms(registry, { conversations: [dm] }, "merge")
+ const previous = registry.collections.channels.get(dm.id)
+ if (!previous || previous.type !== "dm") return "missing-resource" as const
+ upsertRows(registry, "channels", [canonicalChannelRow({ ...previous, preview: dm.preview })])
return "published" as const
})
}
@@ -988,74 +852,79 @@ export function publishCommunityServerRailCommit(queryClient: QueryClient, proje
})
}
+function effectiveMessageResource(registry: CommunityDbRegistry, resource: CommunityMessageResource) {
+ const previous = registry.collections.messages.status === "ready" ? registry.collections.messages.get(resource.id)
+ : registry.queryClient.getQueryData<MessageRow[]>(communityKeys.communityDbCollection(registry.scopeId, "messages"))?.find(message => message.id === resource.id)
+ const retainReply = previous?.channelId === resource.channelId
+ && previous.authorId === resource.authorId && previous.clientNonce === resource.clientNonce
+ && previous.replyToId === resource.replyToId && resource.replyToId !== null && !("replyTo" in resource)
+ return messageSchema.parse({ ...resource, ...(retainReply && previous.replyTo ? { replyTo: previous.replyTo } : {}) })
+}
+
+export function getCanonicalCommunityMessageResources(queryClient: QueryClient, messages: readonly unknown[]) {
+ const registry = getCommunityDbRegistry(queryClient)
+ if (!registry) return
+ const parsed = CommunityMessageResourceSchema.strip().array().safeParse(messages)
+ if (!parsed.success) return
+ const currentProfiles = new Map(collectionRows(registry, "profiles").map(profile => [profile.id, profile]))
+ const profiles = communityMessageProfileIds(parsed.data).flatMap(id => {
+ const profile = CommunityResourceProfileSchema.strip().safeParse(currentProfiles.get(id))
+ return profile.success ? [profile.data] : []
+ })
+ const graph = CommunityMessageResourcesSchema.safeParse({ messages: parsed.data, profiles })
+ return graph.success ? graph.data : undefined
+}
+
+export function validateCommunityMessagePublication(registry: CommunityDbRegistry, messages: readonly unknown[], profiles: readonly CommunityResourceProfile[]) {
+ const graph = CommunityMessageResourcesSchema.parse({ messages, profiles })
+ const retained = graph.messages.map(message => effectiveMessageResource(registry, message))
+ const currentProfiles = new Map(collectionRows(registry, "profiles").map(profile => [profile.id, profile]))
+ const available = new Map(communityMessageProfileIds(retained).flatMap(id => {
+ const profile = CommunityResourceProfileSchema.strip().safeParse(currentProfiles.get(id))
+ return profile.success ? [[id, profile.data] as const] : []
+ }))
+ for (const profile of graph.profiles) available.set(profile.id, profile)
+ if (!CommunityMessageResourcesSchema.safeParse({ messages: retained, profiles: [...available.values()] }).success) throw new Error("Retained message profile resource missing")
+ return graph
+}
+
export function ingestMessages(
registry: CommunityDbRegistry,
channelId: string,
- messages: readonly MessageInput[],
+ messages: readonly unknown[],
+ profiles: readonly CommunityResourceProfile[] = [],
) {
- const previous = new Map(collectionRows(registry, "messages").map((message) => [message.id, message]))
- for (const message of messages) {
- if (message.id.startsWith("temp_") || message.failed === true) continue
- if (message.channelId !== undefined && message.channelId !== channelId) throw new Error("Message channel mismatch")
- if (message.resourceComplete === true) CommunityMessageResourceSchema.strip().parse(message)
- }
- const profileMessages: MessageInput[] = []
- const rows: MessageRow[] = messages
- .filter((message) => !message.id.startsWith("temp_") && !("failed" in message && message.failed === true))
- .map((message) => {
- const full = message.resourceComplete === true
- const { thread: incomingThread, clientNonce, ...incoming } = message
- const fields = Object.fromEntries(Object.entries(incoming).filter(([, value]) => value !== undefined))
- if (message.resourceComplete !== true && message.authorAvatar === avatarInitial(message.authorName ?? "")) delete fields.authorAvatar
- const existingMessage = previous.get(message.id)
- if (!full && existingMessage?.resourceComplete === true) delete fields.attachments
- let thread = incomingThread
- if (!full && incomingThread && existingMessage?.resourceComplete === true) {
- const known = existingMessage.thread?.id === incomingThread.id ? existingMessage.thread : undefined
- const fields = Object.fromEntries(Object.entries(incomingThread).filter(([, value]) => value !== undefined))
- const participants = incomingThread.participants?.map((participant) => ({
- ...known?.participants?.find((row) => row.id === participant.id),
- ...Object.fromEntries(Object.entries(participant).filter(([, value]) => value !== undefined)),
- }))
- const merged = { ...known, ...fields, ...(participants ? { participants } : {}) }
- const parsed = CommunityMessageResourceSchema.shape.thread.safeParse(merged)
- if (parsed.success) thread = parsed.data
- else {
- const { participants: _participants, ...withoutUnknownParticipants } = fields
- const partial = CommunityMessageResourceSchema.shape.thread.safeParse({ ...known, ...withoutUnknownParticipants })
- thread = partial.success ? partial.data : known
- }
- }
- const retainReply = existingMessage?.channelId === channelId
- && (!message.authorId || message.authorId === existingMessage.authorId)
- && (clientNonce === undefined || clientNonce === existingMessage.clientNonce)
- && !("replyTo" in message)
- && (!("replyToId" in message) || message.replyToId === existingMessage.replyToId)
- if (thread) {
- const existing = collectionRows(registry, "channels").find((row) => row.id === thread.id)
- const parent = collectionRows(registry, "channels").find((row) => row.id === channelId)
- upsertRows(registry, "channels", [canonicalChannelRow({
- id: thread.id, serverId: existing?.serverId ?? parent?.serverId, categoryId: null,
- name: thread.name, type: "thread", parentChannelId: channelId, parentMessageId: message.id,
- tags: thread.tags ?? existing?.tags ?? [], pending: false, messageCount: thread.messageCount,
- ...(thread.lastReplyAt !== undefined ? { lastMessageAt: thread.lastReplyAt } : {}),
- ...(thread.preview !== undefined ? { preview: thread.preview } : {}),
- ...(thread.participantCount !== undefined ? { participantCount: thread.participantCount } : {}),
- }, existing)])
- }
- profileMessages.push({ ...fields, id: message.id, type: message.type, ...(incomingThread ? { thread: incomingThread } : {}) })
- const merged = { ...existingMessage, ...fields,
- ...(thread ? { thread } : {}),
- replyTo: retainReply ? existingMessage!.replyTo : message.replyTo,
- replyToId: retainReply ? existingMessage!.replyToId : "replyToId" in message ? message.replyToId : message.replyTo?.id ?? (retainReply ? existingMessage?.replyToId : null),
- type: message.type ?? existingMessage?.type ?? "chat", channelId,
- ...(clientNonce !== undefined ? { clientNonce } : {}),
- resourceComplete: full || existingMessage?.resourceComplete === true,
- }
- return messageSchema.parse(merged)
+ const fullProfiles = new Map(profiles.map(profile => { const parsed = CommunityResourceProfileSchema.parse(profile); return [parsed.id, parsed] as const }))
+ const resources = messages.map(message => {
+ const resource = CommunityMessageResourceSchema.parse(message)
+ if (resource.channelId !== channelId) throw new Error("Message channel mismatch")
+ return resource
})
+ const rows = resources.map(resource => effectiveMessageResource(registry, resource))
upsertRows(registry, "messages", rows)
- writeCanonicalProfilePatches(registry, messageProfilePatches(profileMessages))
+ for (const resource of resources) {
+ const thread = resource.thread
+ const previous = thread && registry.collections.channels.get(thread.id)
+ if (!thread || !previous || !CommunityChannelResourceSchema.strip().safeParse(previous).success) continue
+ upsertRows(registry, "channels", [canonicalChannelRow({ ...previous,
+ name: thread.name, messageCount: thread.messageCount,
+ ...(thread.lastReplyAt === undefined ? {} : { lastMessageAt: thread.lastReplyAt }),
+ ...(thread.tags === undefined ? {} : { tags: thread.tags }),
+ ...(thread.preview === undefined ? {} : { preview: thread.preview }),
+ ...(thread.participantCount === undefined ? {} : { participantCount: thread.participantCount }),
+ })])
+ }
+ writeCanonicalProfilePatches(registry, messageProfilePatches(resources).filter(patch => {
+ const previous = registry.collections.profiles.get(patch.id)
+ return previous !== undefined && CommunityResourceProfileSchema.strip().safeParse(previous).success
+ }).map(patch => {
+ const full = fullProfiles.get(patch.id)
+ if (!full) return patch
+ const hints = { ...patch }
+ delete hints.identityAbout
+ if (hints.avatar && hints.avatar.avatarVersion <= full.avatarVersion) delete hints.avatar
+ return hints
+ }), canonicalWriteContexts.get(registry.queryClient)?.kind === "event")
}
export function ingestReadStateSnapshot(
@@ -1100,76 +969,34 @@ export function publishCommunityConversationReadState(
})
}
-function serverSummaryRows(registry: CommunityDbRegistry, summaries: readonly Pick<ServerRow, "id" | "name" | "discriminator">[]): ServerRow[] {
- const existingById = new Map(collectionRows(registry, "servers").map((row) => [row.id, row]))
- return summaries.map((server, position) => {
- const existing = existingById.get(server.id)
- return {
- description: "", ownerId: "", icon: null, official: false, isOwner: false,
- detailComplete: false, ...existing,
- id: server.id, position: existing?.position ?? position,
- name: server.name, discriminator: server.discriminator,
+export function publishCommunityResourceBundle(queryClient: QueryClient, resources: CommunityResourceBundle, proof: CommunityFreshQueryProof,
+ messageReferences?: readonly { id: string; channelId: string }[]) {
+ return withCommunityQueryProof(queryClient, proof, registry => {
+ const bundle = CommunityResourceBundleSchema.parse(resources)
+ if (messageReferences && (new Set(messageReferences.map(row => row.id)).size !== messageReferences.length
+ || bundle.messages.length !== messageReferences.length
+ || messageReferences.some(ref => !bundle.messages.some(message => message.id === ref.id && message.channelId === ref.channelId)))) {
+ throw new ZodError([{ code: "custom", path: ["messages"], message: "Message window resource closure mismatch" }])
}
+ return ingestCommunityResources(registry, bundle)
})
}
-function seedViewerServerMemberships(registry: CommunityDbRegistry, servers: readonly Pick<ServerRow, "id" | "isOwner">[]) {
- const viewerId = registry.accountId
- if (!viewerId) return
- const existingById = new Map(collectionRows(registry, "serverMemberships").map((row) => [row.id, row]))
- upsertRows(registry, "serverMemberships", servers.map((server) => {
- const id = serverMembershipKey(server.id, viewerId), existing = existingById.get(id)
- return { ...existing, id, serverId: server.id, userId: viewerId,
- role: existing?.role ?? (server.isOwner ? "owner" : "member"), viewer: true }
- }))
-}
-
-function ingestAttentionIncluded(
- registry: CommunityDbRegistry,
- included: Partial<AccountAttentionSnapshot["included"]> | undefined,
-) {
- const existingChannels = new Map(
- collectionRows(registry, "channels").map((row) => [row.id, row]),
- )
- const viewerId = registry.accountId
- const servers = serverSummaryRows(registry, included?.servers ?? [])
- upsertRows(registry, "servers", servers)
- for (const channel of included?.channels ?? []) ingestChannelMetadata(registry, channel)
- const dmChannels: ChannelRow[] = (included?.dms ?? []).map((dm, position) => {
- const existing = existingChannels.get(dm.id)
- return canonicalChannelRow({
- id: dm.id,
- type: "dm",
- position: existing?.position ?? position,
- muted: existing?.muted ?? false,
-
- lastMessageAt: dm.lastMessageAt,
- preview: existing?.preview ?? "",
- }, existing)
- })
- upsertRows(registry, "channels", dmChannels)
- if (viewerId) {
- seedViewerServerMemberships(registry, servers)
- upsertRows(
- registry,
- "channelMemberships",
- [
- ...(included?.channels ?? []).map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "inherited" as const }))),
- ...(included?.dms ?? []).flatMap((dm) => [canonicalChannelMembershipRow(dm.id, viewerId, "access"), canonicalChannelMembershipRow(dm.id, dm.userId, "access")]),
- ],
- )
- }
- const profiles = CommunityResourceProfileSchema.array().safeParse((included?.profiles ?? []).map(({ userId, ...profile }) => ({
- ...profile, id: userId, discriminator: profile.discriminator || null, avatar: canonicalUserImage(userId, profile.avatar, profile.avatarVersion),
+function ingestCommunityResources(registry: CommunityDbRegistry, input: CommunityResourceBundle) {
+ const resources = CommunityResourceBundleSchema.parse(input)
+ if (resources.viewerId !== registry.accountId) throw new Error("Attention account mismatch")
+ validateCommunityMessagePublication(registry, resources.messages, resources.profiles)
+ for (const server of resources.servers) registry.runtime.ws.actions.grantServerAccess(server.id)
+ for (const channel of resources.channels) registry.runtime.ws.actions.rememberChannelAccess(channel.serverId, channel.id, channel.parentChannelId ?? undefined)
+ upsertRows(registry, "servers", resources.servers)
+ upsertRows(registry, "serverMemberships", resources.serverMemberships.map(row => ({
+ ...registry.collections.serverMemberships.get(serverMembershipKey(row.serverId, row.userId)),
+ ...row, id: serverMembershipKey(row.serverId, row.userId), viewer: true,
})))
- if (profiles.success) {
- writeCanonicalProfilePatches(registry, profiles.data.map((profile) => (
- communityUserProfilePatch(profile.id, profile, { legacyPresentation: true })
- )))
- }
- const byChannel = new Map<string, MessageInput[]>()
- for (const message of included?.messages ?? []) byChannel.set(message.channelId, [...(byChannel.get(message.channelId) ?? []), { ...message, resourceComplete: false }])
- for (const [channelId, messages] of byChannel) ingestMessages(registry, channelId, messages)
+ upsertRows(registry, "channels", resources.channels.map(row => canonicalChannelRow(row, registry.collections.channels.get(row.id))))
+ upsertRows(registry, "channelMemberships", resources.memberships.map(row => canonicalChannelMembershipRow(row.channelId, row.userId, row.relation, { source: row.source })))
+ writeCanonicalProfilePatches(registry, resources.profiles.map(row => communityUserProfilePatch(row.id, row)))
+ for (const channel of resources.channels) ingestMessages(registry, channel.id, resources.messages.filter(row => row.channelId === channel.id), resources.profiles)
}
export type AttentionDomain = "channels" | "dms" | "mentions"
@@ -1528,10 +1355,25 @@ export function hasAttentionScopeOptimisticFence(queryClient: QueryClient, scope
}
export function ingestAttentionSnapshot(registry: CommunityDbRegistry, snapshot: AccountAttentionSnapshot) {
+ const included = AttentionIncludedSchema.parse(snapshot.included)
+ const resources = CommunityResourceBundleSchema.parse(snapshot.resources)
+ const channels = new Map(resources.channels.map(channel => [channel.id, channel]))
+ if (included.dms.some(dm => channels.get(dm.id)?.type !== "dm" || dm.userId === resources.viewerId || !resources.profiles.some(profile => profile.id === dm.userId))
+ || included.channels.some(summary => {
+ const channel = channels.get(summary.id)
+ return !channel || channel.serverId !== summary.serverId || channel.type !== summary.type
+ || channel.parentChannelId !== summary.parentChannelId || channel.parentMessageId !== summary.parentMessageId
+ })) throw new Error("Attention presentation resource mismatch")
+ const openerHints = new Map(included.channels.flatMap(channel => channel.openerSeq === undefined && channel.openerUnread === undefined ? [] : [[channel.id, {
+ ...(channel.openerSeq === undefined ? {} : { openerSeq: channel.openerSeq }),
+ ...(channel.openerUnread === undefined ? {} : { openerUnread: channel.openerUnread }),
+ }] as const]))
notifyManager.batch(() => {
const pending = collectionRows(registry, "friendships").filter((row) => row.kind === "incoming" && row.needsOwnerApproval == null)
const blocked = new Set(collectionRows(registry, "friendships").filter((row) => row.kind === "blocked").map((row) => row.userId))
- ingestAttentionIncluded(registry, snapshot.included)
+ ingestCommunityResources(registry, resources)
+ upsertRows(registry, "channelMemberships", included.dms.map(dm => canonicalChannelMembershipRow(dm.id, dm.userId, "access", { source: "added" })))
+ patchRows(registry, "channels", row => ({ ...row, ...openerHints.get(row.id) }), row => openerHints.has(row.id))
const confirmed = confirmedAttentionProjection(registry, snapshot.scopes, snapshot.items)
replaceRows(registry, "attentionScopes", confirmed.scopes, () => true)
replaceRows(registry, "attentionItems", confirmed.items.filter((row) => row.kind !== "friend_request" || !row.actorUserId || (!blocked.has(row.actorUserId) && !isProtectedFromQueryWrite(registry, "friendships", `user:${row.actorUserId}`))), () => true)
@@ -1628,7 +1470,7 @@ function ingestNotificationSettings(
export type CommunityLiveSnapshot =
| { kind: "servers"; data: ServersResponse }
- | { kind: "server-detail"; data: ServerDetail }
+ | { kind: "server-detail"; data: ServerDirectorySnapshot }
| { kind: "folders"; data: FoldersResponse }
| { kind: "dms"; data: DmsResponse }
| { kind: "read-state"; data: AccountReadStateSnapshot }
@@ -1691,18 +1533,24 @@ export function publishCommunityMembersSnapshot(queryClient: QueryClient, server
function withCommunityQueryProof<T>(queryClient: QueryClient, proof: CommunityFreshQueryProof, publish: (registry: CommunityDbRegistry) => T): T {
assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)
+ try {
return withCanonicalWriteContext(queryClient, { kind: "query", requestRevision: proof.token.canonicalRevision, profileSnapshot: proof.token.profileSnapshot }, () => publish(proof.token.registry!))
+ } catch (error) { if (error instanceof ZodError) throw requestBusinessSchemaUpdate(); throw error }
}
-function ingestResourceProfiles(registry: CommunityDbRegistry, profiles: readonly (Pick<CommunityResourceProfile, "id"> & Partial<Omit<CommunityResourceProfile, "id">>)[], proof: CommunityFreshQueryProof, options?: { legacyPresentation: boolean }) {
- writeCommunityProfilePatches(profiles.map((profile) => communityUserProfilePatch(profile.id, profile, options)), registry, { snapshot: proof.token.profileSnapshot })
+function ingestResourceProfiles(registry: CommunityDbRegistry, profiles: readonly CommunityResourceProfile[], proof: CommunityFreshQueryProof) {
+ const resources = profiles.map(profile => CommunityResourceProfileSchema.parse(profile))
+ writeCommunityProfilePatches(resources.map((profile) => communityUserProfilePatch(profile.id, profile)), registry, { snapshot: proof.token.profileSnapshot })
}
-export function publishCommunityChannelMembersSnapshot(queryClient: QueryClient, serverId: string | null, channelId: string, relation: CommunityMemberRelation["relation"], members: readonly CommunityMemberRelation[], proof: CommunityFreshQueryProof, profiles: readonly CommunityResourceProfile[] = [], options?: { legacyPresentation: boolean }) {
- if (serverId) publishCommunityMembersSnapshot(queryClient, serverId, members.flatMap((member) => member.role === null || member.memberId === null ? [] : [{ ...member, id: member.memberId, role: member.role }]), proof)
+export function publishCommunityChannelMembersSnapshot(queryClient: QueryClient, serverId: string | null, channelId: string, relation: CommunityMemberRelation["relation"], members: readonly CommunityMemberRelation[], proof: CommunityFreshQueryProof, profiles: readonly CommunityResourceProfile[] = []) {
return withCommunityQueryProof(queryClient, proof, (registry) => {
- ingestResourceProfiles(registry, profiles, proof, options)
- replaceRows(registry, "channelMemberships", members.map((member) => channelMembershipSchema.parse({ ...member, id: channelMembershipKey(channelId, member.userId, relation), memberId: member.memberId ?? undefined })), (row) => row.channelId === channelId && row.relation === relation)
+ const fullProfiles = profiles.map(profile => CommunityResourceProfileSchema.parse(profile))
+ const relations = members.map(member => CommunityMemberRelationSchema.parse(member))
+ if (relations.some(member => member.channelId !== channelId || member.relation !== relation)) throw new Error("Member resource scope mismatch")
+ if (serverId) publishCommunityMembersSnapshot(queryClient, serverId, relations.flatMap((member) => member.role === null || member.memberId === null ? [] : [{ ...member, id: member.memberId, role: member.role }]), proof)
+ ingestResourceProfiles(registry, fullProfiles, proof)
+ replaceRows(registry, "channelMemberships", relations.map((member) => canonicalChannelMembershipRow(channelId, member.userId, relation, { source: member.source })), (row) => row.channelId === channelId && row.relation === relation)
pruneCanonicalTypingMembership(registry, { channelId, relation })
})
}
@@ -1735,7 +1583,7 @@ export function captureCommunityLiveSnapshotToken(
const parentChannelId = row?.parentChannelId ?? scope?.parentChannelId
const lineageKnown = !!row && (row.type !== "thread" || !!parentChannelId) || scope?.serverId === null || !!parentChannelId
return {
- channelLineage: lineageKnown ? { parentChannelId } : undefined,
+ channelLineage: lineageKnown ? { parentChannelId: parentChannelId ?? null } : undefined,
viewerId: state.profileViewerId,
accountEpoch: state.profileAccountEpoch,
accessEpoch: state.accessEpoch,
@@ -1842,11 +1690,18 @@ export function publishCommunityMessages(
publication: {
channelId: string
messages: MessageInput[]
+ profiles: readonly CommunityResourceProfile[]
proof: CommunityFreshQueryProof
},
) {
return withCommunityQueryProof(queryClient, publication.proof, (registry) => {
- ingestMessages(registry, publication.channelId, publication.messages)
+ const graph = validateCommunityMessagePublication(registry, publication.messages, publication.profiles)
+ if (graph.messages.some(message => message.channelId !== publication.channelId)) throw new Error("Message channel mismatch")
+ notifyManager.batch(() => {
+ ingestResourceProfiles(registry, graph.profiles, publication.proof)
+ if (!getCanonicalCommunityMessageResources(queryClient, graph.messages.map(message => effectiveMessageResource(registry, message)))) throw new Error("Message profile publication incomplete")
+ ingestMessages(registry, publication.channelId, graph.messages, graph.profiles)
+ })
return "published" as const
})
}
@@ -1856,17 +1711,22 @@ export function publishCommunityEmbeddedMessages(
queryClient: QueryClient,
publication: {
entries: Array<{ channelId: string; message: MessageInput | CommunityMessageResource }>
+ profiles: readonly CommunityResourceProfile[]
proof: CommunityFreshQueryProof
},
) {
return withCommunityQueryProof(queryClient, publication.proof, (registry) => {
+ const graph = validateCommunityMessagePublication(registry, publication.entries.map(entry => entry.message), publication.profiles)
+ if (publication.entries.some(entry => entry.channelId !== entry.message.channelId)) throw new Error("Message channel mismatch")
const byChannel = new Map<string, Array<MessageInput | CommunityMessageResource>>()
for (const { channelId, message } of publication.entries) {
byChannel.set(channelId, [...(byChannel.get(channelId) ?? []), message])
}
notifyManager.batch(() => {
+ ingestResourceProfiles(registry, graph.profiles, publication.proof)
+ if (!getCanonicalCommunityMessageResources(queryClient, graph.messages.map(message => effectiveMessageResource(registry, message)))) throw new Error("Message profile publication incomplete")
for (const [channelId, messages] of byChannel) {
- ingestMessages(registry, channelId, messages)
+ ingestMessages(registry, channelId, messages, graph.profiles)
}
})
return "published" as const
@@ -1897,7 +1757,7 @@ export function confirmCommunityConversationPresence(queryClient: QueryClient, c
export function publishCommunityChannelMetadata(
queryClient: QueryClient,
publication: {
- metadata: CommunityChannelIdentity & { resourceComplete?: boolean }
+ metadata: CommunityChannelResource
proof: CommunityFreshQueryProof
},
) {
@@ -1920,60 +1780,27 @@ export function publishCommunityChannelDirectory(
queryClient: QueryClient,
publication: {
directory: ChannelRefDirectory
+ resources: CommunityResourceBundle
proof: CommunityFreshQueryProof
},
) {
return withCommunityQueryProof(queryClient, publication.proof, (registry) => {
- const existingChannels = new Map(
- collectionRows(registry, "channels").map((row) => [row.id, row]),
- )
- const viewerId = registry.accountId
- const servers = serverSummaryRows(registry, publication.directory)
- 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 [canonicalChannelRow({
- id: channel.id, serverId: server.id, name: channel.name, type,
- parentChannelId: null, parentMessageId: null, position: existing?.position ?? position,
- }, existing)]
- })
- ))
- notifyManager.batch(() => {
- upsertRows(registry, "servers", servers)
- upsertRows(registry, "channels", channels)
- if (viewerId) {
- seedViewerServerMemberships(registry, servers)
- upsertRows(
- registry,
- "channelMemberships",
- channels.map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "inherited" as const }))),
- )
- }
- })
+ if (publication.directory.some(server => !publication.resources.servers.some(row => row.id === server.id)
+ || server.channels.some(channel => !publication.resources.channels.some(row => row.id === channel.id && row.serverId === server.id)))) throw new Error("Channel directory resource closure mismatch")
+ ingestCommunityResources(registry, publication.resources)
return "published" as const
})
}
-export type CommunityForumSidebarChannel = Pick<CommunityChannelIdentity, "id" | "parentChannelId" | "parentMessageId"> & Partial<Pick<CommunityChannelIdentity, "creatorId" | "lastMessageAt">> & {
- name: NonNullable<CommunityChannelIdentity["name"]>
- serverId?: NonNullable<CommunityChannelIdentity["serverId"]>
- type?: string
- archived?: CommunityChannelIdentity["archived"] | number
- activityAt: string
- unread: boolean
- participating?: boolean
-}
-
-export type CommunityForumSidebarOpener = Pick<CommunityMessageResource, "id" | "content"> & Partial<Pick<CommunityMessageResource, "seq" | "channelId" | "type">>
+export type CommunityForumSidebarChannel = CommunityChannelResource & { activityAt: string; unread: boolean; participating: boolean }
+export type CommunityForumSidebarOpener = CommunityMessageResource
/** Publish the service facts carried by one forum-sidebar response. */
export function publishCommunityForumSidebar(
queryClient: QueryClient,
publication: {
serverId: string
+ resources: CommunityResourceBundle
channels: CommunityForumSidebarChannel[]
openers: CommunityForumSidebarOpener[]
negativeRetain?: {
@@ -1984,70 +1811,18 @@ export function publishCommunityForumSidebar(
},
) {
return withCommunityQueryProof(queryClient, publication.proof, (registry) => {
- const existingById = new Map(
- collectionRows(registry, "channels").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 [canonicalChannelRow({
- id: channel.id,
- serverId: channel.serverId ?? publication.serverId,
- name: channel.name,
- type: "thread" as const,
- parentChannelId: channel.parentChannelId,
- parentMessageId: channel.parentMessageId,
- creatorId: channel.creatorId ?? existing?.creatorId ?? null,
- archived: channel.archived === true || channel.archived === 1,
-
- lastMessageAt: channel.lastMessageAt ?? channel.activityAt,
- }, existing)]
- })
- const viewerId = registry.accountId
- notifyManager.batch(() => {
- upsertRows(registry, "channels", channels)
+ if (publication.channels.some(channel => channel.serverId !== publication.serverId || channel.type !== "thread"
+ || !publication.resources.channels.some(row => row.id === channel.id && row.parentChannelId === channel.parentChannelId && row.parentMessageId === channel.parentMessageId))) throw new Error("Forum sidebar scope mismatch")
+ ingestCommunityResources(registry, publication.resources)
+ const viewerId = registry.accountId
for (const channel of publication.channels) {
- if (channel.participating === false || channel.archived === true || channel.archived === 1) continue
- const current = collectionRows(registry, "channels")
- .find((row) => row.id === channel.id && row.serverId === publication.serverId && row.type === "thread")
- if (current?.tags.includes(FORUM_ARCHIVE_TAG)) {
- publishConfirmedFields(queryClient, "channels", channel.id, {
- tags: current.tags.filter((tag) => tag !== FORUM_ARCHIVE_TAG),
- }, publication.proof)
- }
- }
- if (viewerId) {
- upsertRows(
- registry,
- "channelMemberships",
- channels.map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "explicit" as const }))),
- )
- const participating = publication.channels
- .filter((channel) => channel.participating !== false)
- .map((channel) => channel.id)
- upsertRows(
- registry,
- "channelMemberships",
- participating.map((channelId) => (canonicalChannelMembershipRow(channelId, viewerId, "notify", { 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 (!channel.participating || channel.archived) continue
+ const current = registry.collections.channels.get(channel.id)
+ if (current?.tags.includes(FORUM_ARCHIVE_TAG)) publishConfirmedFields(queryClient, "channels", channel.id, { tags: current.tags.filter(tag => tag !== FORUM_ARCHIVE_TAG) }, publication.proof)
}
if (publication.negativeRetain) {
const { id, disposition } = publication.negativeRetain
if (disposition === "opener-archived") {
- const current = collectionRows(registry, "channels")
- .find((row) => row.id === id)
- if (!current) {
- upsertRows(registry, "channels", [canonicalChannelRow({ id, serverId: publication.serverId, type: "thread", pending: true })])
- }
const target = collectionRows(registry, "channels")
.find((row) => row.id === id && row.serverId === publication.serverId && row.type === "thread")
if (target && !target.tags.includes(FORUM_ARCHIVE_TAG)) {
@@ -2066,7 +1841,6 @@ export function publishCommunityForumSidebar(
retireCommunityNotificationScope(registry, id)
}
- })
return "published" as const
})
}
@@ -2188,8 +1962,11 @@ export function publishCommunityMessageReaction(queryClient: QueryClient, messag
}), (row) => row.id === messageId, [messageId], ["reactions", field]))
}
-export function publishCommunityForumFeed(queryClient: QueryClient, forumChannelId: string, page: CommunityThreadResources, proof: CommunityFreshQueryProof) {
+export function publishCommunityForumFeed(queryClient: QueryClient, forumChannelId: string, input: CommunityThreadResources, proof: CommunityFreshQueryProof) {
return withCommunityQueryProof(queryClient, proof, (registry) => notifyManager.batch(() => {
+ const { previews: _previews, ...included } = input.included
+ const page = normalizeThreadResources(forumChannelId, { ...input, included })
+ validateCommunityMessagePublication(registry, page.included.messages, page.included.profiles)
const rows = page.threads.map((thread) => {
const first = page.included.previews.find((message) => message.channelId === thread.id)
return canonicalChannelRow({
@@ -2203,8 +1980,9 @@ export function publishCommunityForumFeed(queryClient: QueryClient, forumChannel
})
upsertRows(registry, "channels", rows)
ingestResourceProfiles(registry, page.included.profiles, proof)
- publishCommunityEmbeddedMessages(queryClient, { entries: page.included.messages.map((message) => ({ channelId: message.channelId, message })), proof })
- upsertRows(registry, "channelMemberships", page.included.members.map((member) => channelMembershipSchema.parse({ ...member, id: channelMembershipKey(member.channelId, member.userId, member.relation) })))
+ publishCommunityEmbeddedMessages(queryClient, { entries: page.included.messages.map((message) => ({ channelId: message.channelId, message })), profiles: page.included.profiles, proof })
+ if (page.channel.serverId) publishCommunityMembersSnapshot(queryClient, page.channel.serverId, page.included.members.flatMap(member => member.memberId === null || member.role === null ? [] : [{ id: member.memberId, userId: member.userId, role: member.role }]), proof)
+ upsertRows(registry, "channelMemberships", page.included.members.map((member) => canonicalChannelMembershipRow(member.channelId, member.userId, member.relation, { source: member.source })))
}))
}
@@ -2271,7 +2049,7 @@ export function applyCommunityDmBlockAccess(registry: CommunityDbRegistry, peerU
.map((row) => row.id))
withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => notifyManager.batch(() => {
for (const id of ids) {
- if (blocked) retireCommunityChannelReading(registry, id, { reason: "read-denied", serverId: null })
+ if (blocked) retireCommunityChannelReading(registry, id, { reason: "read-denied", serverId: null, denialCode: "blocked" })
else registry.runtime.ws.actions.beginChannelMembershipChange(null, id)
}
}))
@@ -2526,13 +2304,16 @@ export function collectChannelScopeIds(
export function retireCommunityChannelReading(
registry: CommunityDbRegistry,
channelId: string,
- options: { reason: "read-denied" | "resource-deleted"; serverId?: string | null; preserveQuery?: Query; queries?: ReadonlySet<Query>; assertView?: () => void; clearTransient?: boolean },
+ options: { reason: "read-denied" | "resource-deleted"; denialCode?: CommunityApiError["code"]; serverId?: string | null; preserveQuery?: Query; queries?: ReadonlySet<Query>; assertView?: () => void; clearTransient?: boolean },
) {
const root = registry.collections.channels.get(channelId)
const serverId = options.serverId === undefined ? root?.serverId ?? null : options.serverId
const removed = collectChannelScopeIds(registry.queryClient, serverId, channelId)
- for (const id of registry.runtime.ws.actions.revokeChannelAccess(serverId, channelId)) removed.add(id)
- for (const id of removed) if (!registry.runtime.ws.actions.isChannelAccessRevoked(id, serverId)) registry.runtime.ws.actions.revokeChannelAccess(serverId, id)
+ const revoke = (id: string) => options.denialCode === undefined
+ ? registry.runtime.ws.actions.revokeChannelAccess(serverId, id)
+ : registry.runtime.ws.actions.revokeChannelAccess(serverId, id, options.denialCode)
+ for (const id of revoke(channelId)) removed.add(id)
+ for (const id of removed) if (!registry.runtime.ws.actions.isChannelAccessRevoked(id, serverId)) revoke(id)
void registry.retireReadingDisk(removed, options.reason === "resource-deleted")
.catch((error: unknown) => console.error("Channel cache retirement failed", error))
if (options.clearTransient !== false) clearChannelTransientState(registry, removed, serverId, options.preserveQuery, options)
@@ -2591,7 +2372,7 @@ function projectProfilePatch(
export function projectCommunityWsEventToDb(
queryClient: QueryClient,
event: CommunityWsEvent,
- contract: CommunityContract = 2,
+ contract: CommunityContract = BUSINESS_SCHEMA_VERSION,
) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry) return
@@ -2627,7 +2408,11 @@ export function projectCommunityWsEventToDb(
}
case "community:message.create": {
const projected = projectCommunityMessageCreate(event.message, event.channelId, contract)
- ingestMessages(registry, event.channelId, [projected])
+ const graph = validateCommunityMessagePublication(registry, [projected], event.profiles)
+ notifyManager.batch(() => {
+ writeCanonicalProfilePatches(registry, graph.profiles.map(profile => communityUserProfilePatch(profile.id, profile)), true)
+ ingestMessages(registry, event.channelId, graph.messages, graph.profiles)
+ })
if (event.message.createdAt) {
patchRows(
registry,
@@ -2666,24 +2451,12 @@ export function projectCommunityWsEventToDb(
)
return
case "community:channel.child_create": {
- const full = contract === 3 ? CommunityChannelResourceSchema.parse(event.channel) : null
- if (!full && !event.parentMessageId) return
- const parent = collectionRows(registry, "channels")
- .find((row) => row.id === event.parentChannelId)
+ const full = CommunityChannelResourceSchema.parse(event.channel)
+ const parent = collectionRows(registry, "channels").find(row => row.id === event.parentChannelId)
if (!parent?.serverId) return
- if (full && full.serverId !== parent.serverId) throw new Error("Child channel server mismatch")
- const existing = collectionRows(registry, "channels").find((row) => row.id === event.channel.id)
- const changes = full ? { ...full, resourceComplete: true as const } : {
- id: event.channel.id,
- serverId: parent.serverId,
- name: event.channel.name,
- type: "thread" as const,
- parentChannelId: event.parentChannelId,
- parentMessageId: event.parentMessageId,
- ...(event.channel.creatorId === undefined ? {} : { creatorId: event.channel.creatorId }),
- createdAt: event.channel.createdAt,
- }
- upsertRows(registry, "channels", [canonicalChannelRow(changes, existing)], full ? undefined : Object.keys(changes))
+ if (full.serverId !== parent.serverId || full.parentChannelId !== parent.id || full.parentMessageId !== event.parentMessageId) throw new Error("Child channel scope mismatch")
+ const existing = collectionRows(registry, "channels").find(row => row.id === full.id)
+ upsertRows(registry, "channels", [canonicalChannelRow(full, existing)])
if (registry.accountId) {
upsertRows(
registry,
@@ -2722,16 +2495,9 @@ export function projectCommunityWsEventToDb(
return
case "community:channel.create": {
const existing = collectionRows(registry, "channels").find((row) => row.id === event.channel.id)
- const full = contract === 3 ? CommunityChannelResourceSchema.parse(event.channel) : null
- upsertRows(registry, "channels", [canonicalChannelRow(full ? { ...full, resourceComplete: true } : {
- id: event.channel.id,
- serverId: event.serverId,
- categoryId: event.channel.categoryId ?? null,
- name: event.channel.name,
- type: event.channel.type,
- position: event.channel.position,
- createdAt: event.channel.createdAt,
- }, existing)])
+ const full = CommunityChannelResourceSchema.parse(event.channel)
+ if (full.serverId !== event.serverId) throw new Error("Channel server mismatch")
+ upsertRows(registry, "channels", [canonicalChannelRow(full, existing)])
return
}
case "community:channel.update":
@@ -2762,8 +2528,6 @@ export function projectCommunityWsEventToDb(
return
}
case "community:channel.membership.change":
- case "community:channel.member_add":
- case "community:channel.member_remove":
return
case "community:category.create":
upsertRows(registry, "categories", [{
@@ -2772,6 +2536,7 @@ export function projectCommunityWsEventToDb(
name: event.category.name,
position: event.category.position,
private: event.category.private,
+ creatorId: event.category.creatorId,
pending: false,
}])
return
diff --git a/src/web/src/lib/community-db/write.test.ts b/src/web/src/lib/community-db/write.test.ts
index 7156ab903..f8e578736 100644
--- a/src/web/src/lib/community-db/write.test.ts
+++ b/src/web/src/lib/community-db/write.test.ts
@@ -1,3 +1,5 @@
+import { profileResourceFixture } from "@/test/community-resource-fixtures"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { createCollection } from "@tanstack/react-db"
import { queryCollectionOptions } from "@tanstack/query-db-collection"
import { QueryClient } from "@tanstack/react-query"
@@ -37,32 +39,84 @@ function observeProfilePublications(registry: CommunityDbRegistry) {
}
describe("canonical collection publication", () => {
- it.each([false, true])("preserves sparse same-identity WS fields before ready=%s and honors explicit empty", async (ready) => {
+ it("replaces optional business fields and avoids republishing repeated equivalent snapshots", async () => {
+ const registry = owner()
+ await registry.preload()
+ const profile = profileSchema.parse({ id: "complete", name: "Complete", discriminator: "0042", avatar: null, avatarVersion: 0 })
+ await writeCommunityCollectionRows(registry, "profiles", [{ ...profile, aboutMe: "Private previous content" }], item => item.id)
+ const { publish, unsubscribe } = observeProfilePublications(registry)
+ try {
+ await writeCommunityCollectionRows(registry, "profiles", [profile], item => item.id)
+ expect(registry.collections.profiles.get(profile.id)?.aboutMe).toBeUndefined()
+ expect(publish).toHaveBeenCalledOnce()
+ await writeCommunityCollectionRows(registry, "profiles", [profile], item => item.id)
+ await writeCommunityCollectionRows(registry, "profiles", [{ ...profile, aboutMe: undefined }], item => item.id)
+ expect(publish).toHaveBeenCalledOnce()
+ } finally { unsubscribe() }
+ })
+
+ it("removes only documented live row metadata and still rejects missing or unknown business fields", async () => {
+ const registry = owner()
+ await registry.preload()
+ const profile = profileSchema.parse({ id: "complete", name: "Complete", discriminator: "0042", avatar: null, avatarVersion: 0 })
+ await writeCommunityCollectionRows(registry, "profiles", [profile], item => item.id)
+ const live = registry.collections.profiles.get(profile.id)!
+ expect(live).toHaveProperty("$key", profile.id)
+ await writeCommunityCollectionRows(registry, "profiles", [{ ...live, name: "Updated" }], item => item.id)
+ const key = communityKeys.communityDbCollection(registry.scopeId, "profiles")
+ const before = registry.queryClient.getQueryData(key)
+ await expect(async () => writeCommunityCollectionRows(registry, "profiles", [{ ...live, $unknown: true }], item => item.id)).rejects.toThrow()
+ await expect(async () => writeCommunityCollectionRows(registry, "profiles", [{ ...live, avatar: undefined }], item => item.id)).rejects.toThrow()
+ expect(registry.queryClient.getQueryData(key)).toBe(before)
+ expect(registry.collections.profiles.get(profile.id)?.name).toBe("Updated")
+ })
+
+ it.each([false, true])("rejects incomplete rows before canonical publication with ready=%s", async ready => {
+ const registry = owner()
+ if (ready) await registry.preload()
+ const row = profileSchema.parse({ id: "complete", name: "Complete", discriminator: "0042", avatar: null, avatarVersion: 0 })
+ await writeCommunityCollectionRows(registry, "profiles", [row], item => item.id)
+ const key = communityKeys.communityDbCollection(registry.scopeId, "profiles")
+ const before = registry.queryClient.getQueryData(key)
+ await expect(async () => writeCommunityCollectionRows(registry, "profiles", [{ ...row, avatar: undefined }], item => item.id)).rejects.toThrow()
+ expect(registry.queryClient.getQueryData(key)).toBe(before)
+ expect(registry.collections.profiles.get("partial")).toBeUndefined()
+ })
+
+ it.each([false, true])("requires full WS messages before ready=%s and honors explicit empty", async (ready) => {
const registry = owner()
if (ready) await registry.preload()
- const message = { id: "m-rich", seq: 3, type: "chat" as const, authorId: "peer", authorName: "Peer",
- authorAvatar: "peer-avatar", authorAvatarVersion: 0, content: "before", createdAt: "2026-08-07T10:00:00.000Z" }
- const attachments = [{ name: "notes.txt", url: "/notes.txt", sizeBytes: 1024 }]
+ const attachments = [{ id: "notes", name: "notes.txt", url: "/notes.txt", thumbnailUrl: null, contentType: "text/plain", sizeBytes: 1024, width: null, height: null }]
const embeds = [{ title: "Reference" }]
- ingestMessages(registry, "channel", [{ ...message, attachments, embeds }])
- const summaryFacts = { type: "system" as const, clientNonce: "known-nonce", replyToId: "reply" }
- ingestMessages(registry, "channel", [{ ...message, ...summaryFacts, attachments, embeds }])
- ingestMessages(registry, "channel", [{ id: message.id, content: "summary" }])
- expect(registry.queryClient.getQueryData(communityKeys.communityDbCollection(registry.scopeId, "messages"))).toMatchObject([
- { ...summaryFacts, content: "summary", attachments, embeds },
- ])
+ const message = messageResourceFixture({ id: "m-rich", channelId: "channel", seq: 3, authorId: "peer", authorName: "Peer",
+ authorAvatar: "peer-avatar", authorAvatarVersion: 0, content: "before", createdAt: "2026-08-07T10:00:00.000Z", attachments, embeds })
+ ingestMessages(registry, "channel", [message])
+ const key = communityKeys.communityDbCollection(registry.scopeId, "messages")
+ const before = registry.queryClient.getQueryData(key)
+ expect(() => ingestMessages(registry, "channel", [{ id: message.id, content: "summary" }])).toThrow()
+ expect(registry.queryClient.getQueryData(key)).toBe(before)
expect(registry.collections.messages.status === "ready").toBe(ready)
- projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.create",
+ projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.create", profiles: [profileResourceFixture({ id: "peer", name: "Peer", avatar: "peer-avatar" })],
serverId: "server", channelId: "channel", message: { ...message, content: "after" } })
- const key = communityKeys.communityDbCollection(registry.scopeId, "messages")
- expect(registry.queryClient.getQueryData(key)).toMatchObject([{ ...message, content: "after", attachments, embeds }])
+ expect(registry.queryClient.getQueryData(key)).toMatchObject([{ ...message, content: "after" }])
await registry.preload()
expect(registry.collections.messages.get(message.id)).toMatchObject({ content: "after", attachments, embeds })
- projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.create",
+ projectCommunityWsEventToDb(registry.queryClient, { type: "community:message.create", profiles: [profileResourceFixture({ id: "peer", name: "Peer", avatar: "peer-avatar" })],
serverId: "server", channelId: "channel", message: { ...message, attachments: [], embeds: [] } })
expect(registry.collections.messages.get(message.id)).toMatchObject({ attachments: [], embeds: [] })
})
+ it.each([false, true])("does not create an absent profile from a sparse patch with ready=%s", async ready => {
+ const registry = owner()
+ if (ready) await registry.preload()
+ writeCommunityProfilePatches([{ id: "unknown", identityAbout: { name: "Unknown" } }], registry)
+ const key = communityKeys.communityDbCollection(registry.scopeId, "profiles")
+ expect(registry.queryClient.getQueryData<Array<{ id: string }>>(key)?.some(row => row.id === "unknown") ?? false).toBe(false)
+ writeCommunityProfilePatches([{ id: "known", identityAbout: { name: "Known", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } }], registry)
+ writeCommunityProfilePatches([{ id: "known", identityAbout: { name: "Renamed" } }], registry)
+ expect(registry.queryClient.getQueryData(key)).toMatchObject([{ id: "known", name: "Renamed", discriminator: "0042", avatar: null, avatarVersion: 0 }])
+ })
+
it("reproduces snapshot loss with the library default collection GC", async () => {
vi.useFakeTimers()
const queryClient = new QueryClient()
@@ -94,7 +148,7 @@ describe("canonical collection publication", () => {
vi.useFakeTimers()
const registry = owner()
await registry.preload()
- writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alice" } }], registry)
+ writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alice", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } }], registry)
await vi.advanceTimersByTimeAsync(10 * 60 * 1000)
expect(registry.collections.profiles.status).toBe("ready")
expect(registry.collections.profiles.get("alice")?.name).toBe("Alice")
@@ -111,8 +165,8 @@ describe("canonical collection publication", () => {
const registry = owner()
await registry.preload()
writeCommunityProfilePatches([
- { id: "alice", identityAbout: { name: "Alice" } },
- { id: "bob", identityAbout: { name: "Bob" } },
+ { id: "alice", identityAbout: { name: "Alice", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } },
+ { id: "bob", identityAbout: { name: "Bob", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } },
], registry)
const bob = registry.collections.profiles.get("bob")
const upsert = vi.spyOn(registry.collections.profiles.utils, "writeUpsert")
@@ -136,7 +190,7 @@ describe("canonical collection publication", () => {
it("keeps equal rows silent and synchronizes deleting the final row", async () => {
const registry = owner()
await registry.preload()
- writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alice" } }], registry)
+ writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alice", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } }], registry)
const current = Array.from(registry.collections.profiles.values())
const key = communityKeys.communityDbCollection("viewer", "profiles")
const previous = registry.queryClient.getQueryData(key)
@@ -158,7 +212,7 @@ describe("canonical collection publication", () => {
it("commits a confirmed value equal to the visible optimistic overlay before the native transaction drops it", async () => {
const registry = owner()
await registry.preload()
- writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alice" } }], registry)
+ writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alice", discriminator: "0042" }, avatar: { avatar: null, avatarVersion: 0 } }], registry)
const transaction = registry.dbClient.createTransaction({ mutationFn: async () => {
writeCommunityProfilePatches([{ id: "alice", identityAbout: { name: "Alicia" } }], registry)
} })
@@ -170,7 +224,7 @@ describe("canonical collection publication", () => {
it("seeds a not-ready collection through the restore snapshot and then synchronizes", async () => {
const registry = owner()
- const row = profileSchema.parse({ identityComplete: false,
+ const row = profileSchema.parse({
id: "alice", name: "Alice", discriminator: "0001", avatar: "A", avatarVersion: 1,
})
expect(registry.collections.profiles.status).not.toBe("ready")
diff --git a/src/web/src/lib/community-db/write.ts b/src/web/src/lib/community-db/write.ts
index e4ed6cace..f1fe85c0e 100644
--- a/src/web/src/lib/community-db/write.ts
+++ b/src/web/src/lib/community-db/write.ts
@@ -2,35 +2,39 @@ import { replaceEqualDeep } from "@tanstack/react-query"
import { hasVirtualProps } from "@tanstack/react-db"
import { communityKeys } from "@/lib/query-keys"
import type { CommunityDbRegistry } from "./collections"
+import { communityCollectionSchemas, type CommunityCollectionName, type CommunityCollectionRows } from "@alook/shared"
-function businessRow<T extends object>(row: T): T {
- return hasVirtualProps(row)
- ? Object.fromEntries(Object.entries(row).filter(([key]) => !key.startsWith("$"))) as T
+export function communityRowData(row: unknown) {
+ return row !== null && typeof row === "object" && hasVirtualProps(row)
+ ? Object.fromEntries(Object.entries(row).filter(([key]) => !["$hasPendingWrites", "$synced", "$origin", "$key", "$collectionId"].includes(key)))
: row
}
-export function writeCommunityCollectionRows<T extends object>(
+export function writeCommunityCollectionRows<N extends CommunityCollectionName>(
registry: CommunityDbRegistry,
- name: keyof CommunityDbRegistry["collections"],
- rows: T[],
- getKey: (row: T) => string,
+ name: N,
+ rows: readonly unknown[],
+ getKey: (row: CommunityCollectionRows[N]) => string,
options?: { updatedAt: number },
) {
- const collection = registry.collections[name] as unknown as {
+ type Row = CommunityCollectionRows[N]
+ const verified = rows.map(row => communityCollectionSchemas[name].parse(communityRowData(row))) as Row[]
+ const keys = verified.map(getKey)
+ if (keys.some(key => typeof key !== "string" || key.length === 0) || new Set(keys).size !== keys.length) throw new Error("Invalid canonical row identity")
+ const collection = registry.collections[name] as {
status: string
keys: () => IterableIterator<string>
- getKeyFromItem: (row: T) => string
- get: (key: string) => T | undefined
+ getKeyFromItem: (row: Row) => string
+ get: (key: string) => Row | undefined
utils: {
writeBatch: (callback: () => void) => Promise<void>
writeDelete: (keys: string[]) => void
- writeUpsert: (rows: T[]) => void
+ writeUpsert: (rows: Row[]) => void
}
}
- const committed = registry.queryClient.getQueryData<T[]>(communityKeys.communityDbCollection(registry.scopeId, name))
+ const committed = registry.queryClient.getQueryData<Row[]>(communityKeys.communityDbCollection(registry.scopeId, name))
if (collection.status !== "ready") {
- const previousByKey = new Map((committed ?? []).map((row) => [getKey(row), businessRow(row)]))
- const next = rows.map((row) => ({ ...previousByKey.get(getKey(row)), ...businessRow(row) }))
+ const next = verified
registry.queryClient.setQueryData(
communityKeys.communityDbCollection(registry.scopeId, name),
next,
@@ -39,13 +43,18 @@ export function writeCommunityCollectionRows<T extends object>(
return
}
const previousByKey = committed === undefined ? undefined : new Map(committed.map((row) => [collection.getKeyFromItem(row), row]))
- const nextKeys = new Set(rows.map(getKey))
+ const nextKeys = new Set(keys)
const removed = Array.from(previousByKey?.keys() ?? collection.keys()).filter((key) => !nextKeys.has(key))
- const changed = rows.map(businessRow).filter((row) => {
+ const changed = verified.flatMap((row) => {
const previous = previousByKey === undefined ? collection.get(getKey(row)) : previousByKey.get(getKey(row))
- if (previous === undefined) return true
- const previousData = businessRow(previous)
- return replaceEqualDeep(previousData, row) !== previousData
+ if (previous === undefined) return [row]
+ const previousData = communityRowData(previous)
+ const previousEntries = previousData !== null && typeof previousData === "object" ? Object.entries(previousData) : []
+ const previousFields = Object.fromEntries(previousEntries.filter(([, value]) => value !== undefined))
+ const nextFields = Object.fromEntries(Object.entries(row).filter(([, value]) => value !== undefined))
+ if (replaceEqualDeep(previousFields, nextFields) === previousFields) return []
+ const cleared = Object.fromEntries(previousEntries.filter(([key]) => !(key in row)).map(([key]) => [key, undefined]))
+ return [{ ...cleared, ...row }]
})
if (removed.length === 0 && changed.length === 0) {
return
diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.ts
index 485e9173e..632b2662e 100644
--- a/src/web/src/lib/community/attachment-presentation.ts
+++ b/src/web/src/lib/community/attachment-presentation.ts
@@ -1,4 +1,4 @@
-import type { CommunityMessagePreviewAttachment, CommunityLegacyMessageAttachment } from "@alook/shared"
+import type { AttachmentPreview } from "./models/message"
import type { Attachment } from "./models/message"
import { isInlineAttachmentContentType } from "./attachment-content-type"
@@ -280,10 +280,9 @@ export function formatAttachmentSize(bytes?: number): string {
}
export function presentMessageAttachment(
- attachment: CommunityMessagePreviewAttachment | CommunityLegacyMessageAttachment,
+ attachment: AttachmentPreview,
): Attachment {
- const legacy = "kind" in attachment ? attachment : undefined
- const kind = legacy?.kind ?? (isInlineAttachmentContentType(attachment.contentType) ? "image" : "file")
+ const kind = isInlineAttachmentContentType(attachment.contentType) ? "image" : "file"
const metadata = {
name: attachment.name, url: attachment.url,
...(attachment.contentType != null ? { contentType: attachment.contentType } : {}),
@@ -295,5 +294,5 @@ export function presentMessageAttachment(
...(attachment.width != null ? { width: attachment.width } : {}),
...(attachment.height != null ? { height: attachment.height } : {}),
}
- return { ...metadata, kind, size: legacy?.size ?? formatAttachmentSize(attachment.sizeBytes ?? undefined) }
+ return { ...metadata, kind, size: formatAttachmentSize(attachment.sizeBytes ?? undefined) }
}
diff --git a/src/web/src/lib/community/attention-resources.server.test.ts b/src/web/src/lib/community/attention-resources.server.test.ts
new file mode 100644
index 000000000..be38a7209
--- /dev/null
+++ b/src/web/src/lib/community/attention-resources.server.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { AttentionIncludedChannelSchema, type AccountAttentionProjection, type Database } from "@alook/shared"
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
+
+const mocks = vi.hoisted(() => ({ access: vi.fn(), memberships: vi.fn() }))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return { ...actual, queries: {
+ ...actual.queries,
+ communityMessage: { ...actual.queries.communityMessage, getMessagesByIdsInChannels: vi.fn(async () => []) },
+ communityChannel: { ...actual.queries.communityChannel, listReadableMessageChannelsForUser: (...args: unknown[]) => mocks.access(...args), listChannelMembershipsForUserInChannels: (...args: unknown[]) => mocks.memberships(...args) },
+ communityServer: { ...actual.queries.communityServer, listUserServers: vi.fn(async () => [{ id: "s1", name: "Server", discriminator: "0001", description: "", ownerId: "viewer", icon: null, official: false, role: "owner", memberId: "member" }]) },
+ user: { ...actual.queries.user, getUsersByIds: vi.fn(async () => [{ id: "viewer", name: "Viewer", discriminator: "0001", image: null, avatarVersion: 0 }]) },
+ communityUserProfile: { ...actual.queries.communityUserProfile, getResourceProfiles: vi.fn(async () => [{ id: "viewer", name: "Viewer", discriminator: "0001", avatar: null, avatarVersion: 0 }]), getProfilesByUserIds: vi.fn(async () => []) },
+ } }
+})
+import { hydrateAttentionResources, readCommunityResourceBundle } from "./attention-resources.server"
+
+const db = {} as Database
+const parent = channelResourceFixture({ id: "parent", serverId: "s1" })
+const child = channelResourceFixture({ id: "child", serverId: "s1", type: "thread", parentChannelId: parent.id, parentMessageId: "opener" })
+const access = [parent, child].map(channel => ({ channelId: channel.id, userId: "viewer", relation: "access", source: "explicit" }))
+const notify = { channelId: "child", userId: "viewer", relation: "notify", source: "spoke" }
+const projection: AccountAttentionProjection = {
+ scopes: [], items: [], limit: 100, truncated: false,
+ included: { servers: [{ id: "s1", name: "Server", discriminator: "0001" }], channels: [parent, child].map(channel => AttentionIncludedChannelSchema.strip().parse(channel)), dms: [], profiles: [], messages: [] },
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.access.mockImplementation(async (_db, _viewer, ids: string[]) => ids.map(id => id === "parent" ? parent : child))
+})
+
+describe("current attention resource producer", () => {
+ it.each([false, true])("hydrates a schema-valid full attention snapshot with viewer notify=%s", async hasNotify => {
+ mocks.memberships.mockResolvedValue([...access, ...(hasNotify ? [notify] : [])])
+ const result = await hydrateAttentionResources(db, "viewer", projection)
+ expect(result.resources.memberships).toEqual(access)
+ expect(result.resources.channels).toEqual([parent, child])
+ expect(mocks.memberships).toHaveBeenCalledExactlyOnceWith(db, "viewer", ["parent", "child"])
+ expect(mocks.access).toHaveBeenCalledExactlyOnceWith(db, "viewer", ["parent", "child"])
+ })
+
+ it("preserves notify in the separate generic complete resource bundle", async () => {
+ mocks.memberships.mockResolvedValue([...access, notify])
+ const result = await readCommunityResourceBundle(db, "viewer", { channelIds: ["parent", "child"] })
+ expect(result.memberships).toEqual([...access, notify])
+ })
+})
diff --git a/src/web/src/lib/community/attention-resources.server.ts b/src/web/src/lib/community/attention-resources.server.ts
new file mode 100644
index 000000000..22858a031
--- /dev/null
+++ b/src/web/src/lib/community/attention-resources.server.ts
@@ -0,0 +1,58 @@
+import {
+ AccountAttentionSnapshotSchema, communityMessageProfileIds, COMMUNITY_RESOURCE_CONTRACT_VERSION,
+ CommunityChannelMembershipResourceSchema, CommunityResourceBundleSchema, CommunityServerResourceSchema, communityChannelResourceFromStorage, isServerOwner, queries,
+ withD1Retry, type CommunityResourceBundle, type AccountAttentionProjection, type AccountAttentionSnapshot, type Database,
+} from "@alook/shared"
+import { loadApiMessageContext, mapMessageForApi } from "./message-payload"
+import { serverIconUrl } from "./storage"
+import { readCommunityResourceProfiles } from "./resource-profiles.server"
+
+export async function hydrateAttentionResources(db: Database, viewerId: string, projection: AccountAttentionProjection): Promise<AccountAttentionSnapshot> {
+ const resources = await readCommunityResourceBundle(db, viewerId, {
+ channelIds: [...projection.included.channels.map(row => row.id), ...projection.included.dms.map(row => row.id), ...projection.included.messages.map(row => row.channelId)],
+ profileIds: projection.included.profiles.map(row => row.userId), messageIds: projection.included.messages.map(row => row.id), serverIds: projection.included.servers.map(row => row.id),
+ })
+ return AccountAttentionSnapshotSchema.parse({ ...projection, resources: { ...resources, memberships: resources.memberships.filter(row => row.relation === "access") } })
+}
+
+export async function readCommunityResourceBundle(db: Database, viewerId: string, input: {
+ channelIds: string[]; profileIds?: string[]; messageIds?: string[]; serverIds?: string[]
+}): Promise<CommunityResourceBundle> {
+ const channelIds = new Set(input.channelIds)
+ const readChannels = async (ids: string[]) => {
+ const rows = await withD1Retry(() => queries.communityChannel.listReadableMessageChannelsForUser(db, viewerId, ids), { route: "community/permissions:channel-member" })
+ const byId = new Map(rows.map(row => [row.id, row]))
+ if (ids.some(id => !byId.has(id))) throw new Error("Attention access changed")
+ return ids.map(id => communityChannelResourceFromStorage(byId.get(id)!))
+ }
+ const channels = await readChannels([...channelIds])
+ const missingParents = [...new Set(channels.flatMap(row => row.parentChannelId && !channelIds.has(row.parentChannelId) ? [row.parentChannelId] : []))]
+ if (missingParents.length) channels.push(...await readChannels(missingParents))
+ const allowedIds = channels.map(row => row.id)
+ const [messageRows, serverRows, membershipRows] = await Promise.all([
+ queries.communityMessage.getMessagesByIdsInChannels(db, input.messageIds ?? [], allowedIds),
+ channels.some(row => row.serverId !== null) || input.serverIds?.length ? queries.communityServer.listUserServers(db, viewerId) : Promise.resolve([]),
+ queries.communityChannel.listChannelMembershipsForUserInChannels(db, viewerId, allowedIds),
+ ])
+ if (input.messageIds?.some(id => !messageRows.some(row => row.id === id))) throw new Error("Requested message resource missing from scope")
+ const context = await loadApiMessageContext(db, viewerId, messageRows.map(row => row.id), () =>
+ queries.communityMessage.getMessagesByIdsInChannels(db, messageRows.flatMap(row => row.replyToId ? [row.replyToId] : []), allowedIds), true)
+ const messages = messageRows.map(row => mapMessageForApi(row, context(row.channelId), COMMUNITY_RESOURCE_CONTRACT_VERSION, row.channelId))
+ const profiles = await readCommunityResourceProfiles(db, [viewerId, ...(input.profileIds ?? []), ...communityMessageProfileIds(messages)])
+ const serverIds = new Set([...(input.serverIds ?? []), ...channels.flatMap(row => row.serverId ? [row.serverId] : [])])
+ const selectedServers = serverRows.flatMap((row, position) => serverIds.has(row.id) ? [{ row, position }] : [])
+ const relations = membershipRows.map(row => CommunityChannelMembershipResourceSchema.parse(row))
+ const accessByChannel = new Map(relations.filter(row => row.relation === "access").map(row => [row.channelId, row]))
+ return CommunityResourceBundleSchema.parse({
+ viewerId,
+ servers: selectedServers.map(({ row, position }) => CommunityServerResourceSchema.parse({
+ id: row.id, position, name: row.name, discriminator: row.discriminator, description: row.description,
+ ownerId: row.ownerId, icon: serverIconUrl(row), official: row.official, isOwner: isServerOwner(row.role),
+ })),
+ serverMemberships: selectedServers.map(({ row }) => ({ serverId: row.id, userId: viewerId, memberId: row.memberId, role: row.role })),
+ channels,
+ memberships: [...channels.map(row => accessByChannel.get(row.id) ?? { channelId: row.id, userId: viewerId, relation: "access", source: "access-decision" }), ...relations.filter(row => row.relation === "notify")],
+ profiles,
+ messages,
+ })
+}
diff --git a/src/web/src/lib/community/attention-resources.sql.test.ts b/src/web/src/lib/community/attention-resources.sql.test.ts
new file mode 100644
index 000000000..8a807021b
--- /dev/null
+++ b/src/web/src/lib/community/attention-resources.sql.test.ts
@@ -0,0 +1,157 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { queries, BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, AccountAttentionSnapshotSchema } from "@alook/shared"
+import type { AuthenticatedHandler } from "@/lib/middleware/auth"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+import { hydrateAttentionResources, readCommunityResourceBundle } from "./attention-resources.server"
+
+const attentionHttp = vi.hoisted(() => ({ db: null as unknown }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => attentionHttp.db, getDb: () => attentionHttp.db }))
+vi.mock("@/lib/middleware/auth", async () => {
+ const { protectCommunityJsonResponse } = await import("@/lib/middleware/response-cache")
+ return { withAuth: (handler: AuthenticatedHandler) => async (request: NextRequest) => protectCommunityJsonResponse(request,
+ await handler(request, { env: { DB: {} } as Env, userId: "viewer", email: "[email protected]" })) }
+})
+import { GET } from "@/app/api/community/users/me/attention/route"
+
+const fixtures: ReturnType<typeof createCommunitySqliteDb>[] = []
+const stamp = "2026-10-28T00:00:00.000Z"
+function fixture(count: number) {
+ const result = createCommunitySqliteDb()
+ fixtures.push(result)
+ result.sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt") VALUES (?,?,?,?,0,?,?)').run("viewer", "[email protected]", "Viewer", "0001", stamp, stamp)
+ result.sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES (?,?,?,?,?,?)").run("server", "Server", "0002", "", "viewer", stamp)
+ result.sqlite.exec("INSERT INTO community_server_member (id,server_id,user_id,role) VALUES ('membership','server','viewer','owner')")
+ const insert = result.sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at) VALUES (?,?,?,'text','',0,0,0,?)")
+ const ids = Array.from({ length: count }, (_, index) => `channel-${index}`)
+ for (const id of ids) insert.run(id, "server", id, stamp)
+ return { ...result, ids }
+}
+afterEach(() => { for (const item of fixtures) item.sqlite.close(); fixtures.length = 0 })
+
+async function blockDm(store: ReturnType<typeof createCommunitySqliteDb>, by: "viewer" | "peer") {
+ const blockerId = by === "viewer" ? "viewer" : "peer", targetId = by === "viewer" ? "peer" : "viewer"
+ const result = await queries.communityFriendship.block(store.db, { blockerId, targetId })
+ expect(result.row).toMatchObject({ requesterId: blockerId, addresseeId: targetId, status: "blocked", blockerId })
+ expect(result.row.createdAt).toEqual(expect.any(String))
+ expect(result.row.updatedAt).toEqual(expect.any(String))
+}
+
+async function dmFixture(block: "none" | "viewer" | "peer") {
+ const store = createCommunitySqliteDb(); fixtures.push(store); attentionHttp.db = store.db
+ for (const id of ["viewer", "peer", "other"]) store.sqlite.prepare('INSERT INTO user (id,email,name,discriminator,image,"avatarVersion","createdAt","updatedAt") VALUES (?,?,?,?,null,0,?,?)').run(id, `${id}@example.test`, id, "0042", stamp, stamp)
+ for (const [id, peer] of [["blocked-dm", "peer"], ["allowed-dm", "other"]]) {
+ store.sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at,last_message_at) VALUES (?,null,null,'dm','',0,0,1,?,?)").run(id, stamp, stamp)
+ for (const user of ["viewer", peer]) store.sqlite.prepare("INSERT INTO community_channel_member (id,channel_id,user_id,relation,source,added_by,added_at) VALUES (?,?,?,'access','added','viewer',?)").run(`${id}:${user}`, id, user, stamp)
+ store.sqlite.prepare("INSERT INTO community_message (id,author_id,content,type,channel_id,seq,created_at) VALUES (?,?,?,'default',?,1,?)").run(`${id}:message`, peer, `${id} body`, id, stamp)
+ }
+ if (block !== "none") await blockDm(store, block)
+ return store
+}
+
+it.each(["none", "viewer", "peer"] as const)("keeps an already-existing %s block consistent between eligible and complete read SQL", async block => {
+ const { db } = await dmFixture(block)
+ const expected = new Set(block === "none" ? ["blocked-dm", "allowed-dm"] : ["allowed-dm"])
+ const readable = await queries.communityChannel.listReadableMessageChannelsForUser(db, "viewer", ["blocked-dm", "allowed-dm"])
+ expect(new Set(readable.map(row => row.id))).toEqual(expected)
+ const eligible = await queries.communityInbox.listEligibleUnreadDms(db, "viewer")
+ expect(new Set(eligible.map(row => row.channelId))).toEqual(expected)
+})
+
+it.each(["none", "viewer", "peer"] as const)("returns the complete current attention HTTP resource for an already-existing %s block", async block => {
+ await dmFixture(block)
+ const response = await GET(new NextRequest("http://localhost/api/community/users/me/attention", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }), {} as never)
+ expect(response.status).toBe(200)
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const snapshot = AccountAttentionSnapshotSchema.parse(await response.json())
+ const expected = new Set(block === "none" ? ["blocked-dm", "allowed-dm"] : ["allowed-dm"])
+ expect(new Set(snapshot.scopes.map(row => row.channelId))).toEqual(expected)
+ expect(new Set(snapshot.resources.channels.map(row => row.id))).toEqual(expected)
+})
+
+it("still rejects hydration when a real block happens after the earlier projection", async () => {
+ const store = await dmFixture("none")
+ const projection = await queries.communityAttention.getAccountAttentionProjection(store.db, "viewer")
+ expect(projection.included.dms.some(row => row.id === "blocked-dm")).toBe(true)
+ await blockDm(store, "peer")
+ await expect(hydrateAttentionResources(store.db, "viewer", projection)).rejects.toThrow("Attention access changed")
+})
+
+describe("full resource hydrator with actual scoped SQL", () => {
+ it.each([250, 500])("hydrates all %i public channels within the existing D1 invocation limit", async count => {
+ const { db, record, ids } = fixture(count)
+ const result = await readCommunityResourceBundle(db, "viewer", { channelIds: ids })
+ expect(result.channels.map(row => row.id)).toEqual(ids)
+ expect(result.memberships).toHaveLength(count)
+ expect(result.profiles).toEqual([expect.objectContaining({ id: "viewer", name: "Viewer", avatar: null, avatarVersion: 0 })])
+ console.info(JSON.stringify({ case: "actual-full-resource-sql", channels: count, invocations: record.invocations, statements: record.statements.length, batches: record.batches, maxBindings: Math.max(...record.statements.map(row => row.bindings.length)) }))
+ expect(record.invocations).toBeLessThanOrEqual(1000)
+ expect(record.statements.every(row => row.bindings.length <= 100)).toBe(true)
+ })
+})
+
+it("uses one scoped SQL statement for a deduplicated collection, without hiding fanout in batch", async () => {
+ const { queries } = await import("@alook/shared")
+ const { db, record, ids } = fixture(500)
+ expect(await queries.communityChannel.listReadableMessageChannelsForUser(db, "viewer", [])).toEqual([])
+ expect(record.statements).toHaveLength(0)
+ const result = await queries.communityChannel.listReadableMessageChannelsForUser(db, "viewer", [...ids, ids[0]!])
+ expect(new Set(result.map(row => row.id))).toEqual(new Set(ids))
+ expect(record.invocations).toBe(1)
+ expect(record.statements).toHaveLength(1)
+ expect(record.batches).toEqual([])
+})
+
+it.each([
+ { name: "server owner has no private bypass", allowed: false },
+ { name: "private creator", creator: "viewer", allowed: true },
+ { name: "private access", relation: "access", allowed: true },
+ { name: "private notify is not access", relation: "notify", allowed: false },
+ { name: "creator still needs server membership", creator: "viewer", outsider: true, allowed: false },
+ { name: "foreign server", foreign: true, allowed: false },
+ { name: "child creator has no inherited access", child: true, creator: "viewer", allowed: false },
+ { name: "child inherits anchor creator", child: true, parentCreator: "viewer", allowed: true },
+ { name: "child inherits anchor access", child: true, parentRelation: "access", allowed: true },
+ { name: "child notify is not anchor access", child: true, parentRelation: "notify", allowed: false },
+ { name: "missing anchor", child: true, missingParent: true, allowed: false },
+])("preserves scoped collection permissions: $name", async scenario => {
+ const { sqlite, db } = fixture(1)
+ sqlite.exec("INSERT INTO community_category (id,server_id,name,private) VALUES ('private','server','Private',1)")
+ sqlite.prepare("INSERT INTO community_channel (id,server_id,category_id,name,type,topic,position,archived,message_count,created_at,creator_id,parent_channel_id) VALUES ('private-channel',?,'private','Private',?,'',0,0,0,?,?,?)")
+ .run(scenario.foreign ? "other-server" : "server", scenario.child ? "thread" : "text", stamp, scenario.creator ?? null, scenario.child ? "anchor" : null)
+ if (scenario.child && !scenario.missingParent) sqlite.prepare("INSERT INTO community_channel (id,server_id,category_id,name,type,topic,position,archived,message_count,created_at,creator_id) VALUES ('anchor','server','private','Anchor','text','',0,0,0,?,?)").run(stamp, scenario.parentCreator ?? null)
+ if (scenario.relation) sqlite.prepare("INSERT INTO community_channel_member (id,channel_id,user_id,relation,source) VALUES ('private-roster','private-channel','viewer',?,'added')").run(scenario.relation)
+ if (scenario.parentRelation) sqlite.prepare("INSERT INTO community_channel_member (id,channel_id,user_id,relation,source) VALUES ('anchor-roster','anchor','viewer',?,'added')").run(scenario.parentRelation)
+ if (scenario.outsider) sqlite.exec("DELETE FROM community_server_member WHERE user_id='viewer'")
+ const operation = readCommunityResourceBundle(db, "viewer", { channelIds: ["channel-0", "private-channel"] })
+ if (scenario.allowed) {
+ const result = await operation
+ expect(result.channels.map(row => row.id)).toEqual(scenario.child ? ["channel-0", "private-channel", "anchor"] : ["channel-0", "private-channel"])
+ } else await expect(operation).rejects.toThrow("Attention access changed")
+})
+
+it.each([
+ { name: "valid pair", allowed: true },
+ { name: "blocked by viewer", block: "viewer", allowed: false },
+ { name: "blocked by peer", block: "peer", allowed: false },
+ { name: "no peer access", noPeer: true, allowed: false },
+ { name: "peer notify only", peerRelation: "notify", allowed: false },
+ { name: "viewer notify only", viewerRelation: "notify", allowed: false },
+])("retains DM message access: $name", async scenario => {
+ const { sqlite, db } = fixture(1)
+ sqlite.prepare("INSERT INTO community_channel (id,name,type,topic,position,archived,message_count,created_at) VALUES ('dm',NULL,'dm','',0,0,0,?)").run(stamp)
+ const member = sqlite.prepare("INSERT INTO community_channel_member (id,channel_id,user_id,relation,source) VALUES (?,'dm',?,?,'added')")
+ member.run("dm-viewer", "viewer", scenario.viewerRelation ?? "access")
+ if (!scenario.noPeer) member.run("dm-peer", "peer", scenario.peerRelation ?? "access")
+ if (scenario.block) sqlite.prepare("INSERT INTO community_friendship (id,requester_id,addressee_id,status) VALUES ('block',?,?,'blocked')").run(scenario.block, scenario.block === "viewer" ? "peer" : "viewer")
+ const operation = readCommunityResourceBundle(db, "viewer", { channelIds: ["channel-0", "dm"] })
+ if (scenario.allowed) expect((await operation).channels.map(row => row.id)).toEqual(["channel-0", "dm"])
+ else await expect(operation).rejects.toThrow("Attention access changed")
+})
+
+it("rejects a missing item after valid items and preserves request order without duplicate resources", async () => {
+ const { db } = fixture(2)
+ await expect(readCommunityResourceBundle(db, "foreign-viewer", { channelIds: ["channel-0"] })).rejects.toThrow("Attention access changed")
+ await expect(readCommunityResourceBundle(db, "viewer", { channelIds: ["channel-0", "missing"] })).rejects.toThrow("Attention access changed")
+ expect((await readCommunityResourceBundle(db, "viewer", { channelIds: ["channel-1", "channel-0", "channel-1"] })).channels.map(row => row.id)).toEqual(["channel-1", "channel-0"])
+})
diff --git a/src/web/src/lib/community/bots.server.ts b/src/web/src/lib/community/bots.server.ts
index 9c5195073..5f1c975b3 100644
--- a/src/web/src/lib/community/bots.server.ts
+++ b/src/web/src/lib/community/bots.server.ts
@@ -1,4 +1,4 @@
-import { queries, DAILY_TOKEN_USAGE_WINDOW_DAYS, calendarDayKeyDaysAgo, dayKeyInTimeZone, utcDayKey, utcDayKeyDaysAgo, type Database } from "@alook/shared"
+import { parseCommunityBotsProfileRead, queries, DAILY_TOKEN_USAGE_WINDOW_DAYS, calendarDayKeyDaysAgo, dayKeyInTimeZone, utcDayKey, utcDayKeyDaysAgo, type Database } from "@alook/shared"
import { canonicalUserImage } from "./storage"
export function tokenUsageDayWindow(now: Date, timeZone: string | null | undefined): string[] {
@@ -65,7 +65,7 @@ export async function readCommunityBots(db: Database, userId: string) {
},
}
})
- return {
+ const result = {
bots: withActivity,
plan: capacity.plan,
isFounder: capacity.isFounder,
@@ -73,4 +73,6 @@ export async function readCommunityBots(db: Database, userId: string) {
ownedCount: capacity.ownedCount,
activeCount: capacity.activeCount,
}
+ parseCommunityBotsProfileRead(result, userId)
+ return result
}
diff --git a/src/web/src/lib/community/bots.ts b/src/web/src/lib/community/bots.ts
index 3113d662a..2c2bc7d9e 100644
--- a/src/web/src/lib/community/bots.ts
+++ b/src/web/src/lib/community/bots.ts
@@ -1,4 +1,5 @@
import { queryOptions } from "@tanstack/react-query"
+import { parseCommunityBotsProfileRead, CommunityBotProfileSummarySchema, type CommunityBotsProfileRead } from "@alook/shared"
import type { DailyUsageMetric, ReasoningEffort } from "@alook/shared"
import type { BotActivityDay, CommunityProfilePatch } from "./models/people"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
@@ -60,18 +61,23 @@ export type BotPlanSummary = {
type BotResource = Omit<BotSummary, "name" | "description" | "image" | "avatarVersion" | "presence">
export type BotsResourceResponse = Partial<BotPlanSummary> & { bots: BotResource[]; observed?: boolean; source?: "network" | "rsc" | "restored_idb" }
-export type BotsResponse = BotPlanSummary & { bots: BotSummary[] }
+export type BotsResponse = BotPlanSummary & { bots: Array<BotSummary & CommunityBotsProfileRead["bots"][number]> }
export function botProfilePatch(bot: Pick<BotSummary, "id" | "name" | "image" | "avatarVersion"> & { description?: string }): CommunityProfilePatch {
- return { id: bot.id, identityAbout: { name: bot.name, kind: "bot", ...("discriminator" in bot && typeof bot.discriminator === "string" ? { discriminator: bot.discriminator } : {}), ...(bot.description === undefined ? {} : { aboutMe: bot.description }) }, avatar: { avatar: bot.image, avatarVersion: bot.avatarVersion } }
+ const identity = CommunityBotProfileSummarySchema.parse(bot)
+ return { id: identity.id, identityAbout: { name: identity.name, kind: "bot", ...(identity.discriminator === undefined ? {} : { discriminator: identity.discriminator }), ...(identity.description === undefined ? {} : { aboutMe: identity.description }) }, avatar: { avatar: identity.image, avatarVersion: identity.avatarVersion }, ...(identity.presence === undefined ? {} : { presence: identity.presence }) }
}
function botsResource(data: BotsResponse): BotsResourceResponse {
- return { ...data, bots: data.bots.map(({ name: _name, description: _description, image: _image, avatarVersion: _avatarVersion, presence: _presence, ...resource }) => resource) }
+ return { ...data, bots: data.bots.map(({ name: _name, description: _description, image: _image, avatarVersion: _avatarVersion, presence: _presence, discriminator: _discriminator, ownerUserId: _ownerUserId, ...resource }) => resource) }
}
export const botsOptions = () => queryOptions({
queryKey: communityKeys.bots(),
- queryFn: async ({ client, signal }): Promise<BotsResourceResponse> => ({ ...botsResource(await apiFetchProfiles<BotsResponse>("/api/community/bots", data => data.bots.map(bot => ({ ...botProfilePatch(bot), presence: bot.presence })), { signal }, getCommunityDbRegistry(client))), source: "network" }),
+ queryFn: async ({ client, signal }): Promise<BotsResourceResponse> => {
+ const registry = getCommunityDbRegistry(client)
+ const data = await apiFetchProfiles<BotsResponse>("/api/community/bots", data => parseCommunityBotsProfileRead(data, registry!.accountId!).bots.map(bot => { const patch = botProfilePatch(bot); return { ...patch, identityAbout: { ...patch.identityAbout, ownerUserId: bot.ownerUserId } } }), { signal }, registry)
+ return { ...botsResource(data), source: "network" }
+ },
staleTime: query => query.state.data?.observed === false ? 0 : 5_000,
})
diff --git a/src/web/src/lib/community/conversation-entry.errors.test.ts b/src/web/src/lib/community/conversation-entry.errors.test.ts
new file mode 100644
index 000000000..6cdea4dc0
--- /dev/null
+++ b/src/web/src/lib/community/conversation-entry.errors.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { COMMUNITY_CONVERSATION_ANCHOR_MISSING, BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityReadErrorSchema } from "@alook/shared"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { conversationEntryFixture, dmConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
+import { protectCommunityJsonResponse } from "@/lib/middleware/response-cache"
+import { apiFetch } from "@/lib/api/client"
+import { ApiError, CommunityApiError } from "@/lib/errors"
+import { conversationEntryOptions } from "./conversation-entry"
+import { isConversationAnchorMissingError } from "./conversation-read"
+
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
+
+function respond(status: number, error: string, details?: string[]) {
+ vi.stubGlobal("fetch", vi.fn(async (path: string, options?: RequestInit) => protectCommunityJsonResponse(
+ new Request(new URL(path, "https://alook.test"), options), Response.json({ error, ...(details ? { details } : {}) }, { status }),
+ )))
+}
+
+describe("current error semantics through middleware, API client and entry", () => {
+ it.each(["anchor", "forbidden", "missing"] as const)("preserves %s access semantics after the actual error response boundary", async mode => {
+ const { client, registry } = await createCommunityQueryOwner()
+ await seedConversationEntry(client, conversationEntryFixture())
+ respond(mode === "forbidden" ? 403 : 404, mode === "anchor" ? "anchor not found" : "channel not available",
+ mode === "anchor" ? [COMMUNITY_CONVERSATION_ANCHOR_MISSING] : undefined)
+ const failure = await client.query({ ...conversationEntryOptions(client, { channelId: "c1", serverId: "s1", anchorMessageId: "deleted" }), retry: false, select: undefined }).then(
+ () => { throw new Error("Expected entry failure") }, error => error,
+ )
+ expect(failure).toBeInstanceOf(ApiError)
+ expect(isConversationAnchorMissingError(failure)).toBe(mode === "anchor")
+ expect(registry.runtime.ws.actions.isChannelAccessRevoked("c1", "s1")).toBe(mode !== "anchor")
+ if (mode === "anchor") expect(registry.collections.messages.get("m1")?.content).toBe("Body")
+ })
+
+ it("keeps current validation details and their readable error message", async () => {
+ respond(400, "validation error", ["name: Too long"])
+ const failure = await apiFetch("/api/community/servers", { method: "POST", body: JSON.stringify({ name: "invalid" }) }).then(
+ () => { throw new Error("Expected validation failure") }, error => error,
+ )
+ expect(failure).toBeInstanceOf(ApiError)
+ expect(failure.details).toEqual(["name: Too long"])
+ expect(failure.message).toBe("Name Too long")
+ })
+})
+
+it.each([["blocked",403],["not_allowed",403],["not_found",404]] as const)("hands the actual %s error to the current scope before query generation retirement",async(code,status)=>{
+ const {client,registry}=await createCommunityQueryOwner()
+ const value=code==="blocked" ? dmConversationEntryFixture() : conversationEntryFixture()
+ await seedConversationEntry(client,value)
+ const {captureCommunityLiveSnapshotToken,publishCommunityMessages}=await import("@/lib/community-db/sync")
+ const obsolete=captureCommunityLiveSnapshotToken(client,value.channelId)
+ const payload=CommunityReadErrorSchema.parse({contractVersion:BUSINESS_SCHEMA_VERSION,error:{code,message:code,retryable:false}})
+ vi.stubGlobal("fetch",vi.fn(async()=>new Response(JSON.stringify(payload),{status,headers:{"content-type":"application/json",[COMMUNITY_CONTRACT_HEADER]:String(BUSINESS_SCHEMA_VERSION)}})))
+ const failure=await client.query({...conversationEntryOptions(client,{channelId:value.channelId,serverId:value.channel.serverId}),retry:false,staleTime:0,select:undefined}).catch(error=>error)
+ expect(failure).toBeInstanceOf(CommunityApiError)
+ expect(failure.code).toBe(code)
+ const scope=registry.runtime.ws.get().channelAccessScopes.get(value.channelId)!
+ expect(scope).toMatchObject({revoked:true,denialCode:code})
+ expect(scope.generation).toBeGreaterThan(obsolete.channelScopes.get(value.channelId)?.generation ?? 0)
+ expect(registry.collections.messages.has("m1")).toBe(false)
+ expect(()=>publishCommunityMessages(client,{channelId:value.channelId,messages:value.messages,profiles:value.profiles,proof:{token:obsolete}})).toThrow()
+})
diff --git a/src/web/src/lib/community/conversation-entry.server.ts b/src/web/src/lib/community/conversation-entry.server.ts
index 686bddf55..9f60f7cdb 100644
--- a/src/web/src/lib/community/conversation-entry.server.ts
+++ b/src/web/src/lib/community/conversation-entry.server.ts
@@ -1,12 +1,13 @@
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { COMMUNITY_CONVERSATION_ANCHOR_MISSING, communityChannelResourceFromStorage, CommunityConversationEntryReadSchema, CommunityThreadsReadSchema, CommunityMessageResourceSchema, queries, withD1Retry, type CommunityConversationEntryRead, type Database } from "@alook/shared"
-import { canonicalUserImage } from "./storage"
+import { readCommunityResourceProfiles } from "./resource-profiles.server"
import { readCommunityMessageWindow } from "./message-window.server"
import { communityMessagesReadFromPage } from "./read-contract"
import type { DoorTarget } from "./message-door"
import type { parseCommunityMessageWindow } from "./messages"
import { readCommunityForumRows } from "./forum-feed.server"
import { readCommunityThreadsResource } from "./thread-read"
-import { readCommunityMessageResource } from "./message-payload"
+import { readCommunityMessageResource, readCommunityMessageProfiles } from "./message-payload"
type ConversationEntryInput = {
viewerId: string
@@ -35,8 +36,10 @@ export async function readCommunityConversationEntry(db: Database, input: Conver
channel.parentChannelId ? readParent(db, viewerId, channel.parentChannelId) : Promise.resolve(undefined),
])
if (!read.ok) return read
+ const openerProfiles = opener ? await readCommunityMessageProfiles(db, [opener]) : []
+ const profiles = [...new Map([...read.page.profiles, ...openerProfiles].map(profile => [profile.id, profile])).values()]
return { ok: true, entry: CommunityConversationEntryReadSchema.parse({
- ...communityMessagesReadFromPage(channelId, read.page), viewerId, channel, peer,
+ ...communityMessagesReadFromPage(channelId, read.page), profiles, viewerId, channel, peer,
...(opener ? { opener } : {}),
...(parent ? { parent } : {}),
readState: read.readState, readStateRevision: read.revision, selection: read.selection,
@@ -58,8 +61,8 @@ async function readEntryWindow(db: Database, { viewerId, target, window, preferT
if (target.access.channel.type === "forum" && !window.anchorId) {
const page = await readCommunityForumRows(db, channelId, { tag, pageSize: window.pageSize, includes: new Set(["parentMessage", "firstMessage", "tags", "participants"]) })
const forumFeed = CommunityThreadsReadSchema.parse(await readCommunityThreadsResource(db, viewerId, target.access.channel, page.threads,
- { messages: [...page.parentMessages, ...page.firstMessages], tags: page.tags, participants: page.participants }, { hasMore: page.hasMore, nextCursor: page.nextCursor ?? null }, 3))
- return { ok: true as const, page: { messages: [], latestSeq: readState.lastReadSeq, hasMoreOlder: false, hasMoreNewer: false, surfaceReceipt: { channelId, surfaceKind: "forum" as const } },
+ { messages: [...page.parentMessages, ...page.firstMessages], tags: page.tags, participants: page.participants }, { hasMore: page.hasMore, nextCursor: page.nextCursor ?? null }, COMMUNITY_RESOURCE_CONTRACT_VERSION))
+ return { ok: true as const, page: { messages: [], profiles: [], latestSeq: readState.lastReadSeq, hasMoreOlder: false, hasMoreNewer: false, surfaceReceipt: { channelId, surfaceKind: "forum" as const } },
readState, revision, selection: { reason: "tail" as const, anchorMessageId: null }, forumFeed }
}
const anchorId = window.anchorId ?? (preferTail ? undefined : readState.lastReadMessageId ?? undefined)
@@ -67,12 +70,12 @@ async function readEntryWindow(db: Database, { viewerId, target, window, preferT
reason: window.anchorId ? "explicit_anchor" : anchorId ? "read_pointer" : "tail", anchorMessageId: anchorId ?? null,
}
let result = await readCommunityMessageWindow(db, {
- viewerId, target, window: { ...window, anchorId }, contract: 3, tag,
+ viewerId, target, window: { ...window, anchorId }, contract: COMMUNITY_RESOURCE_CONTRACT_VERSION, tag,
})
if (!result.ok && !window.anchorId && anchorId) {
selection = { reason: "read_pointer_missing", anchorMessageId: null }
result = await readCommunityMessageWindow(db, {
- viewerId, target, window: { ...window, anchorId: undefined }, contract: 3, tag,
+ viewerId, target, window: { ...window, anchorId: undefined }, contract: COMMUNITY_RESOURCE_CONTRACT_VERSION, tag,
})
}
if (!result.ok) return { ...result, ...(window.anchorId ? { details: [COMMUNITY_CONVERSATION_ANCHOR_MISSING] } : {}) }
@@ -80,14 +83,14 @@ async function readEntryWindow(db: Database, { viewerId, target, window, preferT
}
async function readPeer(db: Database, peerId: string) {
- const peer = await withD1Retry(() => queries.user.getUserPublic(db, peerId), { route: "community/messages:entry-peer" })
- return { id: peerId, name: peer?.name ?? "Deleted user", discriminator: peer?.discriminator ?? null,
- avatar: peer ? canonicalUserImage(peerId, peer.image, peer.avatarVersion) : null, avatarVersion: peer?.avatarVersion ?? 0 }
+ const [peer] = await withD1Retry(() => readCommunityResourceProfiles(db, [peerId]), { route: "community/messages:entry-peer" })
+ if (!peer) throw new Error("Conversation peer resource missing")
+ return peer
}
async function readOpener(db: Database, viewerId: string, channelId: string, messageId: string) {
const [message] = await withD1Retry(() => queries.communityMessage.getMessagesByIdsInScope(db, [messageId], { channelId }), { route: "community/messages:entry-opener" })
- return message ? CommunityMessageResourceSchema.parse(await readCommunityMessageResource(db, viewerId, message, 3)) : undefined
+ return message ? CommunityMessageResourceSchema.parse(await readCommunityMessageResource(db, viewerId, message, COMMUNITY_RESOURCE_CONTRACT_VERSION)) : undefined
}
async function readParent(db: Database, viewerId: string, channelId: string) {
diff --git a/src/web/src/lib/community/conversation-entry.test.ts b/src/web/src/lib/community/conversation-entry.test.ts
index 8001163a0..e6e4534af 100644
--- a/src/web/src/lib/community/conversation-entry.test.ts
+++ b/src/web/src/lib/community/conversation-entry.test.ts
@@ -1,6 +1,7 @@
+import { dmListRowFixture, channelResourceFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
import { writeCommunityCollectionRows } from "@/lib/community-db/write"
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONVERSATION_ANCHOR_MISSING, type CommunityConversationEntryRead } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONVERSATION_ANCHOR_MISSING, type CommunityConversationEntryRead } from "@alook/shared"
import { ApiError } from "@/lib/errors"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
@@ -50,7 +51,7 @@ describe("conversation entry canonical publication", () => {
} finally { vi.useRealTimers() }
})
- it.each(["missing", "incomplete", "pending", "archived", "foreign", "parent-missing", "parent-foreign", "retired"] as const)("rejects a %s cache closure without deleting its retained message window", async condition => {
+ it.each(["missing", "pending", "archived", "foreign", "parent-missing", "parent-foreign", "retired"] as const)("rejects a %s cache closure without deleting its retained message window", async condition => {
const { client, registry } = await createCommunityQueryOwner()
const value = entry()
if (condition.startsWith("parent")) {
@@ -64,8 +65,7 @@ describe("conversation entry canonical publication", () => {
if (condition === "retired") registry.runtime.lifecycle.setState(state => ({ active: false, generation: state.generation + 1 }))
else await writeCommunityCollectionRows(registry, "channels", (client.getQueryData<ChannelRow[]>(channels) ?? []).flatMap(row => {
if (condition === "missing" && row.id === "c1" || condition === "parent-missing" && row.id === "parent") return []
- if (row.id === "c1") return [{ ...row, ...(condition === "incomplete" ? { resourceComplete: false as const } : {}),
- ...(condition === "pending" ? { pending: true } : {}), ...(condition === "archived" ? { archived: true } : {}),
+ if (row.id === "c1") return [{ ...row, ...(condition === "pending" ? { pending: true } : {}), ...(condition === "archived" ? { archived: true } : {}),
...(condition === "foreign" ? { serverId: "foreign" } : {}) }]
return [{ ...row, ...(condition === "parent-foreign" ? { serverId: "foreign" } : {}) }]
}), row => row.id)
@@ -157,7 +157,7 @@ describe("conversation entry canonical publication", () => {
expect(client.getQueryData(previous.windowKey)).toBe(before)
const repair = client.getQueryCache().find({ queryKey: repairKey, exact: true })!.promise!.catch(error => error)
if (fail) reject(new Error("held repair failed"))
- else resolve({ messages: [{ ...next.messages[0], id: "m2", seq: 2 }], latestSeq: 2, hasMoreNewer: false })
+ else resolve({ profiles: next.profiles, messages: [{ ...next.messages[0], id: "m2", seq: 2 }], latestSeq: 2, hasMoreNewer: false })
await repair
expect(client.getQueryState(options.queryKey)?.status).toBe("success")
expect(client.getQueryState(repairKey)?.status).toBe(fail ? "error" : "success")
@@ -185,13 +185,13 @@ describe("conversation entry canonical publication", () => {
expect(JSON.stringify(window)).not.toContain("Body")
expect(window).toMatchObject({ pages: [{ threads: [{ id: "t1", openerMessageId: "m1" }] }], pageParams: [null] })
expect(registry.collections.messages.get("m1")?.content).toBe("Body")
- expect(registry.collections.channels.get("t1")).toMatchObject({ parentChannelId: "c1", resourceComplete: true })
+ expect(registry.collections.channels.get("t1")).toMatchObject({ parentChannelId: "c1" })
expect(client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages("c1") })).toHaveLength(0)
await client.query({ ...conversationEntryOptions(client, target), select: undefined })
expect(load).toHaveBeenCalledOnce()
})
- it.each(["child-missing", "child-incomplete", "child-type", "child-server", "child-parent", "opener-missing", "opener-incomplete", "opener-channel"] as const)("rejects a cached Forum display window with %s without refreshing its qualification", async invalid => {
+ it.each(["child-missing", "child-type", "child-server", "child-parent", "opener-missing", "opener-channel"] as const)("rejects a cached Forum display window with %s without refreshing its qualification", async invalid => {
const { client, registry } = await createCommunityQueryOwner()
const value = forumConversationEntryFixture()
const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
@@ -200,18 +200,15 @@ describe("conversation entry canonical publication", () => {
if (invalid === "child-missing") await registry.collections.channels.utils.writeDelete("t1")
else if (invalid.startsWith("child-")) {
const child = registry.collections.channels.get("t1")!
- await registry.collections.channels.utils.writeUpsert({ ...child,
- ...(invalid === "child-incomplete" ? { resourceComplete: false } : {}),
+ await writeCommunityCollectionRows(registry, "channels", Array.from(registry.collections.channels.values()).map(row => row.id === child.id ? { ...row,
...(invalid === "child-type" ? { type: "text" as const } : {}),
...(invalid === "child-server" ? { serverId: "other" } : {}),
...(invalid === "child-parent" ? { parentChannelId: "other" } : {}),
- })
+ } : row), row => row.id)
} else if (invalid === "opener-missing") await registry.collections.messages.utils.writeDelete("m1")
else {
const opener = registry.collections.messages.get("m1")!
- await registry.collections.messages.utils.writeUpsert({ ...opener,
- ...(invalid === "opener-incomplete" ? { resourceComplete: false } : { channelId: "other" }),
- })
+ await writeCommunityCollectionRows(registry, "messages", Array.from(registry.collections.messages.values()).map(row => row.id === opener.id ? { ...row, channelId: "other" } : row), row => row.id)
}
expect(getQualifiedConversationScope(client, target)).toBeDefined()
expect(findConversationDisplayWindow(client, target, scope)).toBeUndefined()
@@ -277,7 +274,7 @@ describe("conversation entry canonical publication", () => {
it("keeps a structural directory from creating a second reading-proof cache", async () => {
const { client, registry } = await createCommunityQueryOwner()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [{ id: "dm", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, status: "offline", preview: "" }] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "dm", userId: "peer", name: "Peer", discriminator: "0042", avatar: "P", avatarVersion: 0, status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
expect(registry.collections.channels.has("dm")).toBe(true)
expect(client.getQueryData(communityKeys.channelMeta(null, "dm"))).toBeUndefined()
expect(client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries("dm") })).toEqual([])
@@ -289,10 +286,10 @@ describe("conversation entry canonical publication", () => {
const resource = await client.query({ ...conversationEntryOptions(client, target), select: undefined })
expect(load).toHaveBeenCalledOnce()
expect(load).toHaveBeenCalledWith("/api/community/channels/c1/messages?entry=1", expect.objectContaining({
- authenticationAccount: "viewer", signal: expect.any(AbortSignal), headers: { [COMMUNITY_CONTRACT_HEADER]: "3" },
+ authenticationAccount: "viewer", signal: expect.any(AbortSignal), headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
}))
- expect(registry.collections.channels.get("c1")).toMatchObject({ resourceComplete: true, name: "Channel" })
- expect(registry.collections.messages.get("m1")).toMatchObject({ resourceComplete: true, content: "Body" })
+ expect(registry.collections.channels.get("c1")).toMatchObject({ name: "Channel" })
+ expect(registry.collections.messages.get("m1")).toMatchObject({ content: "Body" })
expect(registry.collections.readStates.get("c1")).toMatchObject({ lastReadSeq: 1, observedRevision: 4 })
expect(registry.collections.readStateClock.get("account")).toBeUndefined()
const window = client.getQueryData<MessageWindowData>(resource.windowKey)!
@@ -310,7 +307,12 @@ describe("conversation entry canonical publication", () => {
})
it("keeps the pages and pageParams of an existing matching historical window", async () => {
- const { client } = await createCommunityQueryOwner()
+ const { client, registry } = await createCommunityQueryOwner()
+ const { ingestMessages } = await import("@/lib/community-db/sync")
+ const { writeCommunityProfilePatches, communityUserProfilePatch } = await import("./profile-seed")
+ const value = entry()
+ writeCommunityProfilePatches(value.profiles.map(profile => communityUserProfilePatch(profile.id, profile)), registry)
+ ingestMessages(registry, "c1", [{ ...value.messages[0], id: "history", seq: 0 }])
const key = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
const previous: MessageWindowData = {
pages: [{ messages: [{ id: "m1", seq: 1 }] }, { messages: [{ id: "history", seq: 0 }] }],
@@ -392,7 +394,7 @@ describe("conversation entry canonical publication", () => {
const value = entry()
const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
client.removeQueries({ queryKey: communityKeys.communityDbCollection(registry.scopeId, "channels"), exact: true })
- expect(registry.collections.channels.get("c1")?.resourceComplete).toBe(true)
+ expect(registry.collections.channels.get("c1")).toMatchObject(value.channel)
expect(findConversationEntryWindow(client, target, resource, value.readState)?.key).toEqual(resource.windowKey)
})
@@ -416,3 +418,35 @@ describe("conversation entry canonical publication", () => {
})
})
+
+
+it.each(["main", "opener"] as const)("validates the effective retained %s reply graph before any entry write", async location => {
+ const { communityRegistrySnapshot } = await import("@/test/community-registry-snapshot")
+ const { ingestMessages } = await import("@/lib/community-db/sync")
+ const { communityUserProfilePatch, writeCommunityProfilePatches } = await import("./profile-seed")
+ const { client, registry } = await createCommunityQueryOwner()
+ const value = entry()
+ const original = { ...value.messages[0], ...(location === "opener" ? { id: "opener", channelId: "parent" } : {}) }
+ const retainedReply = { id: "prior", authorId: "prior-author", authorName: "Prior author", text: "Retained reply" }
+ ingestMessages(registry, original.channelId, [{ ...original, replyToId: "prior", replyTo: retainedReply }])
+ const incoming = { ...original, replyToId: "prior" }
+ if (location === "main") value.messages = [incoming]
+ else {
+ value.channel = { ...value.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }
+ value.parent = channelResourceFixture({ id: "parent", serverId: "s1", type: "text" })
+ value.opener = incoming
+ value.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }
+ }
+ const before = communityRegistrySnapshot(registry)
+ const queries = client.getQueryCache().getAll().map(query => [query.queryKey, structuredClone(query.state.data)])
+ const access = structuredClone(registry.runtime.ws.get().channelAccessScopes)
+ expect(() => publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })).toThrow("Retained message profile resource missing")
+ expect(communityRegistrySnapshot(registry)).toEqual(before)
+ expect(registry.runtime.ws.get().channelAccessScopes).toEqual(access)
+ expect(client.getQueryCache().getAll().map(query => [query.queryKey, query.state.data])).toEqual(queries)
+ const prior = profileResourceFixture({ id: "prior-author", name: "Prior author" })
+ writeCommunityProfilePatches([communityUserProfilePatch(prior.id, prior)], registry)
+ const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
+ expect(registry.collections.messages.get(original.id)?.replyTo).toEqual(retainedReply)
+ expect(findConversationEntryWindow(client, target, resource, value.readState)).toBeDefined()
+})
diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.ts
index 44d1ec6e4..a2ce696b5 100644
--- a/src/web/src/lib/community/conversation-entry.ts
+++ b/src/web/src/lib/community/conversation-entry.ts
@@ -1,3 +1,4 @@
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { reconcileConversationLanding } from "@/hooks/community/community-ws/reconnect-messages"
import { channelHref } from "./community-route"
import { actionAttributes, currentPageObservation, navigationForHref } from "@/lib/observability/context"
@@ -10,11 +11,11 @@ import { communityRequestOptions } from "./account-cache-lifecycle"
import { isChannelMetadataTokenCurrent } from "./conversation-qualification"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { channelMembershipKey, type ReadStateRow } from "@/lib/community-db/schema"
-import { ApiError } from "@/lib/errors"
+import { ApiError, CommunityApiError } from "@/lib/errors"
import {
assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken,
publishCommunityChannelMetadata, publishCommunityChannelMembersSnapshot, publishCommunityConversationReadState, confirmCommunityConversationPresence,
- publishCommunityMessages, retireCommunityChannelReading, type CommunityFreshQueryProof,
+ publishCommunityMessages, getCanonicalCommunityMessageResources, validateCommunityMessagePublication, retireCommunityChannelReading, type CommunityFreshQueryProof,
publishCommunityForumFeed, getCanonicalCommunityAttentionScopes,
} from "@/lib/community-db/sync"
import { messageWindowPage, type MessagesPageParam } from "./models/message"
@@ -52,19 +53,19 @@ export function assessConversationScope(client: QueryClient, target: Conversatio
const channel = registry.collections.channels.get(target.channelId)
if (registry.runtime.ws.actions.isChannelAccessRevoked(target.channelId, target.serverId, channel?.parentChannelId ?? undefined)) return { reason: "revoked" as const }
if (!channel) return { reason: "metadata_missing" as const }
- if (!channel.resourceComplete || channel.pending) return { reason: "metadata_incomplete" as const }
+ if (channel.pending) return { reason: "metadata_incomplete" as const }
if (channel.archived) return { reason: "archived" as const }
if (channel.serverId !== target.serverId || (target.serverId === null ? channel.type !== "dm" : channel.type === "dm")) return { reason: "scope_mismatch" as const }
const parent = channel.parentChannelId
? registry.collections.channels.get(channel.parentChannelId) : undefined
if (channel.type !== "thread" && channel.parentChannelId) return { reason: "scope_mismatch" as const }
if (channel.type === "thread") {
- if (!parent?.resourceComplete || parent.pending) return { reason: "parent_missing" as const }
+ if (!parent || parent.pending) return { reason: "parent_missing" as const }
if (parent.archived || parent.serverId !== target.serverId || parent.type !== "text" && parent.type !== "forum" || !channel.parentMessageId) return { reason: "parent_mismatch" as const }
}
const access = (id: string) => !!registry.collections.channelMemberships.get(channelMembershipKey(id, registry.accountId!, "access"))
if (!access(channel.id) || parent && !access(parent.id)) return { reason: "access_missing" as const }
- const proof = { ...captureCommunityLiveSnapshotToken(client, channel.id), channelLineage: { parentChannelId: channel.parentChannelId ?? undefined } }
+ const proof = { ...captureCommunityLiveSnapshotToken(client, channel.id), channelLineage: { parentChannelId: channel.parentChannelId } }
if (!isChannelMetadataTokenCurrent(proof)) return { reason: "owner_retired" as const }
return { reason: "qualified" as const, scope: { channelId: channel.id, proof } satisfies ConversationWindowScope }
}
@@ -81,10 +82,7 @@ export function publishConversationEntry(
source: "rsc" | "network" = "network",
): ConversationEntryResource {
assertCommunityLiveSnapshotTokenCurrent(client, proof.token, proof.signal)
- const entry = CommunityConversationEntryReadSchema.parse({ ...value, messages: value.messages.map((message) => {
- const { resourceComplete: _complete, ...resource } = message as typeof message & { resourceComplete?: true }
- return resource
- }) })
+ const entry = CommunityConversationEntryReadSchema.parse(value)
const channel = entry.channel
if (entry.viewerId !== proof.token.viewerId || proof.token.channelId !== target.channelId || entry.channelId !== target.channelId || channel.serverId !== target.serverId
|| (target.serverId === null ? channel.type !== "dm" : channel.type === "dm")
@@ -92,20 +90,23 @@ export function publishConversationEntry(
const registry = proof.token.registry!
const parent = channel.parentChannelId
if (parent && (registry.runtime.ws.get().channelAccessScopes.get(parent)?.generation ?? 0) !== (proof.token.channelScopes.get(parent)?.generation ?? 0)) throw new DOMException("Retired conversation parent", "AbortError")
+ validateCommunityMessagePublication(registry, entry.messages, entry.profiles)
+ if (entry.opener) validateCommunityMessagePublication(registry, [entry.opener], entry.profiles)
+ if (entry.forumFeed) validateCommunityMessagePublication(registry, entry.forumFeed.included.messages, entry.forumFeed.included.profiles)
const initialWindow: InitialMessageWindow = entry.selection.anchorMessageId ? { mode: "anchor", anchor: entry.selection.anchorMessageId } : { mode: "newest" }
const windowKey = entry.forumFeed ? communityKeys.forumFeed(target.channelId, target.tag ?? null) : communityKeys.channelMessagesWindow(target.channelId, initialWindow, target.tag)
- const qualified = { ...proof.token, channelLineage: { parentChannelId: parent ?? undefined } }
+ const qualified = { ...proof.token, channelLineage: { parentChannelId: parent } }
notifyManager.batch(() => {
if (channel.serverId) registry.runtime.ws.actions.grantServerAccess(channel.serverId)
registry.runtime.ws.actions.rememberChannelAccess(channel.serverId, channel.id, parent ?? undefined)
- publishCommunityChannelMetadata(client, { metadata: { ...channel, resourceComplete: true }, proof })
- if (entry.parent) publishCommunityChannelMetadata(client, { metadata: { ...entry.parent, resourceComplete: true }, proof })
+ publishCommunityChannelMetadata(client, { metadata: channel, proof })
+ if (entry.parent) publishCommunityChannelMetadata(client, { metadata: entry.parent, proof })
if (entry.peer) publishCommunityChannelMembersSnapshot(client, null, channel.id, "access", [entry.viewerId, entry.peer.id].map((userId) => ({
channelId: channel.id, userId, relation: "access", source: "added", isCreator: channel.creatorId === userId, role: null, memberId: null,
})), proof, [entry.peer])
- publishCommunityMessages(client, { channelId: channel.id, messages: entry.messages.map((message) => ({ ...message, resourceComplete: true })), proof })
+ publishCommunityMessages(client, { channelId: channel.id, messages: entry.messages, profiles: entry.profiles, proof })
if (entry.opener) {
- publishCommunityMessages(client, { channelId: entry.opener.channelId, messages: [{ ...entry.opener, resourceComplete: true }], proof })
+ publishCommunityMessages(client, { channelId: entry.opener.channelId, messages: [entry.opener], profiles: entry.profiles, proof })
client.setQueryData(communityKeys.message(entry.opener.id), entry.opener.id)
}
publishCommunityConversationReadState(client, entry.readState, entry.readStateRevision, proof)
@@ -113,13 +114,11 @@ export function publishConversationEntry(
if (entry.forumFeed) {
const page = normalizeThreadResources(channel.id, entry.forumFeed)
publishCommunityForumFeed(client, channel.id, page, proof)
- const cached = client.getQueryData<{ pages: ForumFeedPage[]; pageParams: Array<string | null> }>(windowKey)
- if (!Array.isArray(cached?.pages) || !cached.pages.length || !Array.isArray(cached.pageParams) || cached.pages.length !== cached.pageParams.length || cached.pages.some(page => !Array.isArray(page.threads))) client.setQueryData(windowKey, { pages: [forumFeedWindow(page)], pageParams: [null] })
+ if (!conversationDisplayWindows(client, target, { channelId: channel.id, proof: qualified, windowKey })?.some(window => hashKey(window.key) === hashKey(windowKey))) client.setQueryData(windowKey, { pages: [forumFeedWindow(page)], pageParams: [null] })
}
else {
- const cached = client.getQueryData<MessageWindowData>(windowKey)
- if (Array.isArray(cached?.pages) && cached.pages.length && Array.isArray(cached.pageParams) && cached.pages.length === cached.pageParams.length && cached.pages.every(page => Array.isArray(page.messages))) return
- const page = messageWindowPage({ ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages })
+ if (conversationDisplayWindows(client, target, { channelId: channel.id, proof: qualified, windowKey })?.some(window => hashKey(window.key) === hashKey(windowKey))) return
+ const page = messageWindowPage({ ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages, profiles: entry.profiles })
client.setQueryData<MessageWindowData>(windowKey, { pages: [page], pageParams: [initialWindow as MessagesPageParam] })
}
})
@@ -151,14 +150,20 @@ function conversationDisplayWindows(client: QueryClient, target: ConversationEnt
if (channel.type === "forum" && !target.anchorMessageId) {
const key = communityKeys.forumFeed(channel.id, target.tag ?? null)
const feed = client.getQueryData<{ pages: ForumFeedPage[]; pageParams: Array<string | null> }>(key)
- if (!feed?.pages.length || !Array.isArray(feed.pageParams) || feed.pages.length !== feed.pageParams.length) return
+ if (!Array.isArray(feed?.pages) || !feed.pages.length || !Array.isArray(feed.pageParams) || feed.pages.length !== feed.pageParams.length) return
const byId = registry.collections.channels
- if (feed.pages.some(page => !Array.isArray(page.threads) || page.threads.some(thread => {
+ if (feed.pages.some(page => !Array.isArray(page?.threads) || page.threads.some(thread => {
+ if (!thread || typeof thread.id !== "string" || !thread.id) return true
const child = byId.get(thread.id)
const opener = thread.openerMessageId ? messages.get(thread.openerMessageId) : undefined
- return !child?.resourceComplete || child.type !== "thread" || child.serverId !== channel.serverId || child.parentChannelId !== channel.id
- || !!thread.openerMessageId && (!opener?.resourceComplete || opener.channelId !== channel.id)
+ return !child || child.type !== "thread" || child.serverId !== channel.serverId || child.parentChannelId !== channel.id
+ || !!thread.openerMessageId && (!opener || opener.channelId !== channel.id)
}))) return
+ const retained = feed.pages.flatMap(page => page.threads.flatMap(thread => {
+ const child = byId.get(thread.id)
+ return [thread.openerMessageId ? messages.get(thread.openerMessageId) : undefined, child?.firstMessageId ? messages.get(child.firstMessageId) : undefined].filter(message => message !== undefined)
+ }))
+ if (!getCanonicalCommunityMessageResources(client, retained)) return
return [{ key, initial: { mode: "newest" as const }, tag: target.tag ?? null }]
}
const windows = client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages(target.channelId) })
@@ -167,9 +172,10 @@ function conversationDisplayWindows(client: QueryClient, target: ConversationEnt
const identity = messageWindowIdentity(window.queryKey)
if (!identity || identity.tag !== (target.tag ?? null) || identity.initial.mode === "since") return []
const data = window.state.data as MessageWindowData | undefined
- if (!Array.isArray(data?.pages) || !Array.isArray(data.pageParams) || !data.pages.length || data.pageParams.length !== data.pages.length || data.pages.some((page) => !Array.isArray(page.messages))) return []
+ if (!Array.isArray(data?.pages) || !Array.isArray(data.pageParams) || !data.pages.length || data.pageParams.length !== data.pages.length || data.pages.some((page) => !Array.isArray(page?.messages) || page.messages.some(message => typeof message?.id !== "string" || !message.id))) return []
const ids = data.pages.flatMap((page) => page.messages.map((message) => message.id))
- if (ids.some(id => messages.get(id)?.resourceComplete !== true || messages.get(id)?.channelId !== target.channelId)) return []
+ if (ids.some(id => messages.get(id)?.channelId !== target.channelId)) return []
+ if (!getCanonicalCommunityMessageResources(client, ids.map(id => messages.get(id)))) return []
return [{ key: window.queryKey, initial: identity.initial, tag: identity.tag }]
})
}
@@ -234,7 +240,7 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
try {
const entry = await withConversationReadDeadline(signal, (readSignal) => apiFetch<CommunityConversationEntryRead>(
`/api/community/channels/${encodeURIComponent(target.channelId)}/messages?${search}`,
- { ...communityRequestOptions(client, token, readSignal, assert), headers: { [COMMUNITY_CONTRACT_HEADER]: "3" },
+ { ...communityRequestOptions(client, token, readSignal, assert), headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) },
observation: { ...captured, role: "entry", windowMode: target.anchorMessageId ? "anchor" : "newest" } },
))
assert()
@@ -249,7 +255,7 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
void reconcileConversationLanding(client, {
kind: target.serverId === null ? "dm" : "channel", scopeId: target.channelId,
serverId: target.serverId ?? undefined,
- }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages }, initial,
+ }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages, profiles: entry.profiles }, initial,
{ query: original!, signal, lifetime: "query", observation: captured }).catch(() => undefined)
}
record("delivered")
@@ -259,7 +265,8 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
&& !!original && client.getQueryCache().get(original.queryHash) === original
record(!current || error instanceof Error && error.name === "AbortError" ? "cancelled" : "error")
assert()
- if (error instanceof ApiError && (error.status === 403 || error.status === 404) && !isConversationAnchorMissingError(error)) retireCommunityChannelReading(token.registry!, target.channelId, { reason: "read-denied", serverId: target.serverId, preserveQuery: original })
+ if (error instanceof ApiError && (error.status === 403 || error.status === 404) && !isConversationAnchorMissingError(error)) retireCommunityChannelReading(token.registry!, target.channelId, { reason: "read-denied", serverId: target.serverId, preserveQuery: original,
+ ...(error instanceof CommunityApiError ? { denialCode: error.code } : {}) })
throw error
}
},
diff --git a/src/web/src/lib/community/conversation-qualification.test.ts b/src/web/src/lib/community/conversation-qualification.test.ts
new file mode 100644
index 000000000..248fdd420
--- /dev/null
+++ b/src/web/src/lib/community/conversation-qualification.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { retireCommunityChannelReading } from "@/lib/community-db/sync"
+import { retireCommunityAccount } from "./account-cache-lifecycle"
+import { captureChannelMetadataToken, conversationListScopeKey, isChannelMetadataTokenCurrent } from "./conversation-qualification"
+
+describe("conversation list lifetime identity", () => {
+ it("keeps one lifetime stable while isolating accounts, channels and tags", async () => {
+ const alice = await createCommunityQueryOwner("alice")
+ const bob = await createCommunityQueryOwner("bob")
+ const scope = { proof: captureChannelMetadataToken(alice.client, "A"), tag: null }
+ const key = conversationListScopeKey(scope)
+ const records = alice.client.getQueryCache().getAll().length
+ expect(conversationListScopeKey({ ...scope, proof: captureChannelMetadataToken(alice.client, "A") })).toEqual(key)
+ for (const other of [
+ { ...scope, proof: captureChannelMetadataToken(bob.client, "A") },
+ { ...scope, proof: captureChannelMetadataToken(alice.client, "B") },
+ { ...scope, tag: "bug" },
+ ]) expect(conversationListScopeKey(other)).not.toEqual(key)
+ expect(alice.client.getQueryCache().getAll()).toHaveLength(records)
+ })
+
+ it("retires the original channel and account identity through the existing fences", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const scope = { proof: captureChannelMetadataToken(client, "A"), tag: null }
+ retireCommunityChannelReading(registry, "A", { reason: "read-denied", serverId: null })
+ const next = { ...scope, proof: captureChannelMetadataToken(client, "A") }
+ expect(isChannelMetadataTokenCurrent(scope.proof)).toBe(false)
+ expect(conversationListScopeKey(next)).not.toEqual(conversationListScopeKey(scope))
+ retireCommunityAccount(registry)
+ expect(isChannelMetadataTokenCurrent(next.proof)).toBe(false)
+ expect(conversationListScopeKey({ ...scope, proof: captureChannelMetadataToken(client, "A") })).not.toEqual(conversationListScopeKey(next))
+ })
+
+ it("includes the captured parent access lifetime for a child list", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const scope = { proof: { ...captureChannelMetadataToken(client, "child"), channelLineage: { parentChannelId: "parent" } }, tag: null }
+ retireCommunityChannelReading(registry, "parent", { reason: "read-denied", serverId: null })
+ const next = { ...scope, proof: { ...captureChannelMetadataToken(client, "child"), channelLineage: { parentChannelId: "parent" } } }
+ expect(conversationListScopeKey(next)).not.toEqual(conversationListScopeKey(scope))
+ })
+})
diff --git a/src/web/src/lib/community/conversation-qualification.ts b/src/web/src/lib/community/conversation-qualification.ts
index 3a50802d4..75a0167a4 100644
--- a/src/web/src/lib/community/conversation-qualification.ts
+++ b/src/web/src/lib/community/conversation-qualification.ts
@@ -1,6 +1,19 @@
import type { QueryClient } from "@tanstack/react-query"
import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+export type ConversationListScope = {
+ proof: ReturnType<typeof captureChannelMetadataToken>
+ tag: string | null
+}
+
+export function conversationListScopeKey({ proof, tag }: ConversationListScope) {
+ const channelId = proof.channelId!
+ const parentId = proof.channelLineage?.parentChannelId
+ return [proof.viewerId, channelId, tag, proof.accountEpoch, proof.accessEpoch, proof.ownerGeneration,
+ proof.channelScopes.get(channelId)?.generation ?? 0,
+ parentId ?? null, parentId ? proof.channelScopes.get(parentId)?.generation ?? 0 : 0] as const
+}
+
export function captureChannelMetadataToken(client: QueryClient, channelId: string) {
return captureCommunityLiveSnapshotToken(client, channelId)
}
diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.ts
index 49e319884..d8e20cbc7 100644
--- a/src/web/src/lib/community/create-channels.test.ts
+++ b/src/web/src/lib/community/create-channels.test.ts
@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
-const producerEnv = vi.hoisted(() => ({ COMMUNITY_EVENT_CONTRACT: "1" }))
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
+
+const producerEnv = vi.hoisted(() => ({}))
vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: () => ({ env: producerEnv, ctx: {} }) }))
const mockCreateCommunityMessage = vi.fn()
@@ -70,19 +72,17 @@ import { createMessageWithThread, createThreadForUser, createServerChannelForUse
describe("createServerChannelForUser producer contracts", () => {
beforeEach(() => {
vi.clearAllMocks()
- producerEnv.COMMUNITY_EVENT_CONTRACT = "1"
mockRequireServerMember.mockResolvedValue({ ok: true, value: { role: "owner" } })
})
- it.each([["1", false], ["1", true], ["3", false], ["3", true]] as const)("fans out contract %s only to the private=%s audience", async (contract, privateCategory) => {
- producerEnv.COMMUNITY_EVENT_CONTRACT = contract
+ it.each([false, true])("fans out the current full resource only to the private=%s audience", async (privateCategory) => {
const row = { id: "channel", type: "text", serverId: "server", name: "channel", categoryId: "category", topic: "Topic",
parentChannelId: null, parentMessageId: null, creatorId: "viewer", position: 4, archived: 0, createdAt: "now", lastMessageAt: null, messageCount: 0 }
mockGetCategory.mockResolvedValue({ id: "category", serverId: "server", private: privateCategory })
mockCreateChannel.mockResolvedValue(row)
const result = await createServerChannelForUser({} as never, { serverId: "server", actorUserId: "viewer", name: "channel", type: "text", categoryId: "category", topic: "Topic" })
- const legacyChannel = { id: "channel", name: "channel", type: "text", categoryId: "category", topic: "Topic", position: 4, createdAt: "now" }
- expect(result).toEqual({ ok: true, value: legacyChannel })
- const event = { type: "community:channel.create", serverId: "server", channel: contract === "3" ? { ...row, archived: false } : legacyChannel }
+ const channel = { ...row, archived: false }
+ expect(result).toEqual({ ok: true, value: channel })
+ const event = { type: "community:channel.create", serverId: "server", channel }
if (privateCategory) {
expect(mockCreateChannelMember).toHaveBeenCalledWith(expect.anything(), { channelId: "channel", userId: "viewer", addedBy: "viewer" })
expect(mockFanOutToChannel).toHaveBeenCalledExactlyOnceWith("channel", event)
@@ -92,7 +92,6 @@ describe("createServerChannelForUser producer contracts", () => {
expect(mockFanOutToChannel).not.toHaveBeenCalled()
expect(mockCreateChannelMember).not.toHaveBeenCalled()
}
- producerEnv.COMMUNITY_EVENT_CONTRACT = "1"
})
})
@@ -120,7 +119,7 @@ describe("createThreadForUser", () => {
.mockResolvedValueOnce({ ok: true, value: {} })
mockCreateChannel.mockImplementation(async () => {
order.push("create")
- return { id: "thread_1", name: "x".repeat(40), createdAt: "t0", creatorId: "cli_author" }
+ return { ...channelResourceFixture({ id: "thread_1", name: "x".repeat(40), createdAt: "t0", creatorId: "cli_author", type: "thread", serverId: "s1", parentChannelId: "parent_1", parentMessageId: "m1" }), archived: 0 }
})
mockAddThreadParticipants.mockImplementation(async () => {
order.push("participants")
diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.ts
index 52d6958aa..5d1ff753e 100644
--- a/src/web/src/lib/community/create-channels.ts
+++ b/src/web/src/lib/community/create-channels.ts
@@ -21,8 +21,8 @@ import { requireMessageBearingSurface } from "@/lib/community/channel-write-guar
import { guardDmOpen } from "@/lib/community/dm-guard"
import { createCommunityMessage, type IncomingMessageBody } from "@/lib/community/message-handler"
import { nanoid } from "nanoid"
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { communityProducerContract } from "./producer-contract"
+
+
/**
* Single-source creation cores for the `POST /channels` create door (route/disc
@@ -58,7 +58,7 @@ export async function createServerChannelForUser(
categoryId?: unknown
topic?: unknown
},
-): Promise<CreateChannelResult<{ id: string; name: string; type: ChannelType; categoryId: string | null; topic?: string; position: number; createdAt: number }>> {
+): Promise<CreateChannelResult<ReturnType<typeof communityChannelResourceFromStorage>>> {
const { serverId, actorUserId } = params
const auth = await requireServerMember(db, serverId, actorUserId)
@@ -128,24 +128,9 @@ export async function createServerChannelForUser(
})
}
- const channel = {
- id: row.id,
- name: row.name,
- type: row.type as ChannelType,
- categoryId: row.categoryId,
- topic: row.topic ?? undefined,
- position: row.position ?? 0,
- createdAt: row.createdAt,
- }
+ const channel = communityChannelResourceFromStorage(row)
+ const event = CommunityResourceWsEventSchema.parse({ type: WS_EVENTS.CHANNEL_CREATE, serverId, channel })
- const contract = communityProducerContract(getCloudflareContext().env as Env)
- const event = contract === 3
- ? CommunityResourceWsEventSchema.parse({ type: WS_EVENTS.CHANNEL_CREATE, serverId, channel: communityChannelResourceFromStorage(row) })
- : {
- type: WS_EVENTS.CHANNEL_CREATE,
- serverId,
- channel,
- }
if (isPrivateCategory) {
await fanOutToChannel(row.id, event)
} else {
@@ -270,22 +255,13 @@ export async function createThreadForUser(
if (!threadResult.ok) return { ok: false, status: 404, error: "thread not found" }
const childChannel = threadResult.value
if (createdByThisAttempt) {
- const contract = communityProducerContract(getCloudflareContext().env as Env)
const event = {
type: WS_EVENTS.CHILD_CHANNEL_CREATE,
parentChannelId: message.channelId,
- channel: contract === 3 ? communityChannelResourceFromStorage(childChannel) : {
- id: childChannel.id,
- name: childChannel.name,
- type: "thread" as const,
- creatorId: actorUserId,
- createdAt: childChannel.createdAt,
- },
+ channel: communityChannelResourceFromStorage(childChannel),
parentMessageId: messageId,
}
- void fanOutToChannel(message.channelId, contract === 3 ? CommunityResourceWsEventSchema.parse(event) : {
- ...event, channel: { id: childChannel.id, name: childChannel.name, type: "thread", creatorId: actorUserId, createdAt: childChannel.createdAt },
- })
+ void fanOutToChannel(message.channelId, CommunityResourceWsEventSchema.parse(event))
}
return { ok: true, value: childChannel }
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 2034c8951..2473c4073 100644
--- a/src/web/src/lib/community/desktop-system-notification.test.ts
+++ b/src/web/src/lib/community/desktop-system-notification.test.ts
@@ -1,3 +1,4 @@
+import { serverRailResponseFixture } from "@/test/community-resource-fixtures"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { afterEach, describe, expect, it, vi } from "vitest"
import type { CommunityMessageCreate, CommunityWsEvent } from "@alook/shared"
@@ -105,7 +106,7 @@ async function createClient() {
}
function seedCanonicalDirectory(queryClient: QueryClient, options: { channels?: boolean } = {}) {
const registry = getCommunityDbRegistry(queryClient)!
- ingestServers(registry, { servers: serverRows })
+ ingestServers(registry, serverRailResponseFixture({ servers: serverRows }, (registry)!.accountId))
if (options.channels !== false) {
for (const channel of channelRows) publishCommunityCreatedChannel(queryClient, channel, { token: captureCommunityLiveSnapshotToken(queryClient), signal: undefined })
}
diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.ts
index dd8c02019..1b6a20c9e 100644
--- a/src/web/src/lib/community/enrich-messages.test.ts
+++ b/src/web/src/lib/community/enrich-messages.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { beforeEach, describe, expect, it, vi } from "vitest"
const mocks = vi.hoisted(() => ({
@@ -21,6 +22,7 @@ vi.mock("@alook/shared", async () => {
withD1Retry: (operation: () => unknown) => operation(),
queries: {
...actual.queries,
+ communityUserProfile: { ...actual.queries.communityUserProfile, getResourceProfiles: async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: id, discriminator: "0042", avatar: null, avatarVersion: 0 })) },
communityAttachment: {
...actual.queries.communityAttachment,
listByMessageIds: (...args: unknown[]) => mocks.listAttachments(...args),
@@ -76,7 +78,7 @@ describe("enrichMessages attachment projection", () => {
it("skips empty DM attachment, reaction, reply and approval hydration while reading latest sequence", async () => {
const db = {} as never
- expect(await enrichMessages(db, "u1", { channelId: "dm1", isDm: true }, [])).toEqual({ messages: [], latestSeq: 9 })
+ expect(await enrichMessages(db, "u1", { channelId: "dm1", isDm: true }, [])).toEqual({ messages: [], profiles: [], latestSeq: 9 })
expect(mocks.listAttachments).not.toHaveBeenCalled()
expect(mocks.listReactions).not.toHaveBeenCalled()
expect(mocks.getReplies).not.toHaveBeenCalled()
@@ -124,6 +126,7 @@ describe("enrichMessages attachment projection", () => {
}])
mocks.getReplies.mockResolvedValue([{
id: "reply_1",
+ authorId: "bob",
authorName: "Bob",
content: "original",
channelId: "c1",
@@ -151,9 +154,9 @@ describe("enrichMessages attachment projection", () => {
expect(result.messages).toEqual([
expect.objectContaining({
- replyTo: { id: "reply_1", authorName: "Bob", text: "original" },
+ replyTo: { id: "reply_1", authorId: "bob", authorName: "Bob", text: "original" },
attachments: [{
- kind: "image",
+ id: "att_1",
name: "photo.png",
url: "/api/community/channels/c1/attachments/att_1",
contentType: "image/png",
@@ -226,7 +229,7 @@ describe("enrichMessages attachment projection", () => {
})
})
- it("falls back to initials for forum participants without an avatar", async () => {
+ it("preserves a null resource avatar for forum participants without an image", async () => {
mocks.listAttachments.mockResolvedValue([])
mocks.getReplies.mockResolvedValue([])
mocks.listForumChildren.mockResolvedValue([{
@@ -272,21 +275,21 @@ describe("enrichMessages attachment projection", () => {
thread: {
participants: [{
id: "u2",
- avatar: "B",
+ avatar: null,
avatarVersion: 0,
}],
},
})
})
- it("keeps actual NULL thread facts in contract 3 and rejects unknown participant identity", async () => {
+ it("keeps actual NULL thread facts in the current contract and rejects unknown participant identity", async () => {
mocks.listAttachments.mockResolvedValue([])
mocks.listForumChildren.mockResolvedValue([{ id: "thread", parentMessageId: "m1", name: null, messageCount: 0, lastMessageAt: null, createdAt: "now" }])
mocks.listParticipants.mockResolvedValue([{ channelId: "thread", userId: "peer", userName: "Peer", userImage: null, userAvatarVersion: 4, participantCount: 1 }])
const row = { id: "m1", channelId: "forum", seq: 1, authorId: "author", authorName: "Author", authorImage: null, authorAvatarVersion: 2, content: "body", type: "default", mentionType: null, replyToId: null, embeds: null, createdAt: "now" }
- const result = await enrichMessages({} as never, "viewer", { channelId: "forum", isForum: true, contract: 3 }, [row])
+ const result = await enrichMessages({} as never, "viewer", { channelId: "forum", isForum: true, contract: BUSINESS_SCHEMA_VERSION }, [row])
expect(result.messages[0]).toMatchObject({ authorAvatar: null, thread: { name: null, messageCount: 0, lastReplyAt: null, participants: [{ id: "peer", name: "Peer", avatar: null, avatarVersion: 4 }] } })
mocks.listParticipants.mockResolvedValue([{ channelId: "thread", userId: "peer", userName: null, userImage: null, userAvatarVersion: 4 }])
- await expect(enrichMessages({} as never, "viewer", { channelId: "forum", isForum: true, contract: 3 }, [row])).rejects.toThrow()
+ await expect(enrichMessages({} as never, "viewer", { channelId: "forum", isForum: true, contract: BUSINESS_SCHEMA_VERSION }, [row])).rejects.toThrow()
})
})
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index 14e3a91d3..b59233062 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -1,7 +1,6 @@
-import { queries, withD1Retry, CommunityChannelResourceSchema, CommunityMessageThreadParticipantSchema, type CommunityMessageResource, type CommunityContract } from "@alook/shared"
+import { queries, withD1Retry, CommunityChannelResourceSchema, CommunityMessageThreadParticipantSchema, type CommunityMessageResource, type CommunityResourceProfile, type CommunityContract } from "@alook/shared"
import type { getDb } from "@/lib/db"
-import { loadApiMessageContext, mapMessageForApi } from "@/lib/community/message-payload"
-import { avatarInitial } from "@/lib/community/avatar"
+import { loadApiMessageContext, mapMessageForApi, readCommunityMessageProfiles } from "@/lib/community/message-payload"
import { canonicalUserImage } from "@/lib/community/storage"
// Message enrichment shared by the channel messages route, the channel
@@ -23,7 +22,7 @@ export async function enrichMessages(
userId: string,
scope: MessageScope,
items: Array<Parameters<typeof mapMessageForApi>[0] & { channelId: string }>,
-): Promise<{ messages: unknown[]; latestSeq: number }> {
+): Promise<{ messages: CommunityMessageResource[]; profiles: CommunityResourceProfile[]; latestSeq: number }> {
const isDm = scope.isDm === true
const messageIds = items.map((m) => m.id)
const creationMessageIds = items.filter((message) => message.type === "bot_creation_request").map((message) => message.id)
@@ -79,9 +78,8 @@ export async function enrichMessages(
...(participantsByChannel.get(row.channelId) ?? []),
{
id: row.userId,
- name: scope.contract === 3 ? CommunityMessageThreadParticipantSchema.shape.name.parse(row.userName) : row.userName ?? "",
- avatar: scope.contract === 3 ? canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion)
- : canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion) ?? avatarInitial(row.userName ?? ""),
+ name: CommunityMessageThreadParticipantSchema.shape.name.parse(row.userName),
+ avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion),
avatarVersion: row.userAvatarVersion,
},
])
@@ -95,8 +93,8 @@ export async function enrichMessages(
return [c.parentMessageId!, {
id: c.id,
name: c.name,
- messageCount: scope.contract === 3 ? CommunityChannelResourceSchema.shape.messageCount.parse(c.messageCount) : c.messageCount ?? 0,
- lastReplyAt: scope.contract === 3 ? c.lastMessageAt : c.lastMessageAt ?? c.createdAt,
+ messageCount: CommunityChannelResourceSchema.shape.messageCount.parse(c.messageCount),
+ lastReplyAt: c.lastMessageAt,
...(scope.isForum ? {
tags: tagsByMessage.get(c.parentMessageId!) ?? [],
preview: first?.content ?? "",
@@ -115,5 +113,5 @@ export async function enrichMessages(
approvalByMessageId: approvalByMessageId as Map<string, import("@alook/shared").FriendApprovalPayload>,
}, scope.contract, scope.channelId),
)
- return { messages, latestSeq }
+ return { messages, profiles: await readCommunityMessageProfiles(db, messages), latestSeq }
}
diff --git a/src/web/src/lib/community/forum-sidebar-window.ts b/src/web/src/lib/community/forum-sidebar-window.ts
index bdfedb167..0aeb78ad9 100644
--- a/src/web/src/lib/community/forum-sidebar-window.ts
+++ b/src/web/src/lib/community/forum-sidebar-window.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { readServerDirectoryWindow, type ServerDirectoryWindow } from "./server-directory-window"
import { z } from "zod"
import { projectForumSidebar, supportsSidebarThreads } from "./forum-sidebar"
import type { CommunityCollectionRows } from "@/lib/community-db/schema"
@@ -11,13 +13,13 @@ const resultSchema = z.object({
serverNow: z.string().refine(value => Number.isFinite(Date.parse(value))),
serverClockOffsetMs: z.number(),
window: z.object({
- version: z.literal(1), accountId: z.string().min(1), serverId: z.string().min(1),
+ version: z.literal(BUSINESS_SCHEMA_VERSION), accountId: z.string().min(1), serverId: z.string().min(1),
parents: z.array(z.string().min(1)), base: z.array(referenceSchema), retained: retainedSchema.nullable(),
}),
})
export type ForumSidebarWindow = z.infer<typeof resultSchema>["window"]
type WindowRows = Pick<CommunityCollectionRows, "servers" | "channels" | "channelMemberships" | "messages">
-type ForumSidebarWindowRows = { [N in keyof WindowRows]: readonly WindowRows[N][] }
+type ForumSidebarWindowRows = { [N in keyof WindowRows]: readonly WindowRows[N][] } & { directory?: ServerDirectoryWindow }
export function isForumSidebarWindowKey(key: readonly unknown[]): boolean {
return key.length === 4 && key[0] === "community" && key[1] === "servers" && typeof key[2] === "string" && key[3] === "forum-sidebar-base"
@@ -39,10 +41,13 @@ export function readForumSidebarWindowResult(data: unknown) {
export function forumSidebarWindowComplete(
window: ForumSidebarWindow, rows: ForumSidebarWindowRows, accountId: string | null, serverId: string, retainId?: string | null, serverNowMs = Date.now(),
) {
+ const directory = readServerDirectoryWindow(rows.directory)
if (window.accountId !== accountId || window.serverId !== serverId
- || !rows.servers.some(row => row.id === serverId && row.detailComplete)) return false
+ || !directory || directory.accountId !== accountId || directory.serverId !== serverId
+ || !rows.servers.some(row => row.id === serverId)) return false
const parents = rows.channels.filter(row => row.serverId === serverId && supportsSidebarThreads(row.type))
- if (window.parents.some(id => !parents.some(row => row.id === id)) || parents.some(row => !window.parents.includes(row.id))) return false
+ if (window.parents.some(id => !directory.channelIds.includes(id) || !parents.some(row => row.id === id))
+ || parents.some(row => !window.parents.includes(row.id))) return false
const visible = projectForumSidebar(rows.channels, rows.channelMemberships, rows.messages, accountId, serverId,
retainId ?? (window.retained?.disposition === "eligible" ? window.retained.id : null), serverNowMs).threads
const references = [...window.base, ...(window.retained?.disposition === "eligible" ? [window.retained.reference] : []), ...visible]
diff --git a/src/web/src/lib/community/forum-sidebar.ts b/src/web/src/lib/community/forum-sidebar.ts
index 8f6009e0a..5a6d4e1e2 100644
--- a/src/web/src/lib/community/forum-sidebar.ts
+++ b/src/web/src/lib/community/forum-sidebar.ts
@@ -19,6 +19,10 @@ export function viewerNotifyChannelIds(memberships: readonly ChannelMembershipRo
return new Set(memberships.filter((row) => row.relation === "notify" && row.userId === viewerId).map((row) => row.channelId))
}
+export function forumSidebarActivityAt(channel: Pick<ChannelRow, "lastMessageAt" | "createdAt">) {
+ return channel.lastMessageAt ?? channel.createdAt
+}
+
export function compareForumSidebarThreads(left: ForumSidebarThread, right: ForumSidebarThread) {
return compareAsciiSqliteBinary(left.parentChannelId, right.parentChannelId)
|| compareAsciiSqliteBinary(right.activityAt, left.activityAt)
@@ -37,7 +41,7 @@ export function forumSidebarCandidates(
if (channel.serverId !== serverId || channel.type !== "thread" || channel.archived
|| channel.tags.includes(FORUM_ARCHIVE_TAG) || !participating.has(channel.id)
|| !channel.parentChannelId || !parentIds.has(channel.parentChannelId) || !channel.parentMessageId) return []
- const activityAt = channel.lastMessageAt ?? "", activityMs = Date.parse(activityAt)
+ const activityAt = forumSidebarActivityAt(channel), activityMs = Date.parse(activityAt)
const expiresAt = Number.isFinite(activityMs) ? new Date(activityMs + FORUM_SIDEBAR_ACTIVITY_WINDOW_MS).toISOString() : activityAt
return [{ id: channel.id, parentChannelId: channel.parentChannelId, parentMessageId: channel.parentMessageId,
title: messageById.get(channel.parentMessageId)?.content ?? channel.name ?? "", activityAt, expiresAt, unread: attention.some((scope) => scope.scopeId === channel.id && (scope.ordinaryUnread || scope.attentionCount > 0)) }]
diff --git a/src/web/src/lib/community/friend-read.resources.dom.test.ts b/src/web/src/lib/community/friend-read.resources.dom.test.ts
new file mode 100644
index 000000000..2ca92707e
--- /dev/null
+++ b/src/web/src/lib/community/friend-read.resources.dom.test.ts
@@ -0,0 +1,113 @@
+import { act } from "@/test/react-dom-harness"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityAcceptedFriendsReadSchema, CommunityBlockedFriendsReadSchema, CommunityPendingFriendsReadSchema } from "@alook/shared"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { communityKeys } from "@/lib/query-keys"
+
+const mocks = vi.hoisted(() => ({ accepted: vi.fn(), blocked: vi.fn(), pending: vi.fn(), users: vi.fn(), profiles: vi.fn(), api: vi.fn(), db: {} }))
+vi.mock("@/lib/db", () => ({ getDb: () => mocks.db }))
+vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (request: NextRequest, context: unknown) => Promise<Response>) => (request: NextRequest) => handler(request, { actor: { kind: "human", userId: "viewer" }, env: { DB: mocks.db } }), rejectBot: () => null }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => mocks.api(...args) }))
+vi.mock("@alook/shared", async original => {
+ const actual = await original<typeof import("@alook/shared")>()
+ return { ...actual, queries: { ...actual.queries,
+ communityFriendship: { ...actual.queries.communityFriendship, listFriends: (...args: unknown[]) => mocks.accepted(...args), listBlocked: (...args: unknown[]) => mocks.blocked(...args), listPending: (...args: unknown[]) => mocks.pending(...args) },
+ communityMessage: { ...actual.queries.communityMessage, getMessagesByIdsInChannels: vi.fn(async () => []) },
+ communityChannel: { ...actual.queries.communityChannel, listChannelMembershipsForUserInChannels: vi.fn(async () => []) },
+ user: { ...actual.queries.user, getUsersByIds: (...args: unknown[]) => mocks.users(...args) },
+ communityUserProfile: { ...actual.queries.communityUserProfile, getProfilesByUserIds: (...args: unknown[]) => mocks.profiles(...args), getResourceProfiles: async (db: unknown, ids: string[]) => {
+ const users = await mocks.users(db, ids)
+ const rows = new Map((await mocks.profiles(db, users.map((row: { id: string }) => row.id))).map((row: { userId: string }) => [row.userId, row]))
+ return users.map((row: { id: string; name: string; discriminator: string; image: string | null; avatarVersion: number }) => actual.CommunityResourceProfileSchema.parse({ id: row.id, name: row.name, discriminator: row.discriminator, avatar: actual.canonicalCommunityUserImage(row.id, row.image, row.avatarVersion), avatarVersion: row.avatarVersion,
+ ...(rows.has(row.id) ? Object.fromEntries(Object.entries(rows.get(row.id) as object).filter(([key]) => key !== "userId")) : {}) }))
+ } },
+ } }
+})
+import { GET as accepted } from "@/app/api/community/friends/accepted/route"
+import { GET as blocked } from "@/app/api/community/friends/blocked/route"
+import { GET as pending } from "@/app/api/community/friends/pending/route"
+import { friendsQueryFn } from "@/hooks/community/use-friends"
+const request = (bucket: string) => new NextRequest(`https://alook.test/api/community/friends/${bucket}`, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.accepted.mockResolvedValue([{ id: "accepted-row", friendUserId: "accepted-peer", friendName: "Stale joined hint", friendImage: null, friendAvatarVersion: 0 }])
+ mocks.blocked.mockResolvedValue([{ id: "blocked-row", blockedUserId: "blocked-peer", blockedName: "Stale joined hint" }])
+ mocks.pending.mockResolvedValue([{ id: "pending-row", userId: "pending-peer", name: "Stale joined hint", kind: "outgoing", needsOwnerApproval: "viewer" }])
+ mocks.users.mockImplementation(async (_db, ids: string[]) => ids.map(id => ({ id, name: `Full ${id}`, discriminator: "0042", image: null, avatarVersion: 4 })))
+ mocks.profiles.mockImplementation(async (_db, ids: string[]) => ids.map(userId => ({ userId, aboutMe: "About", bannerColor: null, statusEmoji: "🎧", statusText: "Listening" })))
+ mocks.api.mockImplementation(async (path: string, options: { authenticationAccount?: string }) => {
+ expect(options.authenticationAccount).toBe("viewer")
+ const bucket = path.split("/").at(-1)!
+ const handler = { accepted, blocked, pending }[bucket as "accepted" | "blocked" | "pending"]
+ if (!handler) throw new Error(`Unexpected friend transport ${path}`)
+ const response = await handler(request(bucket))
+ expect(response.status).toBe(200)
+ return JSON.parse(await response.text())
+ })
+})
+
+describe("real current human friend producers to the query owner", () => {
+ it("publishes only resource identity and separate accepted/pending/blocked relation facts", async () => {
+ const owner = await createCommunityQueryOwner()
+ await act(async () => { await owner.client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn }) })
+ expect([...owner.registry.collections.friendships.values()]).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: "accepted-row", userId: "accepted-peer", kind: "accepted", sub: "" }),
+ expect.objectContaining({ id: "pending-row", userId: "pending-peer", kind: "outgoing", needsOwnerApproval: "viewer" }),
+ expect.objectContaining({ id: "blocked:blocked-peer", userId: "blocked-peer", kind: "blocked" }),
+ ]))
+ expect(owner.registry.collections.profiles.get("accepted-peer")).toMatchObject({ name: "Full accepted-peer", avatarVersion: 4, statusEmoji: "🎧", statusText: "Listening" })
+ expect(owner.registry.collections.profiles.has("accepted-row")).toBe(false)
+ for (const fn of [mocks.accepted, mocks.blocked, mocks.pending]) expect(fn).toHaveBeenCalledExactlyOnceWith(mocks.db, "viewer")
+ expect(mocks.users).toHaveBeenCalledWith(mocks.db, ["viewer", "accepted-peer"])
+ expect(mocks.api).toHaveBeenCalledTimes(3)
+ for (const [bucket, handler, schema] of [["accepted", accepted, CommunityAcceptedFriendsReadSchema], ["blocked", blocked, CommunityBlockedFriendsReadSchema], ["pending", pending, CommunityPendingFriendsReadSchema]] as const) {
+ const body = schema.parse(await (await handler(request(bucket))).json())
+ const field = bucket === "accepted" ? "friends" : bucket
+ for (const row of (body as unknown as Record<string, Array<Record<string, unknown>>>)[field]!) {
+ expect(row).not.toHaveProperty("name"); expect(row).not.toHaveProperty("avatar"); expect(row).not.toHaveProperty("avatarVersion")
+ }
+ }
+ })
+ it("rejects a missing requested peer resource at the real producer before query publication", async () => {
+ mocks.users.mockImplementation(async () => [{ id: "viewer", name: "Viewer", discriminator: "0001", image: null, avatarVersion: 0 }])
+ const owner = await createCommunityQueryOwner()
+ await expect(owner.client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn, retry: false })).rejects.toThrow()
+ expect([...owner.registry.collections.friendships.values()]).toEqual([])
+ expect([...owner.registry.collections.profiles.values()]).toEqual([])
+ })
+ it.each(["accepted", "blocked", "pending"] as const)("preserves a previous good relationship/profile projection on a stale %s producer", async bucket => {
+ const owner = await createCommunityQueryOwner()
+ await owner.client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn })
+ const previous = owner.registry.collections.friendships.get("accepted-row")
+ mocks[bucket].mockRejectedValue(new Error("D1_ERROR: database is locked"))
+ const handler = { accepted, blocked, pending }[bucket]
+ const response = await handler(request(bucket))
+ const schema = { accepted: CommunityAcceptedFriendsReadSchema, blocked: CommunityBlockedFriendsReadSchema, pending: CommunityPendingFriendsReadSchema }[bucket]
+ expect(schema.parse(await response.json())).toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, [bucket === "accepted" ? "friends" : bucket]: [], stale: true })
+ await expect(owner.client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn, staleTime: 0, retry: false })).rejects.toThrow("stale D1 read")
+ expect(owner.registry.collections.friendships.get("accepted-row")).toMatchObject({ id: previous!.id, userId: previous!.userId, kind: "accepted" })
+ expect(owner.registry.collections.profiles.get("accepted-peer")?.name).toBe("Full accepted-peer")
+ })
+ it.each(["accepted", "blocked", "pending"].flatMap(bucket => ["users", "profiles"].map(query => ({ bucket: bucket as "accepted" | "blocked" | "pending", query: query as "users" | "profiles" }))))("returns named stale after $bucket full resource $query BUSY exhaustion", async ({ bucket, query }) => {
+ const owner = await createCommunityQueryOwner()
+ await owner.client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn })
+ mocks[query].mockRejectedValue(new Error("D1_ERROR: database is locked"))
+ const handler = { accepted, blocked, pending }[bucket]
+ const schema = { accepted: CommunityAcceptedFriendsReadSchema, blocked: CommunityBlockedFriendsReadSchema, pending: CommunityPendingFriendsReadSchema }[bucket]
+ const response = await handler(request(bucket))
+ expect(schema.parse(await response.json())).toEqual({ contractVersion: BUSINESS_SCHEMA_VERSION, [bucket === "accepted" ? "friends" : bucket]: [], stale: true })
+ await expect(owner.client.query({ queryKey: communityKeys.friends(), queryFn: friendsQueryFn, staleTime: 0, retry: false })).rejects.toThrow("stale D1 read")
+ expect(owner.registry.collections.friendships.get("accepted-row")).toMatchObject({ userId: "accepted-peer", kind: "accepted" })
+ expect(owner.registry.collections.profiles.get("accepted-peer")?.name).toBe("Full accepted-peer")
+ })
+
+ it.each(["accepted", "blocked", "pending"].flatMap(bucket => ["users", "profiles"].map(query => ({ bucket: bucket as "accepted" | "blocked" | "pending", query: query as "users" | "profiles" }))))("rethrows $bucket full resource $query non-BUSY errors", async ({ bucket, query }) => {
+ const error = new Error("controlled programming failure")
+ mocks[query].mockRejectedValue(error)
+ const handler = { accepted, blocked, pending }[bucket]
+ await expect(handler(request(bucket))).rejects.toBe(error)
+ expect(mocks[query]).toHaveBeenCalledOnce()
+ })
+
+})
diff --git a/src/web/src/lib/community/funnel-analytics.test.ts b/src/web/src/lib/community/funnel-analytics.test.ts
index e9c5aeeb6..39699608f 100644
--- a/src/web/src/lib/community/funnel-analytics.test.ts
+++ b/src/web/src/lib/community/funnel-analytics.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
const mocks = vi.hoisted(() => ({
@@ -15,7 +16,7 @@ vi.mock("@/lib/analytics", () => ({
trackInvitedHumanJoined: mocks.joined,
}))
-vi.mock("@alook/shared", () => ({ isTauri: () => mocks.native }))
+vi.mock("@alook/shared", async (importOriginal) => ({ ...await importOriginal<typeof import("@alook/shared")>(), isTauri: () => mocks.native }))
vi.mock("@/lib/analytics-consent", () => ({ readAnalyticsConsent: () => mocks.consent }))
vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.product }))
import { createStore } from "@tanstack/store"
@@ -28,7 +29,7 @@ import {
} from "./funnel-analytics"
function response(payload: unknown, ok = true) {
- return { ok, json: vi.fn().mockResolvedValue(payload) } as unknown as Response
+ return Response.json(payload, { status: ok ? 200 : 500, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
}
describe("Community funnel analytics drain", () => {
@@ -74,6 +75,7 @@ describe("Community funnel analytics drain", () => {
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(fetchMock).toHaveBeenNthCalledWith(1, "/api/community/analytics/funnel-events", {
method: "POST",
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
cache: "no-store",
credentials: "same-origin",
})
@@ -185,3 +187,22 @@ it("does not claim a browser event without a browser", async () => {
expect(fetchMock).not.toHaveBeenCalled()
} finally { vi.unstubAllGlobals() }
})
+
+
+describe("current funnel response qualification", () => {
+ afterEach(() => vi.unstubAllGlobals())
+ it.each([null, BUSINESS_SCHEMA_VERSION - 1, BUSINESS_SCHEMA_VERSION + 1])("drops unconfirmed optional receipts (%s) without global upgrade", async version => {
+ vi.clearAllMocks(); _resetCommunityFunnelAnalyticsForTesting()
+ mocks.native = false; mocks.consent = null; vi.stubGlobal("window", {})
+ const create = () => Response.json({ events: [{ event: "invited_human_joined", surface: "community" }, { event: "runtime_connected", surface: "community", connection_type: "local_daemon" }] }, { headers: version === null ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(version) } })
+ const fetchMock = vi.fn(async () => create()); vi.stubGlobal("fetch", fetchMock)
+ const { businessSchemaLifecycle } = await import("@/lib/business-schema-lifecycle")
+ businessSchemaLifecycle.setState(() => ({ phase: "current", expectedVersion: BUSINESS_SCHEMA_VERSION }))
+ await drainCommunityFunnelEvents()
+ await drainInvitedHumanJoined(createStore({ active: true, generation: 1 }))
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ for (const [, options] of fetchMock.mock.calls as unknown as Array<[string, RequestInit]>) expect(new Headers(options.headers).get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(mocks.product).not.toHaveBeenCalled(); expect(mocks.runtime).not.toHaveBeenCalled()
+ expect(businessSchemaLifecycle.get().phase).toBe("current")
+ })
+})
diff --git a/src/web/src/lib/community/funnel-analytics.ts b/src/web/src/lib/community/funnel-analytics.ts
index 9e94058d8..3e6a385de 100644
--- a/src/web/src/lib/community/funnel-analytics.ts
+++ b/src/web/src/lib/community/funnel-analytics.ts
@@ -1,6 +1,6 @@
"use client"
-import { isTauri, type CommunityFunnelAnalyticsEvent } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION, isTauri, type CommunityFunnelAnalyticsEvent } from "@alook/shared"
import { readAnalyticsConsent } from "@/lib/analytics-consent"
import { captureProductAnalytics } from "@/lib/product-analytics"
import type { CommunityRuntime } from "@/stores/community/runtime"
@@ -70,10 +70,11 @@ function publishCommunityFunnelEvent(event: CommunityFunnelAnalyticsEvent) {
async function drainOnce() {
const response = await fetch("/api/community/analytics/funnel-events", {
method: "POST",
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
cache: "no-store",
credentials: "same-origin",
})
- if (!response.ok) return
+ if (!response.ok || response.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) return
const payload: unknown = await response.json()
for (const event of decodeCommunityFunnelEvents(payload)) {
publishCommunityFunnelEvent(event)
@@ -136,12 +137,13 @@ export function drainInvitedHumanJoined(lifecycle: Lifecycle): Promise<void> {
assertCurrent()
const response = await fetch("/api/community/analytics/funnel-events?event=invited_human_joined", {
method: "POST",
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
cache: "no-store",
credentials: "same-origin",
signal: controller.signal,
})
assertCurrent()
- if (!response.ok) return
+ if (!response.ok || response.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) return
const payload: unknown = await response.json()
assertCurrent()
for (const event of decodeCommunityFunnelEvents(payload)) {
diff --git a/src/web/src/lib/community/invite-read.resources.dom.test.ts b/src/web/src/lib/community/invite-read.resources.dom.test.ts
new file mode 100644
index 000000000..fde123ae9
--- /dev/null
+++ b/src/web/src/lib/community/invite-read.resources.dom.test.ts
@@ -0,0 +1,140 @@
+import { CancelledError } from "@tanstack/react-query"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, CommunityInvitesReadSchema } from "@alook/shared"
+import { communityKeys } from "@/lib/query-keys"
+import { invitesReadFixture } from "@/test/community-resource-fixtures"
+import { retireCommunityAccount } from "@/lib/community/account-cache-lifecycle"
+import { projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import { beforeEach, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { createElement, type PropsWithChildren } from "react"
+import { renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+
+const mocks = vi.hoisted(() => ({ list: vi.fn(), users: vi.fn(), profiles: vi.fn(), servers: vi.fn(), api: vi.fn(), member: vi.fn(), db: {} }))
+vi.mock("@/lib/db", () => ({ getDb: () => mocks.db }))
+vi.mock("@/lib/middleware/auth", () => ({ withAuth: (handler: (request: NextRequest, context: unknown) => Promise<Response>) => (request: NextRequest) => handler(request, { userId: "viewer", env: { DB: mocks.db }, params: { id: "s1" } }) }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => mocks.api(...args) }))
+vi.mock("@alook/shared", async original => {
+ const actual = await original<typeof import("@alook/shared")>()
+ return { ...actual, queries: { ...actual.queries,
+ communityInvite: { ...actual.queries.communityInvite, listServerInvites: (...args: unknown[]) => mocks.list(...args) },
+ communityMember: { ...actual.queries.communityMember, getMember: (...args: unknown[]) => mocks.member(...args) },
+ communityMessage: { ...actual.queries.communityMessage, getMessagesByIdsInChannels: vi.fn(async () => []) },
+ communityChannel: { ...actual.queries.communityChannel, listChannelMembershipsForUserInChannels: vi.fn(async () => []) },
+ communityServer: { ...actual.queries.communityServer, listUserServers: (...args: unknown[]) => mocks.servers(...args) },
+ user: { ...actual.queries.user, getUsersByIds: (...args: unknown[]) => mocks.users(...args) },
+ communityUserProfile: { ...actual.queries.communityUserProfile, getProfilesByUserIds: (...args: unknown[]) => mocks.profiles(...args), getResourceProfiles: async (db: unknown, ids: string[]) => {
+ const users = await mocks.users(db, ids)
+ const rows = new Map((await mocks.profiles(db, users.map((row: { id: string }) => row.id))).map((row: { userId: string }) => [row.userId, row]))
+ return users.map((row: { id: string; name: string; discriminator: string; image: string | null; avatarVersion: number }) => actual.CommunityResourceProfileSchema.parse({ id: row.id, name: row.name, discriminator: row.discriminator, avatar: actual.canonicalCommunityUserImage(row.id, row.image, row.avatarVersion), avatarVersion: row.avatarVersion,
+ ...(rows.has(row.id) ? Object.fromEntries(Object.entries(rows.get(row.id) as object).filter(([key]) => key !== "userId")) : {}) }))
+ } },
+ } }
+})
+import { GET } from "@/app/api/community/servers/[id]/invites/route"
+import { invitesQueryFn, useInvites } from "@/hooks/community/use-server-panels"
+const request = () => new NextRequest("https://alook.test/api/community/servers/s1/invites")
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.member.mockResolvedValue({ id: "member-viewer", role: "member" })
+ mocks.list.mockResolvedValue([{ id: "invite", serverId: "s1", token: "token", uses: 0, maxUses: null, expiresAt: null, createdAt: "2026-10-01T00:00:00Z", creatorId: "creator", creatorName: "Alice", creatorEmail: "[email protected]", creatorImage: null, creatorAvatarVersion: 2 }])
+ mocks.users.mockImplementation(async (_db, ids: string[]) => ids.map(id => ({ id, name: id === "creator" ? "Alice" : "Viewer", discriminator: "0042", image: null, avatarVersion: 2 })))
+ mocks.profiles.mockImplementation(async (_db, ids: string[]) => ids.map(userId => ({ userId, aboutMe: "About", bannerColor: null, statusEmoji: null, statusText: null })))
+ mocks.servers.mockResolvedValue([{ id: "s1", name: "Server", discriminator: "0042", description: "", ownerId: "owner", icon: null, official: false, role: "member", memberId: "member-viewer" }])
+ mocks.api.mockImplementation(async (path: string, options: { authenticationAccount?: string }) => {
+ expect(path).toBe("/api/community/servers/s1/invites")
+ expect(options.authenticationAccount).toBe("viewer")
+ const response = await GET(request())
+ expect(response.status).toBe(200)
+ return response.json()
+ })
+})
+it("publishes a cold real creator profile and renders the creator name through the actual invite query", async () => {
+ const owner = await createCommunityQueryOwner()
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
+ const hook = renderHook(() => useInvites("s1"), { wrapper })
+ try {
+ await waitFor(() => expect(hook.result.current.isSuccess).toBe(true))
+ expect(hook.result.current.invites[0]?.by).toBe("Alice")
+ expect(owner.registry.collections.profiles.get("creator")).toMatchObject({ name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 2 })
+ } finally { hook.unmount(); await owner.registry.cleanup(); owner.client.clear() }
+})
+
+it("produces scoped descriptors with full resources and no creator email or second identity", async () => {
+ const response = await GET(request())
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const data = CommunityInvitesReadSchema.parse(await response.json())
+ expect(data.invites).toEqual([{ id: "invite", token: "token", uses: 0, maxUses: null, expiresAt: null, createdAt: "2026-10-01T00:00:00Z", creatorId: "creator" }])
+ expect(data.resources.profiles.find(row => row.id === "creator")).toMatchObject({ name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 2, aboutMe: "About" })
+ expect(JSON.stringify(data)).not.toContain("[email protected]")
+ expect(mocks.member).toHaveBeenCalledExactlyOnceWith(mocks.db, "s1", "viewer")
+ expect(mocks.list).toHaveBeenCalledExactlyOnceWith(mocks.db, "s1")
+ expect(mocks.users).toHaveBeenCalledExactlyOnceWith(mocks.db, ["viewer", "creator"])
+ expect(mocks.servers).toHaveBeenCalledExactlyOnceWith(mocks.db, "viewer")
+})
+it("retains an explicitly null deleted creator without a fabricated profile", async () => {
+ const rows = await mocks.list()
+ mocks.list.mockResolvedValue([{ ...rows[0], creatorId: null, creatorName: null }])
+ const data = CommunityInvitesReadSchema.parse(await (await GET(request())).json())
+ expect(data.invites[0].creatorId).toBeNull()
+ expect(data.resources.profiles.map(row => row.id)).toEqual(["viewer"])
+})
+it("gates membership before reading invite or creator resources", async () => {
+ mocks.member.mockResolvedValue(null)
+ expect((await GET(request())).status).toBe(403)
+ expect(mocks.list).not.toHaveBeenCalled()
+ expect(mocks.users).not.toHaveBeenCalled()
+})
+it("rejects a missing creator full resource without publishing the descriptor", async () => {
+ mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", discriminator: "0042", image: null, avatarVersion: 2 }])
+ const owner = await createCommunityQueryOwner()
+ try {
+ await expect(owner.client.query({ queryKey: communityKeys.invites("s1"), queryFn: invitesQueryFn("s1"), retry: false })).rejects.toThrow("Invite creator profile resource missing")
+ expect(owner.registry.collections.profiles.size).toBe(0)
+ } finally { await owner.registry.cleanup(); owner.client.clear() }
+})
+it.each(["list", "users", "profiles"] as const)("propagates original %s errors without a false empty result", async query => {
+ const failure = new Error("unavailable")
+ mocks[query].mockRejectedValue(failure)
+ await expect(GET(request())).rejects.toBe(failure)
+})
+const item = { id: "invite", token: "token", uses: 0, maxUses: null, expiresAt: null, createdAt: "now", creatorId: "creator" }
+const creator = { id: "creator", name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 2 }
+it.each(["missing core", "missing creator", "old version", "wrong viewer", "wrong server", "duplicate summary"] as const)("rejects raw %s before any canonical profile publication", async variant => {
+ const data = invitesReadFixture(variant === "wrong server" ? "foreign" : "s1", [item], [creator], variant === "wrong viewer" ? "foreign" : "viewer")
+ const raw = structuredClone(data)
+ if (variant === "missing core") Reflect.deleteProperty(raw.resources.profiles[0], "avatar")
+ if (variant === "missing creator") raw.resources.profiles = []
+ if (variant === "old version") Reflect.set(raw, "contractVersion", BUSINESS_SCHEMA_VERSION - 1)
+ if (variant === "duplicate summary") Reflect.set(raw.invites[0], "creatorName", "Untrusted")
+ mocks.api.mockResolvedValue(raw)
+ const owner = await createCommunityQueryOwner()
+ try {
+ await expect(owner.client.query({ queryKey: communityKeys.invites("s1"), queryFn: invitesQueryFn("s1"), retry: false })).rejects.toThrow()
+ expect(owner.registry.collections.profiles.size).toBe(0)
+ } finally { await owner.registry.cleanup(); owner.client.clear() }
+})
+it.each(["retired owner", "newer identity"] as const)("preserves the originating owner and field revision after a held response: %s", async variant => {
+ const owner = await createCommunityQueryOwner()
+ owner.registry.collections.profiles.utils.writeUpsert({ ...creator, name: "Before" })
+ let release!: (value: unknown) => void
+ let originalSignal: AbortSignal | undefined
+ let other: Awaited<ReturnType<typeof createCommunityQueryOwner>> | undefined
+ mocks.api.mockImplementationOnce((_path, options: { signal?: AbortSignal }) => { originalSignal = options.signal; return new Promise(resolve => { release = resolve }) })
+ const result = owner.client.query({ queryKey: communityKeys.invites("s1"), queryFn: invitesQueryFn("s1"), retry: false }).then(value => value, error => error)
+ try {
+ await waitFor(() => expect(release).toBeTypeOf("function"))
+ if (variant === "retired owner") {
+ retireCommunityAccount(owner.registry)
+ other = await createCommunityQueryOwner("other")
+ other.registry.collections.profiles.utils.writeUpsert({ ...creator, name: "Other owner" })
+ }
+ else projectCommunityWsEventToDb(owner.client, { type: "community:profile.update", userId: "creator", name: "Newer" })
+ release(invitesReadFixture("s1", [item], [creator]))
+ const outcome = await result
+ if (variant === "retired owner") { expect(outcome).toBeInstanceOf(CancelledError); expect(originalSignal?.aborted).toBe(true); expect(other!.registry.collections.profiles.get("creator")?.name).toBe("Other owner") }
+ else { expect(outcome).toMatchObject({ invites: [{ creatorId: "creator" }] }); expect(owner.registry.collections.profiles.get("creator")?.name).toBe("Newer") }
+ expect(owner.registry.collections.profiles.get("creator")?.name).not.toBe("Alice")
+ } finally { await owner.registry.cleanup(); owner.client.clear(); await other?.registry.cleanup(); other?.client.clear() }
+})
diff --git a/src/web/src/lib/community/list-persistence.test.ts b/src/web/src/lib/community/list-persistence.test.ts
index bce94d1b1..01adfdfa3 100644
--- a/src/web/src/lib/community/list-persistence.test.ts
+++ b/src/web/src/lib/community/list-persistence.test.ts
@@ -10,7 +10,7 @@ const bot = { id: "bot", machineId: "machine", runtime: "codex", modelName: "mod
describe("native list resource persistence", () => {
it("keeps stable metadata while removing machine observations and account allowance", () => {
- const live = { machines: [machine], machineCapacity: { ownedCount: 1, limit: 20 } }
+ const live = { complete: true, machines: [machine], machineCapacity: { ownedCount: 1, limit: 20 } }
const stable = persistentCommunityListResource(communityKeys.machines(), live)!
expect(stable).toEqual({ machines: [{ id: "machine", hostname: "host", displayName: "Computer", platform: "darwin", arch: "arm64", osRelease: "24", daemonVersion: "1", createdAt: "created", updatedAt: "updated" }], complete: true, observed: false, source: "restored_idb" })
expect(live.machines[0].status).toBe("online")
@@ -27,10 +27,10 @@ describe("native list resource persistence", () => {
it("roundtrips only stable native resources and their canonical bot profile without replacing live query data", async () => {
const client = new QueryClient()
- const liveMachines = { machines: [machine], machineCapacity: { ownedCount: 1 } }
+ const liveMachines = { complete: true, machines: [machine], machineCapacity: { ownedCount: 1 } }
client.setQueryData(communityKeys.machines(), liveMachines)
client.setQueryData(communityKeys.bots(), { bots: [bot], limit: 20 })
- client.setQueryData(communityKeys.communityDbCollection("list-viewer", "profiles"), [{ id: "bot", name: "Canonical bot", discriminator: "0042", avatar: null, avatarVersion: 5, identityComplete: true }])
+ client.setQueryData(communityKeys.communityDbCollection("list-viewer", "profiles"), [{ id: "bot", name: "Canonical bot", discriminator: "0042", avatar: null, avatarVersion: 5 }])
const persister = createIdbPersister("list-viewer")
await persister.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client) })
const restored = await persister.restoreClient()
diff --git a/src/web/src/lib/community/list-persistence.ts b/src/web/src/lib/community/list-persistence.ts
index 5e5706824..2c214f368 100644
--- a/src/web/src/lib/community/list-persistence.ts
+++ b/src/web/src/lib/community/list-persistence.ts
@@ -1,7 +1,7 @@
import { z } from "zod"
-import { CommunityMachineSummarySchema, ReasoningEffortSchema } from "@alook/shared"
+import { CommunityMachineIdentityCacheSchema, ReasoningEffortSchema } from "@alook/shared"
-const machineSchema = CommunityMachineSummarySchema.pick({ id: true, hostname: true, displayName: true, platform: true, arch: true, osRelease: true, daemonVersion: true, createdAt: true, updatedAt: true }).strip()
+const machineSchema = CommunityMachineIdentityCacheSchema.strip()
const botSchema = z.object({ id: z.string(), machineId: z.string(), runtime: z.string(), modelName: z.string().nullable(), reasoningEffort: ReasoningEffortSchema.nullable(), runtimeConfigRevision: z.number() })
export function isCommunityListResourceKey(key: readonly unknown[]) {
@@ -11,8 +11,8 @@ export function isCommunityListResourceKey(key: readonly unknown[]) {
export function persistentCommunityListResource(key: readonly unknown[], data: unknown) {
if (!isCommunityListResourceKey(key)) return
if (key[1] === "machines") {
- const parsed = z.object({ machines: z.array(machineSchema), complete: z.boolean().optional() }).safeParse(data)
- if (parsed.success && parsed.data.complete !== false) return { machines: parsed.data.machines, complete: true, observed: false, source: "restored_idb" }
+ const parsed = z.object({ machines: z.array(machineSchema), complete: z.literal(true) }).safeParse(data)
+ if (parsed.success) return { machines: parsed.data.machines, complete: true, observed: false, source: "restored_idb" }
} else {
const parsed = z.object({ bots: z.array(botSchema) }).safeParse(data)
if (parsed.success) return { bots: parsed.data.bots, observed: false, source: "restored_idb" }
diff --git a/src/web/src/lib/community/machines.server.ts b/src/web/src/lib/community/machines.server.ts
index 4ddb5e76b..74c8eb3eb 100644
--- a/src/web/src/lib/community/machines.server.ts
+++ b/src/web/src/lib/community/machines.server.ts
@@ -50,11 +50,11 @@ export async function readCommunityMachines(db: Database, userId: string) {
})
return { ...machine, quota }
})
- return { machines: withQuota, machineCapacity }
+ return { machines: withQuota, machineCapacity, complete: true as const }
}
export async function readCommunityMachineList(db: Database, userId: string) {
- return { machines: await queries.communityMachine.listMachinesForUser(db, userId) }
+ return { machines: await queries.communityMachine.listMachinesForUser(db, userId), complete: true as const }
}
export async function readCommunityMachineObservations(db: Database, userId: string) {
diff --git a/src/web/src/lib/community/machines.ts b/src/web/src/lib/community/machines.ts
index db3213f0b..fd6bb37b7 100644
--- a/src/web/src/lib/community/machines.ts
+++ b/src/web/src/lib/community/machines.ts
@@ -1,4 +1,5 @@
import { queryOptions, type QueryClient } from "@tanstack/react-query"
+import { requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import {
@@ -6,7 +7,7 @@ import {
captureCommunityLiveSnapshotToken,
communityRequestOptions,
} from "@/lib/community-db/sync"
-import type { CommunityMachineSummary, MachineCapacitySummary, ProviderQuotaObservation, QuotaLimit } from "@alook/shared"
+import { CommunityMachineListReadSchema, type CommunityMachineIdentityCache, type CommunityMachineSummary, type MachineCapacitySummary, type ProviderQuotaObservation, type QuotaLimit } from "@alook/shared"
type MachineQuotaSnapshot =
| { status: "pending" }
@@ -32,21 +33,22 @@ export type MachineBackendQuota = {
snapshot: MachineQuotaSnapshot
}
-export type MachineSummary = Omit<CommunityMachineSummary, "status" | "lastSeenAt" | "availableRuntimes" | "lastRuntimeError"> & Partial<Pick<CommunityMachineSummary, "status" | "lastSeenAt" | "availableRuntimes" | "lastRuntimeError">> & {
+export type MachineSummary = CommunityMachineIdentityCache & Partial<Pick<CommunityMachineSummary, "status" | "lastSeenAt" | "availableRuntimes" | "lastRuntimeError">> & {
quota?: MachineBackendQuota[]
}
export type MachineObservations = { machineCapacity?: MachineCapacitySummary; quotas: Array<{ machineId: string; quota: MachineBackendQuota[] }> }
-export type MachinesResponse = { machines: MachineSummary[]; machineCapacity?: MachineCapacitySummary; complete?: boolean; observed?: boolean; source?: "network" | "rsc" | "restored_idb" }
+export type MachinesResponse = { machines: MachineSummary[]; machineCapacity?: MachineCapacitySummary; complete: boolean; observed?: boolean; source?: "network" | "rsc" | "restored_idb" }
export const machinesOptions = () => queryOptions<MachinesResponse>({
queryKey: communityKeys.machines(),
- queryFn: async ({ client, signal }) => ({ ...await apiFetch<MachinesResponse>(
- "/api/community/machines?view=list",
- communityRequestOptions(client, signal),
- ), source: "network" as const }),
- staleTime: (query) => query.state.data?.complete === false || query.state.data?.observed === false ? 0 : 5_000,
+ queryFn: async ({ client, signal }) => {
+ const parsed = CommunityMachineListReadSchema.safeParse(await apiFetch<unknown>("/api/community/machines?view=list", communityRequestOptions(client, signal)))
+ if (!parsed.success) throw requestBusinessSchemaUpdate()
+ return { ...parsed.data, observed: true, source: "network" as const }
+ },
+ staleTime: (query) => query.state.data?.complete !== true || query.state.data?.observed !== true ? 0 : 5_000,
})
export function captureMachinesPublication(client: QueryClient) {
diff --git a/src/web/src/lib/community/member-payload.test.ts b/src/web/src/lib/community/member-payload.test.ts
index 766db97f8..0c626e53a 100644
--- a/src/web/src/lib/community/member-payload.test.ts
+++ b/src/web/src/lib/community/member-payload.test.ts
@@ -8,6 +8,7 @@ function row(overrides: Partial<MemberRow> = {}): MemberRow {
role: "member",
userName: "Ann",
userImage: null,
+ userAvatarVersion: 0,
discriminator: "0001",
statusEmoji: null,
statusText: null,
@@ -27,7 +28,7 @@ describe("mapMemberForApi", () => {
sub: "",
role: "member",
statusEmoji: null,
- statusText: "",
+ statusText: null,
})
// No opt-in flags → no isCreator/source/isBot fields.
expect("isCreator" in m).toBe(false)
@@ -39,10 +40,11 @@ describe("mapMemberForApi", () => {
expect(mapMemberForApi(row({ userId: "viewer" }), "viewer").status).toBe("online")
})
- it("falls back to avatarInitial when image absent", () => {
+ it("preserves a null avatar when the stored image is absent", () => {
const m = mapMemberForApi(row({ userName: "Zed", userImage: null }), "viewer")
expect(m.name).toBe("Zed")
- expect(m.avatar).toBeTruthy()
+ expect(m.avatar).toBeNull()
+ expect(m.avatarVersion).toBe(0)
})
it("botGating exposes isBot/ownerUserId only on the viewer's own bot", () => {
@@ -78,3 +80,7 @@ describe("mapMemberForApi", () => {
expect(m.source).toBe("explicit")
})
})
+
+it.each([null, "", "Busy"])("preserves actual member status %s without a display fallback", statusText => {
+ expect(mapMemberForApi(row({ statusText }), "viewer").statusText).toBe(statusText)
+})
diff --git a/src/web/src/lib/community/member-payload.ts b/src/web/src/lib/community/member-payload.ts
index db84bd364..832b934b1 100644
--- a/src/web/src/lib/community/member-payload.ts
+++ b/src/web/src/lib/community/member-payload.ts
@@ -1,4 +1,5 @@
-import { avatarInitial } from "./avatar"
+import { CommunityResourceProfileSchema, type CommunityResourceProfile } from "@alook/shared"
+
import { canonicalUserImage } from "./storage"
// Canonical row shape the member-list queries produce. Bot columns
@@ -18,18 +19,12 @@ export type MemberRow = {
userOwnerUserId?: string | null
}
-export type MappedMember = {
+export type MappedMember = Pick<CommunityResourceProfile, "name" | "discriminator" | "avatar" | "avatarVersion"> & Required<Pick<CommunityResourceProfile, "statusEmoji" | "statusText">> & {
id: string
userId: string
- name: string
- discriminator: string | undefined
- avatar: string
- avatarVersion: number
status: "online" | "offline"
sub: string
role: string
- statusEmoji: string | null
- statusText: string
isCreator?: boolean
source?: string
isBot?: true
@@ -37,20 +32,14 @@ export type MappedMember = {
}
// The single canonical member-DTO mapper shared by every UI member-list
-// endpoint. Centralizes the `avatarInitial` default, the self-→`online` status
-// guess, the constant `sub: ""` (the client `Member` type requires `sub:
-// string`), and the owner-scoped `isBot`/`ownerUserId` projection.
-//
-// `botGating` is opt-in: only the server-members LIST route applies the
-// owner-scoped `isBot`/`ownerUserId` projection. The search route never emitted
-// bot fields (and doesn't select the columns), so it passes `botGating: false`
-// to stay byte-identical.
+// endpoint. Bot ownership is exposed only when botGating is enabled and the
+// actor owns that bot. Search rows do not carry bot ownership columns.
export function mapMemberForApi(
row: MemberRow,
viewerUserId: string,
opts?: { botGating?: boolean; isCreator?: boolean; source?: string },
): MappedMember {
- const display = row.userName ?? ""
+ const display = CommunityResourceProfileSchema.shape.name.parse(row.userName)
const isOwnBot =
!!opts?.botGating &&
row.userIsBot === true &&
@@ -59,15 +48,14 @@ export function mapMemberForApi(
id: row.id,
userId: row.userId,
name: display,
- discriminator: row.discriminator ?? undefined,
- avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion)
- ?? avatarInitial(display),
+ discriminator: CommunityResourceProfileSchema.shape.discriminator.parse(row.discriminator),
+ avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion),
avatarVersion: row.userAvatarVersion,
status: row.userId === viewerUserId ? "online" : "offline",
sub: "",
role: row.role ?? "member",
statusEmoji: row.statusEmoji ?? null,
- statusText: row.statusText ?? "",
+ statusText: row.statusText,
...(opts?.isCreator !== undefined ? { isCreator: opts.isCreator } : {}),
...(opts?.source !== undefined ? { source: opts.source } : {}),
...(isOwnBot ? { isBot: true as const, ownerUserId: row.userOwnerUserId! } : {}),
diff --git a/src/web/src/lib/community/member-read.test.ts b/src/web/src/lib/community/member-read.test.ts
index b944f4be5..ad02792aa 100644
--- a/src/web/src/lib/community/member-read.test.ts
+++ b/src/web/src/lib/community/member-read.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { beforeEach, describe, expect, it, vi } from "vitest"
const mocks = vi.hoisted(() => ({ access: vi.fn(), channel: vi.fn(), participants: vi.fn(), audience: vi.fn(), users: vi.fn(), serverMembers: vi.fn(), resolve: vi.fn() }))
vi.mock("./permissions", () => ({ requireMessageSurfaceAccess: mocks.access }))
@@ -30,7 +31,7 @@ describe("common member relations", () => {
it.each(["text", "forum"])("resolves the %s access audience rather than notify participants", async (type) => {
mocks.access.mockResolvedValue({ ok: true, value: { surface: "channel", channel: { id: "parent", type, serverId: "server", creatorId: "viewer" } } })
mocks.resolve.mockResolvedValue([{ userId: "viewer", source: "admin" }])
- mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", image: null, avatarVersion: 0 }])
+ mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", discriminator: "1234", image: null, avatarVersion: 0 }])
mocks.serverMembers.mockResolvedValue([])
const response = await readCommunityMembers({} as never, "parent", "viewer", "access")
expect(await response.json()).toMatchObject({ members: [{ channelId: "parent", userId: "viewer", relation: "access", source: "admin" }] })
@@ -45,7 +46,7 @@ describe("common member relations", () => {
it("retains both DM participants without server membership or email fields", async () => {
const response = await readCommunityMembers({} as never, "dm", "viewer", "access")
const body = await response.json()
- expect(body).toMatchObject({ contractVersion: 2, channelId: "dm", relation: "access" })
+ expect(body).toMatchObject({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "dm", relation: "access" })
expect(body.members).toHaveLength(2)
expect(body.members.every((member: { role: unknown; memberId: unknown }) => member.role === null && member.memberId === null)).toBe(true)
expect(JSON.stringify(body)).not.toContain("[email protected]")
diff --git a/src/web/src/lib/community/member-read.ts b/src/web/src/lib/community/member-read.ts
index 077a3f720..2b3d3a72e 100644
--- a/src/web/src/lib/community/member-read.ts
+++ b/src/web/src/lib/community/member-read.ts
@@ -1,11 +1,11 @@
-import { CommunityResourceProfileSchema, communityReadSchemas, queries, type Database } from "@alook/shared"
+import { COMMUNITY_CONTRACT_VERSION, type CommunityContract, CommunityResourceProfileSchema, communityReadSchemas, queries, type Database } from "@alook/shared"
import { requireMessageSurfaceAccess } from "./permissions"
import { writeError } from "@/lib/middleware/helpers"
import { writeCommunityContractJSON } from "./read-contract"
import { canonicalUserImage } from "./storage"
import { resourceProfile } from "./participant-resources"
-export async function readCommunityMembers(db: Database, channelId: string, userId: string, relation: string | null, contract: 2 | 3 = 2) {
+export async function readCommunityMembers(db: Database, channelId: string, userId: string, relation: string | null, contract: CommunityContract = COMMUNITY_CONTRACT_VERSION) {
const access = await requireMessageSurfaceAccess(db, channelId, userId)
if (!access.ok) return writeError(access.error, access.status)
if (relation !== "access" && relation !== "notify") return writeError("relation must be access or notify", 400)
@@ -23,7 +23,7 @@ export async function readCommunityMembers(db: Database, channelId: string, user
? queries.communityMember.getMembersByUserIds(db, channel.serverId, ids) : Promise.resolve([]),
])
const memberByUser = new Map(serverMembers.map((row) => [row.userId, row]))
- const profiles = users.map((row) => resourceProfile({ id: row.id, name: contract === 3 ? CommunityResourceProfileSchema.shape.name.parse(row.name) : row.name ?? "", discriminator: row.discriminator ?? null,
+ const profiles = users.map((row) => resourceProfile({ id: row.id, name: CommunityResourceProfileSchema.shape.name.parse(row.name), discriminator: row.discriminator,
avatar: canonicalUserImage(row.id, row.image, row.avatarVersion), avatarVersion: row.avatarVersion,
...(memberByUser.has(row.id) ? {
statusEmoji: memberByUser.get(row.id)!.statusEmoji, statusText: memberByUser.get(row.id)!.statusText,
@@ -32,5 +32,5 @@ export async function readCommunityMembers(db: Database, channelId: string, user
return writeCommunityContractJSON(communityReadSchemas(contract).members.parse({ contractVersion: contract, channelId, relation,
members: relations.filter((row) => available.has(row.userId)).map((row) => ({ channelId, userId: row.userId,
relation, source: row.source ?? "explicit", isCreator: row.userId === channel.creatorId,
- role: memberByUser.get(row.userId)?.role ?? null, memberId: memberByUser.get(row.userId)?.id ?? null })), profiles: contract === 2 ? profiles.map((profile) => ({ id: profile.id, name: profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "" })) : profiles }), contract)
+ role: memberByUser.get(row.userId)?.role ?? null, memberId: memberByUser.get(row.userId)?.id ?? null })), profiles }), contract)
}
diff --git a/src/web/src/lib/community/message-delivery-transport.test.ts b/src/web/src/lib/community/message-delivery-transport.test.ts
index 26eef079f..0a3d35d73 100644
--- a/src/web/src/lib/community/message-delivery-transport.test.ts
+++ b/src/web/src/lib/community/message-delivery-transport.test.ts
@@ -1,3 +1,5 @@
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"
import {
COMMUNITY_DELIVERY_OPERATION_ID_HEADER,
@@ -19,7 +21,7 @@ const {
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: () => ({
env: {
- COMMUNITY_EVENT_CONTRACT: "2",
+ COMMUNITY_EVENT_CONTRACT: String(BUSINESS_SCHEMA_VERSION),
WS_DO_WORKER: { fetch: bindingFetch },
DEV_WS_DO_URL: "http://dev-ws:8789",
},
@@ -46,14 +48,14 @@ const originalFetch = globalThis.fetch
const globalFetch = vi.fn<(...args: unknown[]) => Promise<Response>>()
function batch(overrides: Partial<MessageDeliveryBatch> = {}): MessageDeliveryBatch {
- return {
+ return { communityContract: BUSINESS_SCHEMA_VERSION,
messageId: "message-1",
messageEvent: {
- type: "community:message.create",
+ type: "community:message.create", profiles: [{ id: "u1", name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 }],
channelId: "thread-1",
serverId: "server-1",
parentChannelId: "forum-1",
- message: {
+ message: messageResourceFixture({ channelId: "thread-1",
id: "message-1",
seq: 4,
authorId: "u1",
@@ -62,13 +64,13 @@ function batch(overrides: Partial<MessageDeliveryBatch> = {}): MessageDeliveryBa
content: "hello",
type: "chat",
createdAt: "2026-08-18T00:00:00.000Z",
- },
+ }),
},
contentUserIds: ["u1", "u2", "u3"],
unreadPlainUserIds: ["u2"],
unreadMentionUserIds: ["u3"],
mentionUserIds: ["u3"],
- memberAdded: { userId: "u1", serverId: "server-1", channelId: "thread-1" },
+ joinedParticipantUserIds: ["u1"], rosterRefreshUserId: "u1",
parentProjection: {
type: "community:channel.child_update",
parentChannelId: "forum-1",
@@ -106,7 +108,7 @@ describe("sendMessageDeliveryBatch", () => {
it("retains the original roster refresh identity after a partial retry subset", async () => {
bindingFetch.mockResolvedValueOnce(Response.json({ failedUserIds: ["u2"] }, { status: 207 }))
.mockResolvedValueOnce(Response.json({ failedUserIds: [] }))
- await sendMessageDeliveryBatch(batch({ joinedParticipantUserIds: ["u1", "u2"], rosterRefreshUserId: "u1", memberAdded: undefined }))
+ await sendMessageDeliveryBatch(batch({ joinedParticipantUserIds: ["u1", "u2"], rosterRefreshUserId: "u1", }))
expect(requestBatch(0)).toMatchObject({ joinedParticipantUserIds: ["u1", "u2"], rosterRefreshUserId: "u1" })
expect(requestBatch(1)).toMatchObject({ joinedParticipantUserIds: ["u2"], rosterRefreshUserId: "u1" })
expect(requestOperationId(1)).toBe(requestOperationId(0))
@@ -137,7 +139,7 @@ describe("sendMessageDeliveryBatch", () => {
unreadPlainUserIds: [],
unreadMentionUserIds: [],
mentionUserIds: [],
- memberAdded: undefined,
+ joinedParticipantUserIds: undefined, rosterRefreshUserId: undefined,
parentProjection: undefined,
parentProjectionUserIds: undefined,
}))
@@ -156,7 +158,7 @@ describe("sendMessageDeliveryBatch", () => {
unreadPlainUserIds: [],
unreadMentionUserIds: ids,
mentionUserIds: ids,
- memberAdded: undefined,
+ joinedParticipantUserIds: undefined, rosterRefreshUserId: undefined,
parentProjectionUserIds: ids,
})
@@ -187,7 +189,7 @@ describe("sendMessageDeliveryBatch", () => {
unreadPlainUserIds: [],
unreadMentionUserIds: [],
mentionUserIds: [],
- memberAdded: undefined,
+ joinedParticipantUserIds: undefined, rosterRefreshUserId: undefined,
parentProjection: undefined,
parentProjectionUserIds: undefined,
})
@@ -210,7 +212,7 @@ describe("sendMessageDeliveryBatch", () => {
unreadMentionUserIds: [],
mentionUserIds: [],
})
- expect(requestBatch(1).memberAdded).toBeUndefined()
+ expect(requestBatch(1).joinedParticipantUserIds).toEqual([])
expect(requestBatch(1).parentProjection).toBeUndefined()
expect(requestOperationId(1)).toBe(requestOperationId(0))
expect(globalFetch).not.toHaveBeenCalled()
diff --git a/src/web/src/lib/community/message-delivery-transport.ts b/src/web/src/lib/community/message-delivery-transport.ts
index 51f1f5938..3f42a8ee1 100644
--- a/src/web/src/lib/community/message-delivery-transport.ts
+++ b/src/web/src/lib/community/message-delivery-transport.ts
@@ -26,7 +26,6 @@ function allTargetUserIds(batch: MessageDeliveryBatch): string[] {
...batch.unreadPlainUserIds,
...batch.unreadMentionUserIds,
...batch.mentionUserIds,
- ...(batch.memberAdded ? [batch.memberAdded.userId] : []),
...(batch.parentProjectionUserIds ?? []),
])]
}
@@ -35,7 +34,7 @@ function selectTargets(batch: MessageDeliveryBatch, selected: ReadonlySet<string
const keep = (ids: readonly string[]) => ids.filter((id) => selected.has(id))
const parentProjectionUserIds = keep(batch.parentProjectionUserIds ?? [])
return {
- ...(batch.communityContract === 3 ? { communityContract: 3 as const } : {}),
+ communityContract: batch.communityContract,
messageId: batch.messageId,
messageEvent: batch.messageEvent,
contentUserIds: keep(batch.contentUserIds),
@@ -43,9 +42,6 @@ function selectTargets(batch: MessageDeliveryBatch, selected: ReadonlySet<string
unreadMentionUserIds: keep(batch.unreadMentionUserIds),
mentionUserIds: keep(batch.mentionUserIds),
...(batch.joinedParticipantUserIds ? { joinedParticipantUserIds: keep(batch.joinedParticipantUserIds), rosterRefreshUserId: batch.rosterRefreshUserId } : {}),
- ...(batch.memberAdded && selected.has(batch.memberAdded.userId)
- ? { memberAdded: batch.memberAdded }
- : {}),
...(batch.parentProjection && parentProjectionUserIds.length > 0
? { parentProjection: batch.parentProjection, parentProjectionUserIds }
: {}),
diff --git a/src/web/src/lib/community/message-dispatcher.test.ts b/src/web/src/lib/community/message-dispatcher.test.ts
index cd5d565fc..770cf3a08 100644
--- a/src/web/src/lib/community/message-dispatcher.test.ts
+++ b/src/web/src/lib/community/message-dispatcher.test.ts
@@ -31,6 +31,7 @@ vi.mock("@alook/shared", async () => {
}),
withD1Retry: (run: () => Promise<unknown>) => run(),
queries: {
+ communityUserProfile: { getResourceProfiles: async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "Alice", discriminator: "0042", avatar: null, avatarVersion: 0 })) },
communityMessage: {
getMessage: (...args: unknown[]) => mockGetMessage(...args),
getWakeContextMessageInScope: (...args: unknown[]) =>
@@ -74,7 +75,7 @@ vi.mock("./queue-producer", () => ({
enqueueQueueTasks: (...args: unknown[]) => mockEnqueueQueueTasks(...args),
}))
import { dispatchCommittedMessage, planCommittedMessage } from "./message-dispatcher"
-import { deriveCommunityDeliveryOperationId } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, deriveCommunityDeliveryOperationId } from "@alook/shared"
const message = {
id: "msg_1",
@@ -281,6 +282,8 @@ describe("planCommittedMessage", () => {
}))
mockListAttachments.mockResolvedValue([{
id: "att_1",
+ messageId: "msg_1",
+ r2Key: "channel/c1/photo.png",
targetId: "c1",
filename: "photo.png",
thumbnailR2Key: "thumb",
@@ -324,6 +327,8 @@ describe("planCommittedMessage", () => {
mockListAttention.mockResolvedValue([{ userId: "bot_1", kind: "mention" }])
mockListAttachments.mockResolvedValue([{
id: "att_1",
+ messageId: "msg_1",
+ r2Key: "channel/c1/photo.png",
targetId: "c1",
filename: "private-name.png",
thumbnailR2Key: null,
@@ -500,13 +505,15 @@ describe("planCommittedMessage", () => {
const plan = await planCommittedMessage(
{} as never,
"msg_1",
- { memberAddedUserId: "u_all" },
+ { joinedParticipantUserIds: ["u_all"] },
)
- expect(plan.memberAdded).toEqual({ userId: "u_all", serverId: "s1", channelId: "c1" })
+ expect(plan.joinedParticipantUserIds).toEqual(["u_all"])
+ expect(plan.rosterRefreshUserId).toBe("u_all")
+ expect(plan.communityContract).toBe(BUSINESS_SCHEMA_VERSION)
await expect(planCommittedMessage(
{} as never,
"msg_1",
- { memberAddedUserId: "outside" },
+ { joinedParticipantUserIds: ["outside"] },
)).rejects.toThrow("outside message scope")
})
@@ -586,11 +593,11 @@ describe("dispatchCommittedMessage", () => {
await expect(work).resolves.toBeUndefined()
expect(mockSendMessageDeliveryBatch).toHaveBeenCalledTimes(1)
expect(mockSendMessageDeliveryBatch).toHaveBeenCalledWith(
- expect.objectContaining({ messageId: "msg_1" }),
+ expect.objectContaining({ messageId: "msg_1", communityContract: BUSINESS_SCHEMA_VERSION }),
await deriveCommunityDeliveryOperationId("msg_1"),
)
expect(Object.keys(mockSendMessageDeliveryBatch.mock.calls[0]![0]).sort()).toEqual([
- "contentUserIds", "mentionUserIds", "messageEvent", "messageId",
+ "communityContract", "contentUserIds", "mentionUserIds", "messageEvent", "messageId",
"unreadMentionUserIds", "unreadPlainUserIds",
])
expect(mockEnqueueQueueTasks).toHaveBeenCalledWith([])
@@ -610,7 +617,7 @@ describe("dispatchCommittedMessage", () => {
)
await dispatchCommittedMessage({} as never, "msg_1", {
- memberAddedUserId: "author_1", joinedParticipantUserIds: ["author_1"],
+ joinedParticipantUserIds: ["author_1"],
})
expect(mockSendMessageDeliveryBatch).toHaveBeenCalledWith(
@@ -620,14 +627,14 @@ describe("dispatchCommittedMessage", () => {
channelId: "t1",
}),
parentProjectionUserIds: ["parent_viewer"],
- memberAdded: { userId: "author_1", serverId: "s1", channelId: "t1" },
+ communityContract: BUSINESS_SCHEMA_VERSION,
joinedParticipantUserIds: ["author_1"],
rosterRefreshUserId: "author_1",
}),
await deriveCommunityDeliveryOperationId("msg_1"),
)
expect(Object.keys(mockSendMessageDeliveryBatch.mock.calls[0]![0]).sort()).toEqual([
- "contentUserIds", "joinedParticipantUserIds", "memberAdded", "mentionUserIds",
+ "communityContract", "contentUserIds", "joinedParticipantUserIds", "mentionUserIds",
"messageEvent", "messageId", "parentProjection", "parentProjectionUserIds",
"rosterRefreshUserId", "unreadMentionUserIds", "unreadPlainUserIds",
])
diff --git a/src/web/src/lib/community/message-dispatcher.ts b/src/web/src/lib/community/message-dispatcher.ts
index ee9da6854..ec1cfe3bc 100644
--- a/src/web/src/lib/community/message-dispatcher.ts
+++ b/src/web/src/lib/community/message-dispatcher.ts
@@ -1,7 +1,8 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import {
deriveCommunityDeliveryOperationId,
- decodeCommunityBrowserEvent,
+ validateCommunityWsEvent,
reachIsParticipantSet,
WS_EVENTS,
createLogger,
@@ -13,10 +14,10 @@ import {
type CommunityContract,
type AlookQueueTask,
} from "@alook/shared"
-import { mapMessageForWs, type MessageRow } from "./message-payload"
+import { mapMessageForWs, readCommunityMessageProfiles, type MessageRow } from "./message-payload"
import { sendMessageDeliveryBatch } from "./message-delivery-transport"
import { enqueueQueueTasks } from "./queue-producer"
-import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
+
import { communityProducerContract } from "./producer-contract"
import { groupAttachments } from "./messages"
@@ -24,7 +25,6 @@ const log = createLogger({ service: "committed-message-dispatcher" })
export type CommittedMessageStructuralOutcome = {
/** A participant row inserted by this exact message write. */
- memberAddedUserId?: string
joinedParticipantUserIds?: string[]
/** Existing thread-open collision suppression; no audience/policy input. */
suppressParentProjection?: boolean
@@ -60,7 +60,7 @@ export async function planCommittedMessage(
db: Database,
messageId: string,
structural: CommittedMessageStructuralOutcome = {},
- contract: CommunityContract = 2,
+ contract: CommunityContract = BUSINESS_SCHEMA_VERSION,
): Promise<MessageDeliveryPlan> {
const message = await withD1Retry(
() => queries.communityMessage.getMessage(db, messageId),
@@ -194,22 +194,11 @@ export async function planCommittedMessage(
replyMap,
botCreation: creationRequest,
clientNonce: clientNonce ?? undefined,
- ...(contract === 3 ? { resourceAttachments: groupAttachments(attachments)[message.id] ?? [] } : {}),
- attachments: attachments.map((attachment) => ({
- id: attachment.id,
- filename: attachment.filename,
- url: attachmentUrl(attachment.targetId, attachment.id),
- ...(attachment.thumbnailR2Key
- ? { thumbnailUrl: attachmentThumbnailUrl(attachment.targetId, attachment.id) }
- : {}),
- contentType: attachment.contentType ?? undefined,
- size: attachment.size ?? undefined,
- width: attachment.width ?? undefined,
- height: attachment.height ?? undefined,
- })),
+ resourceAttachments: groupAttachments(attachments)[message.id] ?? [],
}, contract, message.channelId),
}
- const messageResult = decodeCommunityBrowserEvent(messageInput, contract)
+ const profiles = await readCommunityMessageProfiles(db, [messageInput.message])
+ const messageResult = validateCommunityWsEvent({ ...messageInput, profiles }, contract)
if (!messageResult.ok || messageResult.event.type !== WS_EVENTS.MESSAGE_CREATE) throw new Error("Invalid committed message event")
const messageEvent = messageResult.event
@@ -224,22 +213,16 @@ export async function planCommittedMessage(
channelId: channel.id,
changes: {
messageCount: channel.messageCount,
- lastMessageAt: contract === 3 ? channel.lastMessageAt : channel.lastMessageAt ?? message.createdAt,
+ lastMessageAt: channel.lastMessageAt,
},
} as const
: undefined
const joinedParticipantUserIds = [...new Set(structural.joinedParticipantUserIds ?? [])]
if (joinedParticipantUserIds.some((id) => !channel.serverId || !contentUserIds.includes(id))) throw new Error("committed participant outcome is outside message scope")
- if (
- structural.memberAddedUserId
- && (!channel.serverId || !contentUserIds.includes(structural.memberAddedUserId))
- ) {
- throw new Error("committed participant outcome is outside message scope")
- }
return {
- ...(contract === 3 ? { communityContract: 3 as const } : {}),
+ communityContract: contract,
operationId: await deriveCommunityDeliveryOperationId(message.id),
messageId: message.id,
messageEvent,
@@ -250,15 +233,6 @@ export async function planCommittedMessage(
wakeBotUserIds,
pushUserIds,
...(joinedParticipantUserIds.length ? { joinedParticipantUserIds, rosterRefreshUserId: joinedParticipantUserIds[0]! } : {}),
- ...(structural.memberAddedUserId && channel.serverId
- ? {
- memberAdded: {
- userId: structural.memberAddedUserId,
- serverId: channel.serverId,
- channelId: channel.id,
- },
- }
- : {}),
...(parentProjection
? { parentProjection, parentProjectionUserIds }
: {}),
@@ -271,8 +245,8 @@ async function runCommittedMessageDispatch(
structural: CommittedMessageStructuralOutcome,
): Promise<void> {
const startedAt = Date.now()
- const { env } = getCloudflareContext()
- const contract = communityProducerContract(env as Env)
+ getCloudflareContext()
+ const contract = communityProducerContract()
const plan = await planCommittedMessage(
db,
messageId,
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index f28bb82ee..998797c36 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { describe, it, expect, vi, beforeEach } from "vitest"
vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: () => ({ env: {} }) }))
@@ -12,6 +13,7 @@ const mockListByMessageIds = vi.fn()
const mockListMembers = vi.fn()
const mockListMemberUserIds = vi.fn()
const mockCreateMentions = vi.fn()
+const mockGetThreadChannelByParentMessage = vi.fn()
const mockGetChannel = vi.fn()
const mockIsChannelPrivate = vi.fn(() => false)
const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])
@@ -52,6 +54,7 @@ vi.mock("@alook/shared", async () => {
createMentions: (...a: unknown[]) => mockCreateMentions(...a),
},
communityChannel: {
+ getThreadChannelByParentMessage: (...args: unknown[]) => mockGetThreadChannelByParentMessage(...args),
getChannel: (...a: unknown[]) => mockGetChannel(...a),
isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),
getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),
@@ -1022,6 +1025,7 @@ describe("post-commit notification registration", () => {
mockGetMessage.mockResolvedValue(messageRow())
mockListByMessageIds.mockResolvedValue([])
mockDispatchCommittedMessage.mockResolvedValue(undefined)
+ mockGetThreadChannelByParentMessage.mockResolvedValue(channelResourceFixture({ id: "child", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "msg_1", name: "post", createdAt: "2026-01-01" }))
})
const params = {
@@ -1031,16 +1035,22 @@ describe("post-commit notification registration", () => {
body: { content: "hello" },
}
- it.each(["attachments", "message"])("registers message and child notices before a failed %s response read", async (projection) => {
+ it.each(["attachments", "message"])("starts delivery and child resource lookup before failed %s projection, then completes the full child notice", async (projection) => {
+ let releaseChild!: (value: unknown) => void
+ mockGetThreadChannelByParentMessage.mockImplementationOnce(() => new Promise(resolve => { releaseChild = resolve }))
const fail = async () => {
expect(mockDispatchCommittedMessage).toHaveBeenCalledOnce()
- expect(mockFanOutToChannel).toHaveBeenCalledOnce()
+ expect(mockGetThreadChannelByParentMessage).toHaveBeenCalledExactlyOnceWith(expect.anything(), "c1", "msg_1")
+ expect(mockFanOutToChannel).not.toHaveBeenCalled()
throw new Error("projection unavailable")
}
if (projection === "attachments") mockListByMessageIds.mockImplementationOnce(fail)
else mockGetMessage.mockImplementationOnce(fail)
await expect(createCommunityMessage({ ...params, attachmentIds: ["att_1"] })).rejects.toThrow("projection unavailable")
expect(mockHardDeleteMessage).not.toHaveBeenCalled()
+ const channel = channelResourceFixture({ id: "child", serverId: "s1", type: "thread", parentChannelId: "c1", parentMessageId: "msg_1", name: "post", createdAt: "2026-01-01" })
+ releaseChild(channel)
+ await vi.waitFor(() => expect(mockFanOutToChannel).toHaveBeenCalledExactlyOnceWith("c1", { type: "community:channel.child_create", parentChannelId: "c1", parentMessageId: "msg_1", channel }))
})
it("surfaces a missing response projection after registering notifications without deleting committed data", async () => {
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 0512f0d77..7bd702e13 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -19,8 +19,8 @@ import { nanoid } from "nanoid"
import { dispatchCommittedMessage } from "./message-dispatcher"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
import { broadcastToUserSafe, fanOutToChannel } from "./fanout"
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { communityProducerContract } from "./producer-contract"
+
+
import { extractChatMentionedUserIds } from "./chat-markdown"
const log = createLogger({ service: "community-message-handler" })
@@ -564,17 +564,14 @@ export async function createCommunityMessage(params: {
}))
}
if (created.createdThread && !params.suppressThreadFanout) {
- const contract = communityProducerContract(getCloudflareContext().env as Env)
- const child = contract === 3 ? await queries.communityChannel.getThreadChannelByParentMessage(db, target.channelId, created.id) : null
+ const child = await queries.communityChannel.getThreadChannelByParentMessage(db, target.channelId, created.id)
const event = {
type: WS_EVENTS.CHILD_CHANNEL_CREATE,
parentChannelId: target.channelId,
parentMessageId: created.id,
- channel: contract === 3 ? communityChannelResourceFromStorage(child) : { ...created.createdThread, type: "thread" as const, creatorId: authorId },
+ channel: communityChannelResourceFromStorage(child),
}
- deliveries.push(fanOutToChannel(target.channelId, contract === 3 ? CommunityResourceWsEventSchema.parse(event) : {
- ...event, channel: { ...created.createdThread, type: "thread", creatorId: authorId },
- }))
+ deliveries.push(fanOutToChannel(target.channelId, CommunityResourceWsEventSchema.parse(event)))
}
await Promise.all(deliveries)
}
diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.ts
index 884e9cdbe..c64a51ff7 100644
--- a/src/web/src/lib/community/message-payload.test.ts
+++ b/src/web/src/lib/community/message-payload.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { beforeEach, describe, it, expect, vi } from "vitest"
const creationMocks = vi.hoisted(() => ({ hydrate: vi.fn(), attachments: vi.fn(), reactions: vi.fn() }))
vi.mock("@alook/shared", async () => {
@@ -10,6 +11,7 @@ import { readCommunityMessageResource, mapMessageForApi, mapMessageForWs, type M
const baseRow: MessageRow = {
id: "m1",
authorId: "u_alice",
+ authorAvatarVersion: 0,
authorName: "Alice",
authorImage: "https://avatars/alice.png",
content: "hello",
@@ -21,17 +23,17 @@ const baseRow: MessageRow = {
createdAt: "2026-07-03T12:00:00.000Z",
}
-const emptyApiCtx = {
+const emptyApiCtx = { viewerId: "u_alice",
replyMap: new Map(),
attachmentsByMessage: {},
reactionsByMessage: {},
}
-const emptyWsCtx = { replyMap: new Map(), attachments: [] }
+const emptyWsCtx = { replyMap: new Map(), resourceAttachments: [] }
describe("mapMessageForApi", () => {
it("returns the core author/content/timestamp fields with avatar fallback", () => {
- const out = mapMessageForApi(baseRow, emptyApiCtx)
+ const out = mapMessageForApi(baseRow, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.id).toBe("m1")
expect(out.authorName).toBe("Alice")
expect(out.authorAvatar).toBe("https://avatars/alice.png")
@@ -40,56 +42,56 @@ describe("mapMessageForApi", () => {
})
it("coerces null content to empty string (message with attachments only)", () => {
- const out = mapMessageForApi({ ...baseRow, content: null }, emptyApiCtx)
+ const out = mapMessageForApi({ ...baseRow, content: null }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.content).toBe("")
})
- it("derives avatarInitial when authorImage is null", () => {
- const out = mapMessageForApi({ ...baseRow, authorImage: null, authorName: "Alice" }, emptyApiCtx)
- expect(out.authorAvatar).toBe("A")
+ it("keeps a null stored avatar as null in the full resource", () => {
+ const out = mapMessageForApi({ ...baseRow, authorImage: null, authorName: "Alice" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
+ expect(out.authorAvatar).toBeNull()
})
it("maps ordinary rows to type: \"chat\" (never undefined — #12's exhaustive discriminator) and surfaces `system` verbatim", () => {
- expect(mapMessageForApi({ ...baseRow, type: null }, emptyApiCtx).type).toBe("chat")
- expect(mapMessageForApi({ ...baseRow, type: "default" }, emptyApiCtx).type).toBe("chat")
- expect(mapMessageForApi({ ...baseRow, type: "system" }, emptyApiCtx).type).toBe("system")
+ expect(mapMessageForApi({ ...baseRow, type: null }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel").type).toBe("chat")
+ expect(mapMessageForApi({ ...baseRow, type: "default" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel").type).toBe("chat")
+ expect(mapMessageForApi({ ...baseRow, type: "system" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel").type).toBe("system")
})
it("splits `type: \"thread_created\"` into { type: \"system\", systemKind: \"thread\" }", () => {
- const out = mapMessageForApi({ ...baseRow, type: "thread_created" }, emptyApiCtx)
+ const out = mapMessageForApi({ ...baseRow, type: "thread_created" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.type).toBe("system")
expect(out.systemKind).toBe("thread")
})
it("a bare `type: \"system\"` row (no known kind) omits systemKind", () => {
- const out = mapMessageForApi({ ...baseRow, type: "system" }, emptyApiCtx)
+ const out = mapMessageForApi({ ...baseRow, type: "system" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.systemKind).toBeUndefined()
})
it("resolves replyTo from an in-scope replyMap entry", () => {
- const replyMap = new Map([["m0", { id: "m0", authorName: "Bob", content: "hey there" }]])
- const out = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap })
- expect(out.replyTo).toEqual({ id: "m0", authorName: "Bob", text: "hey there" })
+ const replyMap = new Map([["m0", { id: "m0", authorId: "bob", authorName: "Bob", content: "hey there" }]])
+ const out = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel")
+ expect(out.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob", text: "hey there" })
})
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)
+ const out = mapMessageForApi({ ...baseRow, replyToId: "m-gone" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.replyTo).toEqual({ id: "m-gone", authorName: "Deleted user", text: "", deleted: true })
})
it("gives API and WS projections the same ellipsized reply preview", () => {
const long = "x".repeat(500)
- const replyMap = new Map([["m0", { id: "m0", authorName: "Bob", content: long }]])
- const apiOut = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap })
- const wsOut = mapMessageForWs({ ...baseRow, replyToId: "m0" }, { ...emptyWsCtx, replyMap })
+ const replyMap = new Map([["m0", { id: "m0", authorId: "bob", authorName: "Bob", content: long }]])
+ const apiOut = mapMessageForApi({ ...baseRow, replyToId: "m0" }, { ...emptyApiCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel")
+ const wsOut = mapMessageForWs({ ...baseRow, replyToId: "m0" }, { ...emptyWsCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel")
const expected = `${"x".repeat(119)}…`
expect(apiOut.replyTo?.text).toBe(expected)
expect(wsOut.replyTo?.text).toBe(expected)
})
it("omits attachments/reactions when there are none", () => {
- const out = mapMessageForApi(baseRow, emptyApiCtx)
- expect(out.attachments).toBeUndefined()
+ const out = mapMessageForApi(baseRow, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
+ expect(out.attachments).toEqual([])
expect(out.reactions).toBeUndefined()
})
@@ -97,121 +99,118 @@ describe("mapMessageForApi", () => {
const out = mapMessageForApi(baseRow, {
...emptyApiCtx,
attachmentsByMessage: {
- m1: [{ kind: "image", name: "a.png", url: "/a.png" }],
+ m1: [{ id: "a", name: "a.png", url: "/a.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: null, width: null, height: null }],
},
reactionsByMessage: {
m1: [{ emoji: "🎉", count: 2, me: true, userIds: ["u_alice", "u_bob"] }],
},
- })
- expect(out.attachments).toEqual([{ kind: "image", name: "a.png", url: "/a.png" }])
+ }, BUSINESS_SCHEMA_VERSION, "channel")
+ expect(out.attachments).toEqual([{ id: "a", name: "a.png", url: "/a.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: null, width: null, height: null }])
expect(out.reactions).toEqual([{ emoji: "🎉", count: 2, me: true, userIds: ["u_alice", "u_bob"] }])
})
it("adds thread info only when threadByMessageId hits", () => {
const threadByMessageId = new Map([["m1", { id: "t1", name: "post title", messageCount: 5 }]])
- const withThread = mapMessageForApi(baseRow, { ...emptyApiCtx, threadByMessageId })
+ const withThread = mapMessageForApi(baseRow, { ...emptyApiCtx, threadByMessageId }, BUSINESS_SCHEMA_VERSION, "channel")
expect(withThread.thread).toEqual({ id: "t1", name: "post title", messageCount: 5 })
- const withoutThread = mapMessageForApi(baseRow, emptyApiCtx)
+ const withoutThread = mapMessageForApi(baseRow, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(withoutThread.thread).toBeUndefined()
})
it("returns client-provided nonces and filters srv fallbacks", () => {
- expect(mapMessageForApi({ ...baseRow, clientNonce: "client-1" }, emptyApiCtx).clientNonce)
+ expect(mapMessageForApi({ ...baseRow, clientNonce: "client-1" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel").clientNonce)
.toBe("client-1")
- expect(mapMessageForApi({ ...baseRow, clientNonce: "srv:fallback" }, emptyApiCtx).clientNonce)
- .toBeUndefined()
- expect(mapMessageForApi({ ...baseRow, clientNonce: null }, emptyApiCtx).clientNonce)
- .toBeUndefined()
+ expect(mapMessageForApi({ ...baseRow, clientNonce: "srv:fallback" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel").clientNonce)
+ .toBeNull()
+ expect(mapMessageForApi({ ...baseRow, clientNonce: null }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel").clientNonce)
+ .toBeNull()
})
})
describe("mapMessageForWs", () => {
it("preserves the required server seq", () => {
- expect(mapMessageForWs(baseRow, emptyWsCtx).seq).toBe(42)
+ expect(mapMessageForWs(baseRow, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").seq).toBe(42)
})
it("maps ordinary rows to type: \"chat\" (was \"default\" before #12's exhaustive discriminator)", () => {
- expect(mapMessageForWs({ ...baseRow, type: null }, emptyWsCtx).type).toBe("chat")
- expect(mapMessageForWs({ ...baseRow, type: "default" }, emptyWsCtx).type).toBe("chat")
- expect(mapMessageForWs({ ...baseRow, type: "system" }, emptyWsCtx).type).toBe("system")
+ expect(mapMessageForWs({ ...baseRow, type: null }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").type).toBe("chat")
+ expect(mapMessageForWs({ ...baseRow, type: "default" }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").type).toBe("chat")
+ expect(mapMessageForWs({ ...baseRow, type: "system" }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").type).toBe("system")
})
it("splits `type: \"thread_created\"` into { type: \"system\", systemKind: \"thread\" } for both mappers", () => {
- const wsOut = mapMessageForWs({ ...baseRow, type: "thread_created" }, emptyWsCtx)
+ const wsOut = mapMessageForWs({ ...baseRow, type: "thread_created" }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(wsOut.type).toBe("system")
expect(wsOut.systemKind).toBe("thread")
- const apiOut = mapMessageForApi({ ...baseRow, type: "thread_created" }, emptyApiCtx)
+ const apiOut = mapMessageForApi({ ...baseRow, type: "thread_created" }, emptyApiCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(apiOut.type).toBe("system")
expect(apiOut.systemKind).toBe("thread")
})
it("a bare `type: \"system\"` row (no known kind) round-trips to { type: \"system\" } with systemKind omitted", () => {
- const out = mapMessageForWs({ ...baseRow, type: "system" }, emptyWsCtx)
+ const out = mapMessageForWs({ ...baseRow, type: "system" }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.type).toBe("system")
expect(out.systemKind).toBeUndefined()
})
it("carries replyTo and mentionType — regression for the thread-payload skip bug", () => {
- const replyMap = new Map([["m0", { id: "m0", authorName: "Bob", content: "hey there" }]])
+ const replyMap = new Map([["m0", { id: "m0", authorId: "bob", authorName: "Bob", content: "hey there" }]])
const out = mapMessageForWs(
{ ...baseRow, replyToId: "m0", mentionType: "everyone" },
- { ...emptyWsCtx, replyMap },
+ { ...emptyWsCtx, replyMap }, BUSINESS_SCHEMA_VERSION, "channel"
)
- expect(out.replyTo).toEqual({ id: "m0", authorName: "Bob", text: "hey there" })
+ expect(out.replyTo).toEqual({ id: "m0", authorId: "bob", authorName: "Bob", text: "hey there" })
expect(out.mentionType).toBe("everyone")
})
it("narrows non-array embeds to undefined (WS schema demands unknown[])", () => {
- expect(mapMessageForWs({ ...baseRow, embeds: null }, emptyWsCtx).embeds).toBeUndefined()
- expect(mapMessageForWs({ ...baseRow, embeds: { foo: 1 } }, emptyWsCtx).embeds).toBeUndefined()
- expect(mapMessageForWs({ ...baseRow, embeds: [{ url: "x" }] }, emptyWsCtx).embeds).toEqual([{ url: "x" }])
+ expect(mapMessageForWs({ ...baseRow, embeds: null }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").embeds).toBeUndefined()
+ expect(mapMessageForWs({ ...baseRow, embeds: { foo: 1 } }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").embeds).toBeUndefined()
+ expect(mapMessageForWs({ ...baseRow, embeds: [{ url: "x" }] }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").embeds).toEqual([{ url: "x" }])
})
it("returns raw attachment shape (id/filename/url/contentType/size)", () => {
const out = mapMessageForWs(baseRow, {
...emptyWsCtx,
- attachments: [
- { id: "a1", filename: "x.png", url: "/x.png", contentType: "image/png", size: 4096 },
+ resourceAttachments: [
+ { id: "a1", name: "x.png", url: "/x.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: 4096, width: null, height: null },
],
- })
+ }, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.attachments).toEqual([
- { id: "a1", filename: "x.png", url: "/x.png", contentType: "image/png", size: 4096 },
+ { id: "a1", name: "x.png", url: "/x.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: 4096, width: null, height: null },
])
})
it("omits attachments when the raw list is empty", () => {
- expect(mapMessageForWs(baseRow, emptyWsCtx).attachments).toBeUndefined()
+ expect(mapMessageForWs(baseRow, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").attachments).toEqual([])
})
it("includes width/height on an image attachment when present on the input", () => {
const out = mapMessageForWs(baseRow, {
...emptyWsCtx,
- attachments: [
- { id: "a1", filename: "x.png", url: "/x.png", contentType: "image/png", size: 4096, width: 1920, height: 1080 },
+ resourceAttachments: [
+ { id: "a1", name: "x.png", url: "/x.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: 4096, width: 1920, height: 1080 },
],
- })
+ }, BUSINESS_SCHEMA_VERSION, "channel")
expect(out.attachments).toEqual([
- { id: "a1", filename: "x.png", url: "/x.png", contentType: "image/png", size: 4096, width: 1920, height: 1080 },
+ { id: "a1", name: "x.png", url: "/x.png", thumbnailUrl: null, contentType: "image/png", sizeBytes: 4096, width: 1920, height: 1080 },
])
})
it("coerces null content to empty string (attachments-only message)", () => {
- expect(mapMessageForWs({ ...baseRow, content: null }, emptyWsCtx).content).toBe("")
+ expect(mapMessageForWs({ ...baseRow, content: null }, emptyWsCtx, BUSINESS_SCHEMA_VERSION, "channel").content).toBe("")
})
})
describe("attachment contract selection", () => {
- it("keeps NULL metadata in 3 and preserves the original absent size field in 1/2", () => {
+ it("keeps exact nullable attachment facts only on the current contract", () => {
const attachment = { id: "attachment", name: "file.bin", url: "/file", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }
const ctx = { ...emptyApiCtx, attachmentsByMessage: { m1: [attachment] } }
- for (const contract of [1, 2] as const) {
- const value = JSON.parse(JSON.stringify(mapMessageForApi(baseRow, ctx, contract)))
- expect(value.attachments).toEqual([{ kind: "file", name: "file.bin", url: "/file" }])
- }
- expect(mapMessageForApi({ ...baseRow, authorAvatarVersion: 2 }, ctx, 3, "channel").attachments).toEqual([attachment])
+ for (const contract of [1, 2, 3, 6]) expect(() => mapMessageForApi(baseRow, ctx, contract, "channel")).toThrow("protocol mismatch")
+ expect(mapMessageForApi({ ...baseRow, authorAvatarVersion: 2 }, ctx, BUSINESS_SCHEMA_VERSION, "channel").attachments).toEqual([attachment])
})
})
@@ -223,13 +222,13 @@ describe("single-message creation payload hydration", () => {
creationMocks.reactions.mockResolvedValue([])
})
it.each(["default", "friend_approval"])("does not query creation requests for %s", async type => {
- await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type, channelId: "dm" }, 3)
+ await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type, channelId: "dm" }, BUSINESS_SCHEMA_VERSION)
expect(creationMocks.hydrate).not.toHaveBeenCalled()
})
it("hydrates a creation card with the same immutable owner identity", async () => {
const payload = botCreationFixture()
creationMocks.hydrate.mockResolvedValue(new Map([[baseRow.id, payload]]))
- const message = await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type: "bot_creation_request", channelId: "dm" }, 3)
+ const message = await readCommunityMessageResource({} as never, "viewer", { ...baseRow, type: "bot_creation_request", channelId: "dm" }, BUSINESS_SCHEMA_VERSION)
expect(creationMocks.hydrate).toHaveBeenCalledExactlyOnceWith({}, [baseRow.id], "viewer")
expect(message.botCreation).toEqual(payload)
expect(message.botCreation).not.toHaveProperty("canDecide")
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index ae2a20e1d..686afc84a 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -14,36 +14,32 @@
* embeds pass-through, and mentionType projection so adding/removing a
* field on the wire is one edit, not four.
*/
-import { CommunityMessageResourceSchema, queries, truncateMessagePreview, type CommunityContract, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment, type CommunityLegacyMessageCreate } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityMessageResourceSchema, CommunityMessageResourcesSchema, communityMessageProfileIds, queries, truncateMessagePreview, type CommunityContract, type Database, type MentionType, type CommunityMessageResource, type CommunityMessageAttachment } from "@alook/shared"
import type { BotCreationPayload, FriendApprovalPayload } from "@alook/shared"
-import { avatarInitial } from "@/lib/community/avatar"
+
+import { readCommunityResourceProfiles } from "./resource-profiles.server"
import { canonicalUserImage } from "@/lib/community/storage"
import { projectMessageWireType } from "@/lib/community/message-wire-type"
import { groupAttachments, groupReactions } from "./messages"
-import { presentMessageAttachment } from "./attachment-presentation"
export type MessageRow = Pick<Awaited<ReturnType<typeof queries.communityMessage.getMessagesByIdsInScope>>[number],
"id" | "authorId" | "authorName" | "authorImage" | "authorAvatarVersion" | "mentionType" | "replyToId" | "seq" | "createdAt"> & { content: string | null; type: string | null; embeds: unknown; clientNonce?: string | null; friendshipId?: string | null }
type ReplyTargetRow = Pick<MessageRow, "id" | "authorId" | "authorName" | "content">
-type WsAttachment = NonNullable<CommunityLegacyMessageCreate["message"]["attachments"]>[number]
type UiReaction = NonNullable<CommunityMessageResource["reactions"]>[number]
type ReplyPreview = NonNullable<CommunityMessageResource["replyTo"]>
type ThreadPreview = NonNullable<CommunityMessageResource["thread"]>
/** Common fields shared by both API and WS variants — derived exactly once. */
-function coreFields(row: MessageRow, replyMap: Map<string, ReplyTargetRow>, nonce = row.clientNonce) {
- const clientNonce = nonce && !nonce.startsWith("srv:") ? nonce : undefined
+function coreFields(row: MessageRow, replyMap: Map<string, ReplyTargetRow>) {
return {
...projectMessageWireType(row.type),
- ...(clientNonce ? { clientNonce } : {}),
replyTo: resolveReply(row, replyMap),
id: row.id,
authorId: row.authorId,
authorName: row.authorName,
- authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion)
- ?? avatarInitial(row.authorName),
+ authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion),
authorAvatarVersion: row.authorAvatarVersion,
// `content` is nullable in the DB (empty message with attachments) but
// both the API response and the WS payload treat it as string; coerce
@@ -78,6 +74,7 @@ function resolveReply(row: MessageRow, replyMap: Map<string, ReplyTargetRow>): R
}
export type ApiMessageContext = {
+ viewerId: string
replyMap: Map<string, ReplyTargetRow>
attachmentsByMessage: Record<string, CommunityMessageAttachment[] | undefined>
reactionsByMessage: Record<string, UiReaction[] | undefined>
@@ -95,7 +92,7 @@ export async function loadApiMessageContext(db: Database, userId: string, ids: s
readReplies(),
])
const attachmentsByMessage = groupAttachments(attachments), reactionsByMessage = groupReactions(reactions, userId)
- return (channelId: string): ApiMessageContext => ({ attachmentsByMessage, reactionsByMessage,
+ return (channelId: string): ApiMessageContext => ({ viewerId: userId, attachmentsByMessage, reactionsByMessage,
replyMap: new Map(replies.filter((reply) => reply.channelId === channelId).map((reply) => [reply.id, reply])),
})
}
@@ -121,90 +118,52 @@ export async function readCommunityMessageResource(db: Database, userId: string,
// 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, contract: CommunityContract = 1, channelId?: string) {
- if (contract === 3) return CommunityMessageResourceSchema.strip().parse({
+export function mapMessageForApi(row: MessageRow, ctx: ApiMessageContext, contract: number = BUSINESS_SCHEMA_VERSION, channelId?: string) {
+ if (contract !== BUSINESS_SCHEMA_VERSION) throw new Error("Message resource protocol mismatch")
+ return mapMessageResource(row, ctx, channelId, row.authorId === ctx.viewerId ? row.clientNonce ?? null : null)
+}
+
+function mapMessageResource(row: MessageRow, ctx: Omit<ApiMessageContext, "viewerId">, channelId: string | undefined, clientNonce: string | null) {
+ return CommunityMessageResourceSchema.parse({
...coreFields(row, ctx.replyMap), channelId,
authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion),
- clientNonce: row.clientNonce && !row.clientNonce.startsWith("srv:") ? row.clientNonce : null,
+ clientNonce: clientNonce && !clientNonce.startsWith("srv:") ? clientNonce : null,
attachments: ctx.attachmentsByMessage[row.id] ?? [],
...(Array.isArray(row.embeds) ? { embeds: row.embeds } : {}),
reactions: ctx.reactionsByMessage[row.id], thread: ctx.threadByMessageId?.get(row.id),
approval: ctx.approvalByMessageId?.get(row.id),
botCreation: ctx.botCreationByMessageId?.get(row.id),
})
- return {
- ...coreFields(row, ctx.replyMap),
- embeds: row.embeds,
- attachments: ctx.attachmentsByMessage[row.id]?.length ? ctx.attachmentsByMessage[row.id]!.map((attachment) => {
- const presented = presentMessageAttachment(attachment)
- return presented.kind === "file" && attachment.sizeBytes == null ? { ...presented, size: undefined } : presented
- }) : undefined,
- reactions: ctx.reactionsByMessage[row.id]?.length ? ctx.reactionsByMessage[row.id] : undefined,
- thread: ctx.threadByMessageId?.get(row.id),
- approval: ctx.approvalByMessageId?.get(row.id),
- botCreation: ctx.botCreationByMessageId?.get(row.id),
- }
}
-export async function mapPostedMessageForApi(db: Database, channelId: string, row: MessageRow, contract: CommunityContract = 2) {
+export async function mapPostedMessageForApi(db: Database, channelId: string, row: MessageRow, contract: number = BUSINESS_SCHEMA_VERSION) {
+ if (contract !== BUSINESS_SCHEMA_VERSION) throw new Error("Posted message protocol mismatch")
const [replies, attachments] = await Promise.all([
row.replyToId ? queries.communityMessage.getMessagesByIdsInScope(db, [row.replyToId], { channelId }) : Promise.resolve([]),
- contract === 3 ? queries.communityAttachment.listByMessageIds(db, [row.id]) : Promise.resolve([]),
+ queries.communityAttachment.listByMessageIds(db, [row.id]),
])
- const replyMap = new Map(replies.filter((reply) => reply.channelId === channelId).map((reply) => [reply.id, reply]))
- const attachmentsByMessage = groupAttachments(attachments)
- if (contract === 3) return mapMessageForApi(row, { replyMap, attachmentsByMessage, reactionsByMessage: {} }, 3, channelId)
- return { ...row, replyTo: resolveReply(row, replyMap) }
+ const replyMap = new Map(replies.filter(reply => reply.channelId === channelId).map(reply => [reply.id, reply]))
+ return mapMessageForApi(row, { viewerId: row.authorId, replyMap, attachmentsByMessage: groupAttachments(attachments), reactionsByMessage: {} }, contract, channelId)
}
export type WsMessageContext = {
replyMap: Map<string, ReplyTargetRow>
- attachments: WsAttachment[]
- resourceAttachments?: CommunityMessageAttachment[]
- /**
- * The sender's client-provided idempotency nonce, echoed on the broadcast so
- * the sender's optimistic row can be reconciled in place (see
- * `CommunityMessageCreate.message.clientNonce`). Pass the RAW client nonce
- * (undefined when the client sent none); the `srv:`-prefixed server fallback
- * is filtered out below so a content fingerprint never reaches the wire.
- */
+ resourceAttachments: CommunityMessageAttachment[]
clientNonce?: string
botCreation?: BotCreationPayload
}
-export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext, contract: CommunityContract = 2, channelId?: string) {
- if (contract === 3) return CommunityMessageResourceSchema.required({ authorName: true, authorAvatarVersion: true }).parse({
- ...coreFields(row, ctx.replyMap, ctx.clientNonce ?? null),
- botCreation: ctx.botCreation,
- channelId,
- authorAvatar: canonicalUserImage(row.authorId, row.authorImage, row.authorAvatarVersion),
- clientNonce: ctx.clientNonce && !ctx.clientNonce.startsWith("srv:") ? ctx.clientNonce : null,
- attachments: ctx.resourceAttachments,
- embeds: Array.isArray(row.embeds) ? row.embeds : undefined,
- })
- // Echo ONLY a client-provided nonce, and never the `srv:`-prefixed server
- // fallback (a content fingerprint — a content-correlation leak on the
- // broadcast wire, and a fallback send has no client optimistic row to match
- // anyway). The prefix guard is defense-in-depth: callers pass the raw client
- // nonce, but if a `srv:` value ever reaches here it is dropped, not fanned.
- return {
- ...coreFields(row, ctx.replyMap, ctx.clientNonce ?? null),
- botCreation: ctx.botCreation,
- // The shared CommunityMessageCreate.embeds is `unknown[]` — narrow here
- // rather than widening the wire type.
- embeds: Array.isArray(row.embeds) ? row.embeds : undefined,
- attachments:
- ctx.attachments.length > 0
- ? ctx.attachments.map((a) => ({
- id: a.id,
- filename: a.filename,
- url: a.url,
- thumbnailUrl: a.thumbnailUrl,
- contentType: a.contentType,
- size: a.size,
- width: a.width,
- height: a.height,
- }))
- : undefined,
- }
+export function mapMessageForWs(row: MessageRow, ctx: WsMessageContext, contract: number = BUSINESS_SCHEMA_VERSION, channelId?: string) {
+ if (contract !== BUSINESS_SCHEMA_VERSION) throw new Error("Message resource protocol mismatch")
+ return mapMessageResource(row, {
+ replyMap: ctx.replyMap, attachmentsByMessage: { [row.id]: ctx.resourceAttachments }, reactionsByMessage: {},
+ botCreationByMessageId: ctx.botCreation ? new Map([[row.id, ctx.botCreation]]) : undefined,
+ }, channelId, ctx.clientNonce ?? row.clientNonce ?? null)
+}
+
+
+export async function readCommunityMessageProfiles(db: Database, messages: readonly CommunityMessageResource[]) {
+ const profiles = await readCommunityResourceProfiles(db, communityMessageProfileIds(messages))
+ CommunityMessageResourcesSchema.parse({ messages, profiles })
+ return profiles
}
diff --git a/src/web/src/lib/community/message-read.profile.dom.test.tsx b/src/web/src/lib/community/message-read.profile.dom.test.tsx
new file mode 100644
index 000000000..3e3c7e150
--- /dev/null
+++ b/src/web/src/lib/community/message-read.profile.dom.test.tsx
@@ -0,0 +1,188 @@
+import { createElement, Profiler } from "react"
+import { afterEach, expect, it, vi } from "vitest"
+import { COMMUNITY_CONTRACT_VERSION, CommunityMessagesReadSchema, encodeCommunityBrowserEvent, decodeCommunityBrowserEvent } from "@alook/shared"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+import { act, render, waitFor } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { resolveMessageTarget } from "@/lib/community/message-door"
+import { readCommunityConversationEntry } from "@/lib/community/conversation-entry.server"
+import { publishConversationEntry } from "@/lib/community/conversation-entry"
+import { planCommittedMessage } from "@/lib/community/message-dispatcher"
+import { readCommunityMessageWindow } from "@/lib/community/message-window.server"
+import { parseCommunityMessageWindow } from "@/lib/community/messages"
+import { decodeCommunityReadResponse } from "@/lib/community/read-response"
+import { writeCommunityMessagesRead } from "@/lib/community/read-contract"
+import { readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
+import { captureCommunityLiveSnapshotToken, publishCommunityResourceBundle, projectCommunityWsEventToDb } from "@/lib/community-db/sync"
+import { channelMessagesQueryFn } from "@/lib/community/message-window"
+import { useCanonicalMessagesById, useCanonicalCommunityProfile } from "@/lib/community-db/projections"
+import { Message } from "@/components/community/messages/message"
+const fixtures = vi.hoisted(() => ({ response: null as unknown }))
+vi.mock("@/lib/api/client", async importOriginal => ({ ...await importOriginal<typeof import("@/lib/api/client")>(), apiFetch: vi.fn(async () => fixtures.response) }))
+vi.mock("@/hooks/community/use-inbox", async importOriginal => ({ ...await importOriginal<typeof import("@/hooks/community/use-inbox")>(), useMessageMarked: () => false }))
+const stores: ReturnType<typeof createCommunitySqliteDb>[] = []
+afterEach(() => { for (const item of stores) item.sqlite.close(); stores.length = 0 })
+it.each(["messages", "entry", "committed-ws"].flatMap(scenario => [false, true].map(softDeleted => ({ scenario, softDeleted }))))("publishes the actual cold author graph before first native consumption ($scenario, soft=$softDeleted)", async ({ scenario, softDeleted }) => {
+ const store = createCommunitySqliteDb(); stores.push(store)
+ const { sqlite, db } = store
+ const stamp = "2026-10-28T00:00:00Z"
+ const expectedName = softDeleted ? "Deleted user" : "Former Author"
+ const insertUser = sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt") VALUES (?,?,?,?,0,?,?)')
+ for (const [id,name] of [["viewer","Viewer"],["former",expectedName]]) insertUser.run(id, `${id}@example.test`,name,"0001",stamp,stamp)
+ if (softDeleted) sqlite.prepare('UPDATE user SET "deletedAt"=? WHERE id=?').run(stamp, "former")
+ sqlite.exec("INSERT INTO community_user_profile (user_id,about_me,banner_color,status_emoji,status_text) VALUES ('former','Real about',null,null,null)")
+ sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES ('server','Server','0002','','viewer',?)").run(stamp)
+ sqlite.exec("INSERT INTO community_server_member (id,server_id,user_id,role) VALUES ('viewer-member','server','viewer','owner')")
+ sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at,creator_id,parent_channel_id,parent_message_id) VALUES ('channel','server','Channel','text','',0,0,1,?,'viewer',null,null)").run(stamp)
+ sqlite.prepare("INSERT INTO community_message (id,author_id,content,type,channel_id,seq,created_at,reply_to_id) VALUES ('message','former','Actual historic message','default','channel',1,?,null)").run(stamp)
+ expect(sqlite.prepare("SELECT id FROM community_server_member WHERE server_id='server' AND user_id='former'").get()).toBeUndefined()
+ const target = await resolveMessageTarget(db, "viewer", { id: "channel" }, "human")
+ if (!target.ok) throw new Error(JSON.stringify(target))
+ const result = await readCommunityMessageWindow(db, { viewerId: "viewer", target: target.value, window: parseCommunityMessageWindow(new URLSearchParams()), contract: COMMUNITY_CONTRACT_VERSION })
+ if (!result.ok) throw new Error(JSON.stringify(result))
+ const response = writeCommunityMessagesRead(new Request("http://localhost/api/community/channels/channel/messages"), "channel", result.page)
+ const body = await response.json()
+ let wireProfiles = CommunityMessagesReadSchema.parse(body).profiles
+ fixtures.response = decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body)
+ const { client, registry } = await createCommunityQueryOwner("viewer")
+ const structure = await readCommunityResourceBundle(db, "viewer", { channelIds: ["channel"] })
+ await act(async () => { publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) }) })
+ expect(registry.collections.profiles.get("former")).toBeUndefined()
+ function Consumer() {
+ useCanonicalCommunityProfile("former")
+ const rows = useCanonicalMessagesById(["message"])
+ const message = rows?.get("message")
+ return message ? createElement(Message, { m: { ...message, grouped: false }, onOpenThread: () => {}, viewerUserId: "viewer" }) : createElement("span", { "data-testid": "waiting-message" }, "Waiting")
+ }
+ const frames: string[] = []
+ const container = document.createElement("div")
+ document.body.appendChild(container)
+ const view = render(createElement(Profiler, { id: "cold-message-author", onRender: () => {
+ const name = container.querySelector("[data-message-author-line] button")?.textContent
+ if (name) frames.push(name)
+ } }, createElement(Consumer)), { container, wrapper: ({ children }) => createElement(CommunityTestProvider, { client, registry, userId: "viewer", retainOwner: true }, children) })
+ expect(view.getByTestId("waiting-message")).toBeDefined()
+ if (scenario === "messages") {
+ await act(async () => { await channelMessagesQueryFn("channel", null, { queryClient: client })({ pageParam: { mode: "newest" } }) })
+ } else if (scenario === "entry") {
+ const entry = await readCommunityConversationEntry(db, { viewerId: "viewer", target: target.value, window: parseCommunityMessageWindow(new URLSearchParams()), preferTail: true })
+ if (!entry.ok) throw new Error(JSON.stringify(entry))
+ wireProfiles = entry.entry.profiles
+ await act(async () => { publishConversationEntry(client, { serverId: "server", channelId: "channel" }, entry.entry, { token: captureCommunityLiveSnapshotToken(client, "channel") }) })
+ } else {
+ const plan = await planCommittedMessage(db, "message")
+ const encoded = encodeCommunityBrowserEvent(plan.messageEvent)
+ if (!encoded.ok) throw new Error(JSON.stringify(encoded))
+ const decoded = decodeCommunityBrowserEvent(encoded.envelope)
+ if (!decoded.ok) throw new Error(JSON.stringify(decoded))
+ wireProfiles = plan.messageEvent.profiles
+ await act(async () => { projectCommunityWsEventToDb(client, decoded.event) })
+ }
+ await waitFor(() => expect(view.container.textContent).toContain("Actual historic message"))
+ expect(wireProfiles).toEqual(expect.arrayContaining([expect.objectContaining({ id: "former", name: expectedName, discriminator: "0001", avatar: null, avatarVersion: 0 })]))
+ expect(registry.collections.profiles.get("former")).toMatchObject({ id: "former", name: expectedName, aboutMe: "Real about", bannerColor: null, statusEmoji: null, statusText: null })
+ expect(view.container.querySelector("[data-message-author-line]")?.textContent).toContain(expectedName)
+ expect(frames.length).toBeGreaterThan(0)
+ expect(frames.every(name => name === expectedName)).toBe(true)
+})
+
+it.each(["initial", "two-hop"])("carries the actual SQL approval author through strict encoding and first native consumption (%s)", async scenario => {
+ const { queries } = await import("@alook/shared")
+ const store = createCommunitySqliteDb(); stores.push(store)
+ const { sqlite, db } = store
+ const stamp = "2026-10-28T00:00:00Z"
+ const insert = sqlite.prepare('INSERT INTO user (id,email,name,discriminator,image,"avatarVersion","createdAt","updatedAt","isBot","ownerUserId") VALUES (?,?,?,?,?,?,?,?,?,?)')
+ for (const [id, name, bot, owner, version] of [["human1","Human",0,null,0],["owner1","Owner One",0,null,0],["owner2","Owner Two",0,null,0],["bot1","First Bot",1,"owner1",7],["bot2","Second Bot",1,"owner2",9]] as const) insert.run(id, `${id}@example.test`, name, "0042", null, version, stamp, stamp, bot, owner)
+ sqlite.exec("INSERT INTO community_user_profile (user_id,about_me,status_emoji,status_text) VALUES ('bot1','First real about',null,null),('bot2','Second real about',null,null)")
+ const request = await queries.communityFriendship.sendRequest(db, { requesterId: scenario === "initial" ? "human1" : "bot1", addresseeId: scenario === "initial" ? "bot1" : "bot2" })
+ const result = scenario === "initial" ? request : await queries.communityFriendship.ownerDecideOnRow(db, { friendshipId: request.friendship.id, actorId: "owner1", decision: "approve" })
+ if ("ok" in result && !result.ok) throw new Error(result.reason)
+ const viewer = scenario === "initial" ? "owner1" : "owner2"
+ const author = scenario === "initial" ? "bot1" : "bot2"
+ const expectedName = scenario === "initial" ? "First Bot" : "Second Bot"
+ const creates = result.broadcasts.filter(broadcast => broadcast.event.type === "community:message.create")
+ expect(creates).toHaveLength(1)
+ expect(creates[0].userId).toBe(viewer)
+ const encoded = encodeCommunityBrowserEvent(creates[0].event)
+ if (!encoded.ok) throw new Error(JSON.stringify(encoded))
+ const decoded = decodeCommunityBrowserEvent(encoded.envelope)
+ if (!decoded.ok || decoded.event.type !== "community:message.create") throw new Error(JSON.stringify(decoded))
+ const event = decoded.event
+ expect(event.message.authorId).toBe(author)
+ expect(event.message.approval).toMatchObject({ friendshipId: request.friendship.id, status: "pending", waitingOn: "you", botProfile: { id: author, name: expectedName, discriminator: "0042", image: null, avatarVersion: scenario === "initial" ? 7 : 9 } })
+ expect(event.message.content).toContain(expectedName)
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_message").get()).toMatchObject({ count: scenario === "initial" ? 1 : 2 })
+ expect(sqlite.prepare("SELECT status,needs_owner_approval AS owner FROM community_friendship WHERE id=?").get(request.friendship.id)).toMatchObject({ status: "pending", owner: viewer })
+ const { client, registry } = await createCommunityQueryOwner(viewer)
+ const structure = await readCommunityResourceBundle(db, viewer, { channelIds: [event.channelId] })
+ publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
+ expect(registry.collections.profiles.get(author)).toBeUndefined()
+ function Consumer() {
+ useCanonicalCommunityProfile(author)
+ const rows = useCanonicalMessagesById([event.message.id])
+ const message = rows?.get(event.message.id)
+ return message ? createElement(Message, { m: { ...message, grouped: false }, onOpenThread: () => {}, viewerUserId: viewer }) : createElement("span", null, "Waiting")
+ }
+ const frames: string[] = []
+ const container = document.createElement("div"); document.body.appendChild(container)
+ const view = render(createElement(Profiler, { id: "approval-author", onRender: () => {
+ const name = container.querySelector("[data-message-author-line] button")?.textContent
+ if (name) frames.push(name)
+ } }, createElement(Consumer)), { container, wrapper: ({ children }) => createElement(CommunityTestProvider, { client, registry, userId: viewer, retainOwner: true }, children) })
+ await act(async () => { projectCommunityWsEventToDb(client, event) })
+ await waitFor(() => expect(view.container.querySelector("[data-message-author-line]")?.textContent).toContain(expectedName))
+ expect(frames.length).toBeGreaterThan(0)
+ expect(frames.every(name => name === expectedName)).toBe(true)
+ expect(registry.collections.profiles.get(author)).toMatchObject({ name: expectedName, discriminator: "0042", avatar: null, avatarVersion: scenario === "initial" ? 7 : 9, aboutMe: scenario === "initial" ? "First real about" : "Second real about", statusEmoji: null, statusText: null })
+})
+
+it.each([false, true])("keeps current actual DB profile facts on first native consumption of a retained old create (warm=%s)", async warm => {
+ const { queries } = await import("@alook/shared")
+ const store = createCommunitySqliteDb(); stores.push(store)
+ const { sqlite, db } = store
+ const stamp = "2026-10-28T00:00:00Z"
+ const insert = sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt") VALUES (?,?,?,?,0,?,?)')
+ insert.run("viewer", "[email protected]", "Viewer", "0042", stamp, stamp)
+ insert.run("former", "[email protected]", "Before", "0043", stamp, stamp)
+ sqlite.exec("INSERT INTO community_user_profile (user_id,about_me,banner_color,status_emoji,status_text) VALUES ('former','Before about',null,'old','Before status')")
+ sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES ('server','Server','0044','','viewer',?)").run(stamp)
+ sqlite.exec("INSERT INTO community_server_member (id,server_id,user_id,role) VALUES ('member','server','viewer','owner')")
+ sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at,creator_id,parent_channel_id,parent_message_id) VALUES ('channel','server','Channel','text','',0,0,1,?,'viewer',null,null)").run(stamp)
+ sqlite.prepare("INSERT INTO community_message (id,author_id,content,type,channel_id,seq,created_at,reply_to_id) VALUES ('retained','former','Retained message','default','channel',1,?,null)").run(stamp)
+ const plan = await planCommittedMessage(db, "retained")
+ const encoded = encodeCommunityBrowserEvent(plan.messageEvent)
+ if (!encoded.ok) throw new Error(JSON.stringify(encoded))
+ const { client, registry } = await createCommunityQueryOwner("viewer")
+ const structure = await readCommunityResourceBundle(db, "viewer", { channelIds: ["channel"], ...(warm ? { profileIds: ["former"] } : {}) })
+ publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
+ const frames: string[] = []
+ function Consumer() {
+ useCanonicalCommunityProfile("former")
+ const message = useCanonicalMessagesById(["retained"])?.get("retained")
+ return message ? createElement(Message, { m: { ...message, grouped: false }, onOpenThread: () => {}, viewerUserId: "viewer" }) : createElement("span", null, "Waiting")
+ }
+ const container = document.createElement("div"); document.body.appendChild(container)
+ const view = render(createElement(Profiler, { id: "retained-author", onRender: () => {
+ const name = container.querySelector("[data-message-author-line] button")?.textContent
+ if (name) frames.push(name)
+ } }, createElement(Consumer)), { container, wrapper: ({ children }) => createElement(CommunityTestProvider, { client, registry, userId: "viewer", retainOwner: true }, children) })
+ sqlite.exec("UPDATE user SET name='After',avatarVersion=2 WHERE id='former'; UPDATE community_user_profile SET about_me='After about',banner_color='blue',status_emoji=null,status_text=null WHERE user_id='former'")
+ const [fresh] = await queries.communityUserProfile.getResourceProfiles(db, ["former"])
+ if (!fresh || fresh.aboutMe === undefined || fresh.bannerColor === undefined || fresh.statusEmoji === undefined || fresh.statusText === undefined) throw new Error("Actual DB profile facts missing")
+ await act(async () => {
+ projectCommunityWsEventToDb(client, { type: "community:profile.update", userId: fresh.id, name: fresh.name, discriminator: fresh.discriminator, aboutMe: fresh.aboutMe!, bannerColor: fresh.bannerColor!, kind: "human", ownerUserId: null })
+ if (!warm) expect(registry.collections.profiles.has("former")).toBe(false)
+ projectCommunityWsEventToDb(client, { type: "community:status.update", userId: fresh.id, statusEmoji: fresh.statusEmoji!, statusText: fresh.statusText! })
+ if (!warm) expect(registry.collections.profiles.has("former")).toBe(false)
+ projectCommunityWsEventToDb(client, { type: "community:identity.update", userId: fresh.id, avatar: fresh.avatar, avatarVersion: fresh.avatarVersion })
+ })
+ const decoded = decodeCommunityBrowserEvent(encoded.envelope)
+ if (!decoded.ok) throw new Error(JSON.stringify(decoded))
+ await act(async () => { for (let delivery = 0; delivery < 3; delivery++) projectCommunityWsEventToDb(client, decoded.event) })
+ await waitFor(() => expect(view.container.querySelector("[data-message-author-line]")?.textContent).toContain("After"))
+ expect(frames.length).toBeGreaterThan(0)
+ expect(frames.every(name => name === "After")).toBe(true)
+ expect(registry.collections.profiles.get("former")).toMatchObject(fresh)
+ expect(registry.collections.messages.get("retained")?.authorName).toBe("Before")
+})
diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.ts
index a2b7c12fe..0c5ca99c1 100644
--- a/src/web/src/lib/community/message-stream.test.ts
+++ b/src/web/src/lib/community/message-stream.test.ts
@@ -1,3 +1,4 @@
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it } from "vitest"
import type { Msg } from "@/lib/community/models/message"
import {
@@ -15,7 +16,7 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { ingestMessages } from "@/lib/community-db/sync"
function message(id: string, seq: number, extra: Partial<CanonicalMessage> = {}): CanonicalMessage {
- return {
+ return messageResourceFixture({ channelId: "channel",
id,
seq,
type: "chat",
@@ -24,7 +25,7 @@ function message(id: string, seq: number, extra: Partial<CanonicalMessage> = {})
content: id,
createdAt: `2026-08-06T00:00:${String(seq).padStart(2, "0")}.000Z`,
...extra,
- }
+ })
}
function localMessage(content: string): NewOutboxIntent["message"] {
@@ -501,10 +502,10 @@ describe("attachment ownership effects", () => {
})
return apply(ws.state, {
type: "baseChanged",
- messages: [canonical("mf", 20, "files")],
+ messages: [canonical("mf", 20, "files", { attachments: settledResourceAttachments })],
}).state
}],
- ])("preserves settled attachments through a lagging canonical %s", (_label, arrange) => {
+ ])("preserves settled attachments through matching full canonical %s", (_label, arrange) => {
let state = submit(emptyMessageOverlay(), attachedIntent())
state = apply(state, {
type: "uploadSettled",
@@ -553,7 +554,7 @@ describe("attachment ownership effects", () => {
}).state
const replacementCanonical = canonical("mf", 20, "files", {
- attachments: [{ id: "replacement", name: "canonical.txt", url: "/media/canonical", sizeBytes: 2048 }],
+ attachments: [{ id: "replacement", name: "canonical.txt", url: "/media/canonical", sizeBytes: 2048, thumbnailUrl: null, contentType: null, width: null, height: null }],
})
state = apply(state, {
type: "baseChanged",
@@ -561,7 +562,7 @@ describe("attachment ownership effects", () => {
}).state
expect(state.liveIds).toContain("mf")
- expect(canonicalRows().get("mf")?.attachments).toEqual([{ id: "replacement", name: "canonical.txt", url: "/media/canonical", sizeBytes: 2048 }])
+ expect(canonicalRows().get("mf")?.attachments).toEqual([{ id: "replacement", name: "canonical.txt", url: "/media/canonical", sizeBytes: 2048, thumbnailUrl: null, contentType: null, width: null, height: null }])
expect(materializeMessageStream([replacementCanonical], state)[0]?.attachments).toEqual(
replacement,
)
diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.ts
index 9df0a7450..3bd958745 100644
--- a/src/web/src/lib/community/message-stream.ts
+++ b/src/web/src/lib/community/message-stream.ts
@@ -1,5 +1,5 @@
import type { Msg, SendAttachment, CanonicalMessage } from "@/lib/community/models/message"
-import type { MentionType, CommunityMessagePreview } from "@alook/shared"
+import type { MentionType } from "@alook/shared"
import { presentCanonicalMessage } from "@/lib/community/message-wire"
import { presentMessageAttachment } from "@/lib/community/attachment-presentation"
@@ -104,7 +104,7 @@ function updateIntent(
return { state: { ...state, outboxByNonce }, effects: [] }
}
-function compoundIdentity(message: Pick<CommunityMessagePreview, "authorId" | "clientNonce">): string | undefined {
+function compoundIdentity(message: Partial<Pick<CanonicalMessage, "authorId" | "clientNonce">>): string | undefined {
return message.authorId && message.clientNonce && !message.clientNonce.startsWith("srv:")
? JSON.stringify([message.authorId, message.clientNonce]) : undefined
}
diff --git a/src/web/src/lib/community/message-window.test.ts b/src/web/src/lib/community/message-window.test.ts
index cada9dac8..50c593365 100644
--- a/src/web/src/lib/community/message-window.test.ts
+++ b/src/web/src/lib/community/message-window.test.ts
@@ -1,3 +1,4 @@
+import { messageResourceFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { InfiniteQueryObserver } from "@tanstack/react-query"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
@@ -36,10 +37,10 @@ describe("native message window identity", () => {
it("uses native bidirectional pages and stores only references while the canonical owner holds bodies", async () => {
const { client, registry } = await createCommunityQueryOwner()
- const row = (id: string, seq: number) => ({ id, channelId: "c1", type: "chat", seq, createdAt: `2026-10-01T00:00:0${seq}.000Z`, content: `Body ${seq}` })
- load.mockResolvedValueOnce({ messages: [row("m2", 2)], olderCursor: "older", newerCursor: "newer", hasMoreOlder: true, hasMoreNewer: true, latestSeq: 3 })
- .mockResolvedValueOnce({ messages: [row("m1", 1)], hasMoreOlder: false, hasMoreNewer: true, newerCursor: "m2", latestSeq: 3 })
- .mockResolvedValueOnce({ messages: [row("m3", 3)], hasMoreOlder: true, hasMoreNewer: false, olderCursor: "m2", latestSeq: 3 })
+ const row = (id: string, seq: number) => messageResourceFixture({ id, channelId: "c1", seq, createdAt: `2026-10-01T00:00:0${seq}.000Z`, content: `Body ${seq}` })
+ load.mockResolvedValueOnce({ profiles: [profileResourceFixture()], messages: [row("m2", 2)], olderCursor: "older", newerCursor: "newer", hasMoreOlder: true, hasMoreNewer: true, latestSeq: 3 })
+ .mockResolvedValueOnce({ profiles: [profileResourceFixture()], messages: [row("m1", 1)], hasMoreOlder: false, hasMoreNewer: true, newerCursor: "m2", latestSeq: 3 })
+ .mockResolvedValueOnce({ profiles: [profileResourceFixture()], messages: [row("m3", 3)], hasMoreOlder: true, hasMoreNewer: false, olderCursor: "m2", latestSeq: 3 })
const options = messageWindowOptions(client, "c1", { mode: "anchor", anchor: "m2" }, "tag")
await client.infiniteQuery({ ...options, select: undefined })
const observer = new InfiniteQueryObserver(client, { ...options, enabled: false })
diff --git a/src/web/src/lib/community/message-window.ts b/src/web/src/lib/community/message-window.ts
index 0e1a1cacd..f5ca60e63 100644
--- a/src/web/src/lib/community/message-window.ts
+++ b/src/web/src/lib/community/message-window.ts
@@ -1,12 +1,13 @@
+import { COMMUNITY_RESOURCE_CONTRACT_VERSION } from "@alook/shared"
import { infiniteQueryOptions, type InfiniteData, type QueryClient, type QueryKey } from "@tanstack/react-query"
import type { ApiRequestOptions } from "@/lib/api/client"
-import type { CommunityMessageSurfaceReceipt } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, type CommunityMessageSurfaceReceipt } from "@alook/shared"
import { actionAttributes } from "@/lib/observability/context"
import { emitTelemetry, telemetryGeneration } from "@/lib/observability/telemetry"
import { apiFetchCommunity } from "./account-cache-lifecycle"
import { captureCommunityLiveSnapshotToken, publishCommunityMessages } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
-import { messageWindowPage, type MessagesPage as WireMessagesPage, type MessagesWindowPage as MessagesPage, type MessagesPageParam } from "./models/message"
+import { messageWindowPage, type MessagesReadPage as WireMessagesPage, type MessagesWindowPage as MessagesPage, type MessagesPageParam } from "./models/message"
import { conversationReadRetryPolicy, withConversationReadDeadline } from "./conversation-read"
type MessagesTransportPage = WireMessagesPage & {
@@ -50,7 +51,7 @@ async function fetchMessagesTransport(
): Promise<WireMessagesPage> {
const transport = await withConversationReadDeadline(signal, (readSignal) => apiFetchCommunity<MessagesTransportPage>(
url,
- { signal: readSignal, observation: typeof options?.observation === "function" ? options.observation() : options?.observation }, token,
+ { signal: readSignal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_RESOURCE_CONTRACT_VERSION) }, observation: typeof options?.observation === "function" ? options.observation() : options?.observation }, token,
))
const { surfaceReceipt: _surfaceReceipt, ...page } = transport
return page
@@ -88,6 +89,7 @@ export const channelMessagesQueryFn =
const result = publishCommunityMessages(originalClient, {
channelId,
messages: page.messages,
+ profiles: page.profiles,
proof: { token: publicationToken, signal },
})
if (result === "published" && generation === telemetryGeneration()) emitTelemetry("data.publish", { ...actionAttributes(observation?.action ?? observation?.page), source: "network", cache_stage: "canonical", request_reason: observation?.reason ?? "unknown", eligibility: "eligible", outcome: "success" })
diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.ts
index 1c8216225..4c2df21fe 100644
--- a/src/web/src/lib/community/message-wire.test.ts
+++ b/src/web/src/lib/community/message-wire.test.ts
@@ -1,3 +1,4 @@
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
import { describe, expect, it } from "vitest"
import type { CommunityMessageCreate } from "@alook/shared"
import { presentCanonicalMessage, projectCommunityMessageCreate, projectPostedMessage } from "./message-wire"
@@ -5,7 +6,8 @@ import { presentCanonicalMessage, projectCommunityMessageCreate, projectPostedMe
function wire(
overrides: Partial<CommunityMessageCreate["message"]> = {},
): CommunityMessageCreate["message"] {
- return {
+ return messageResourceFixture({
+ channelId: "channel-1",
id: "m1",
seq: 42,
authorId: "u1",
@@ -15,35 +17,36 @@ function wire(
type: "chat",
createdAt: "2026-08-06T00:00:00.000Z",
...overrides,
- }
+ })
}
describe("projectCommunityMessageCreate", () => {
- it("presents sparse thread participants without altering stored facts", () => {
+ it("presents full thread participants without altering stored facts", () => {
const thread = { id: "thread", name: null, messageCount: 2, lastReplyAt: null, participants: [
- { id: "unknown" },
- { id: "initial", name: "Peer", avatar: null },
+ { id: "unknown", name: "", avatar: null, avatarVersion: 0 },
+ { id: "initial", name: "Peer", avatar: null, avatarVersion: 0 },
{ id: "known", name: "Author", avatar: "/avatar", avatarVersion: 4 },
] }
- expect(presentCanonicalMessage({ id: "opener", type: "chat", thread }).thread).toEqual({
- id: "thread", name: "", messageCount: 2, lastReplyAt: undefined, participants: [
+ expect(presentCanonicalMessage(wire({ id: "opener", thread })).thread).toEqual({
+ id: "thread", name: null, messageCount: 2, lastReplyAt: null, participants: [
{ id: "unknown", name: "", avatar: "?", avatarVersion: 0 },
{ id: "initial", name: "Peer", avatar: "P", avatarVersion: 0 },
{ id: "known", name: "Author", avatar: "/avatar", avatarVersion: 4 },
],
})
- expect(thread.participants[0]).toEqual({ id: "unknown" })
+ expect(thread.participants[0]).toEqual({ id: "unknown", name: "", avatar: null, avatarVersion: 0 })
expect(thread.participants[1].avatar).toBeNull()
})
- it("keeps explicit empty rich fields distinct from omission", () => {
+ it("requires full attachments and keeps optional embeds distinct from omission", () => {
expect(projectCommunityMessageCreate(wire({ attachments: [], embeds: [] }), "channel-1"))
.toMatchObject({ attachments: [], embeds: [] })
const sparse = projectCommunityMessageCreate(wire(), "channel-1")
- expect(sparse).not.toHaveProperty("attachments")
+ expect(sparse.attachments).toEqual([])
+ expect(() => projectCommunityMessageCreate(Object.assign({}, wire(), { attachments: undefined }), "channel-1")).toThrow()
expect(sparse).not.toHaveProperty("embeds")
})
it("preserves canonical identity and presentation fields", () => {
- const replyTo = { id: "m0", authorName: "A", text: "prior" }
+ const replyTo = { authorId: "peer", id: "m0", authorName: "A", text: "prior" }
const approval = {
friendshipId: "f1",
status: "pending" as const,
@@ -93,9 +96,9 @@ describe("projectCommunityMessageCreate", () => {
const raw = projectCommunityMessageCreate(wire({
embeds: [{ title: "Card", url: "https://example.com" }, { url: "missing-title" }, null],
attachments: [
- { id: "a1", filename: "photo.png", url: "/photo", contentType: "image/png", size: 2048, width: 640, height: 480 },
- { id: "a2", filename: "doc.pdf", url: "/doc", contentType: "application/pdf", size: 2048 },
- { id: "a3", filename: "unsafe.svg", url: "/unsafe", contentType: "image/svg+xml", size: 1024 },
+ { id: "a1", name: "photo.png", url: "/photo", thumbnailUrl: null, contentType: "image/png", sizeBytes: 2048, width: 640, height: 480 },
+ { id: "a2", name: "doc.pdf", url: "/doc", thumbnailUrl: null, contentType: "application/pdf", sizeBytes: 2048, width: null, height: null },
+ { id: "a3", name: "unsafe.svg", url: "/unsafe", thumbnailUrl: null, contentType: "image/svg+xml", sizeBytes: 1024, width: null, height: null },
],
}), "channel-1")
const projected = presentCanonicalMessage(raw)
@@ -111,8 +114,8 @@ describe("projectCommunityMessageCreate", () => {
})
describe("projectPostedMessage", () => {
- it.each([0, 46])("keeps valid legacy POST facts at seq %s without storage extras", (seq) => {
- const replyTo = { id: "prior", authorName: "Peer", text: "quoted" }
+ it.each([0, 46])("rejects raw old POST storage rows at seq %s", (seq) => {
+ const replyTo = { authorId: "peer", id: "prior", authorName: "Peer", text: "quoted" }
const attachments = [{ id: "file", name: "file.txt", url: "/file", thumbnailUrl: null,
contentType: "text/plain", sizeBytes: 4, width: null, height: null }]
const embeds = [{ title: "Card" }]
@@ -123,26 +126,20 @@ describe("projectPostedMessage", () => {
mentionType: null, replyToId: replyTo.id, replyTo, attachments, embeds, reactions, thread,
clientNonce: "stored-nonce", authorEmail: "[email protected]", storageMetadata: { legacy: true } }
- expect(projectPostedMessage(row, "accepted-nonce", "channel-1")).toEqual({
- id: row.id, channelId: row.channelId, seq, authorId: row.authorId, authorName: row.authorName,
- authorAvatar: null, authorAvatarVersion: 4, createdAt: row.createdAt, content: row.content, type: "chat",
- mentionType: null, replyToId: replyTo.id, replyTo, attachments, embeds, reactions, thread,
- clientNonce: "accepted-nonce", resourceComplete: false,
- })
+ expect(() => projectPostedMessage(row, "accepted-nonce", "channel-1")).toThrow()
})
it.each([{ seq: undefined }, { seq: -1 }, { seq: 0.5 },
{ replyTo: { id: "prior", authorName: "Peer", text: "quoted", extra: true } },
- ])("rejects malformed known legacy POST facts %j", (fields) => {
- const row = { id: "legacy", seq: 1, authorId: "author", authorName: "Author", authorImage: null,
- authorAvatarVersion: 0, createdAt: "2026-10-07T12:00:00Z", content: "body", type: "default", embeds: null }
+ ])("rejects malformed current POST facts %j", (fields) => {
+ const row = wire({ clientNonce: "nonce", authorId: "author", authorName: "Author" })
expect(() => projectPostedMessage(Object.assign({}, row, fields), "nonce", "channel-1")).toThrow()
})
it("keeps full POST resource and confirmation requirements", () => {
const full = { id: "full", channelId: "channel-1", seq: 47, authorId: "author", authorName: "Author",
authorAvatar: null, authorAvatarVersion: 4, createdAt: "2026-10-07T12:00:00Z", content: "body", type: "chat" as const,
- replyToId: null, clientNonce: "nonce", attachments: [], resourceComplete: true as const }
+ replyToId: null, clientNonce: "nonce", attachments: [] }
expect(projectPostedMessage(full, "nonce", "channel-1")).toEqual(full)
for (const fields of [{ attachments: undefined }, { channelId: "foreign" }, { clientNonce: "foreign" }]) {
expect(() => projectPostedMessage(Object.assign({}, full, fields), "nonce", "channel-1")).toThrow()
@@ -150,49 +147,42 @@ describe("projectPostedMessage", () => {
})
it("falls back to an initial when the posted author has no canonical avatar", () => {
- const projected = projectPostedMessage({
- id: "m2",
- seq: 43,
- authorId: "u2",
- authorName: "Gus",
- authorImage: null,
- authorAvatarVersion: 0,
- content: "hello",
- type: "default",
- embeds: null,
- createdAt: "2026-08-06T00:00:00.000Z",
- }, "nonce-2", "dm-1")
-
- expect(projected).toMatchObject({
- authorAvatar: null,
- authorAvatarVersion: 0,
- clientNonce: "nonce-2",
- })
+ const projected = projectPostedMessage(messageResourceFixture({
+ id: "m2", channelId: "dm-1", seq: 43, clientNonce: "nonce-2", authorId: "u2", authorName: "Gus",
+ authorAvatar: null, authorAvatarVersion: 0, content: "hello", createdAt: "2026-08-06T00:00:00.000Z",
+ }), "nonce-2", "dm-1")
+ expect(projected).toMatchObject({ authorAvatar: null, authorAvatarVersion: 0, clientNonce: "nonce-2" })
expect(presentCanonicalMessage(projected).authorAvatar).toBe("G")
})
it("rejects an absent or mismatched actual POST channel scope", () => {
- const row = { id: "m3", seq: 44, authorId: "u3", authorName: "Peer", authorImage: null,
- authorAvatarVersion: 0, content: null, type: "default", embeds: null, createdAt: "2026-08-06T00:00:00.000Z" }
+ const row = messageResourceFixture({ id: "m3", channelId: "dm-1", seq: 44, authorId: "u3", clientNonce: "nonce-3", content: "" })
expect(() => projectPostedMessage(row, "nonce-3", "")).toThrow()
- expect(() => projectPostedMessage(Object.assign({}, row, { channelId: "other" }), "nonce-3", "dm-1"))
- .toThrow("Message resource scope mismatch")
- expect(projectPostedMessage(row, "nonce-3", "dm-1")).toMatchObject({ id: "m3", content: "", type: "chat" })
+ expect(() => projectPostedMessage({ ...row, channelId: "other" }, "nonce-3", "dm-1"))
+ .toThrow("Posted message confirmation mismatch")
+ expect(projectPostedMessage(row, "nonce-3", "dm-1")).toEqual(row)
})
- it("keeps absent POST and WS rich content sparse", () => {
- const row = { id: "m4", seq: 45, authorId: "u4", authorName: "Peer", authorImage: null,
- authorAvatarVersion: 0, content: "plain", type: "default", embeds: null, createdAt: "2026-08-06T00:00:00.000Z" }
+ it("keeps required empty attachments and optional POST and WS rich content sparse", () => {
+ const row = messageResourceFixture({ id: "m4", channelId: "dm-1", seq: 45, clientNonce: "nonce-4", authorId: "u4", content: "plain" })
const posted = projectPostedMessage(row, "nonce-4", "dm-1")
- expect(projectPostedMessage(Object.assign({}, row, { attachments: [], embeds: [] }), "nonce-4", "dm-1"))
+ expect(projectPostedMessage({ ...row, attachments: [], embeds: [] }, "nonce-4", "dm-1"))
.toMatchObject({ attachments: [], embeds: [] })
for (const message of [posted, projectCommunityMessageCreate(wire(), "channel-1")]) {
- expect(message).not.toHaveProperty("attachments")
+ expect(message.attachments).toEqual([])
expect(message).not.toHaveProperty("embeds")
expect(message.channelId).toBe(message.id === "m4" ? "dm-1" : "channel-1")
- expect(message).not.toHaveProperty("replyToId")
+ expect(message.replyToId).toBeNull()
expect(message).not.toHaveProperty("replyTo")
}
})
+ it.each([0, 46])("preserves all current POST rich facts at seq %s", (seq) => {
+ const full = wire({ seq, clientNonce: "nonce", replyToId: "prior", replyTo: { id: "prior", authorId: "peer", authorName: "Peer", text: "quoted" },
+ attachments: [{ id: "file", name: "file.txt", url: "/file", thumbnailUrl: null, contentType: "text/plain", sizeBytes: 4, width: null, height: null }],
+ embeds: [{ title: "Card" }], reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["peer"] }],
+ thread: { id: "thread", name: "Thread", messageCount: 1, lastReplyAt: null },
+ })
+ expect(projectPostedMessage(full, "nonce", "channel-1")).toEqual(full)
+ })
})
diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.ts
index 1ac76b3a4..5b961d3a8 100644
--- a/src/web/src/lib/community/message-wire.ts
+++ b/src/web/src/lib/community/message-wire.ts
@@ -1,16 +1,12 @@
-import { CommunityLegacyMessageCreateSchema, CommunityMessagePreviewSchema, CommunityMessageResourceSchema, type CommunityMessageCreate, type CommunityMessageResource, type CommunityMessagePreview } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, CommunityMessageResourceSchema, type CommunityMessageResource } from "@alook/shared"
import { MessageEmbedSchema, type Msg, type CanonicalMessage } from "@/lib/community/models/message"
-import type { MessageRow } from "./message-payload"
import { avatarInitial } from "@/lib/community/avatar"
import { presentMessageAttachment } from "@/lib/community/attachment-presentation"
-import { canonicalUserImage } from "@/lib/community/storage"
-import { projectMessageWireType } from "@/lib/community/message-wire-type"
type UiEmbed = NonNullable<Msg["embeds"]>[number]
-const richContentSchema = CommunityMessagePreviewSchema.pick({ attachments: true, embeds: true }).strip()
+const richContentSchema = CommunityMessageResourceSchema.pick({ attachments: true, embeds: true }).strip()
-type LegacyPostedMessage = Pick<MessageRow, "id" | "seq" | "createdAt" | "content" | "authorId" | "authorName" | "authorImage" | "authorAvatarVersion" | "type" | "embeds"> & Partial<Pick<CommunityMessageResource, "replyToId" | "replyTo" | "attachments" | "clientNonce">>
-export type PostedMessage = LegacyPostedMessage | (CommunityMessageResource & { resourceComplete: true })
+export type PostedMessage = CommunityMessageResource
function omitUndefined<T>(value: T): T {
if (Array.isArray(value)) return value.map(omitUndefined) as T
@@ -32,7 +28,7 @@ function projectMessageRichContent(value: unknown): Pick<Msg, "attachments" | "e
}
}
-export function presentCanonicalMessage(message: CommunityMessagePreview): Msg {
+export function presentCanonicalMessage(message: CommunityMessageResource): Msg {
const { channelId: _channelId, replyToId: _replyToId, clientNonce, authorAvatar, attachments: _attachments, embeds: _embeds, thread, ...fields } = message
return {
...fields,
@@ -43,60 +39,24 @@ export function presentCanonicalMessage(message: CommunityMessagePreview): Msg {
}
}
-function presentMessageThread(thread: NonNullable<CommunityMessagePreview["thread"]>): NonNullable<Msg["thread"]> {
+function presentMessageThread(thread: NonNullable<CommunityMessageResource["thread"]>): NonNullable<Msg["thread"]> {
const { participants, ...fields } = thread
- return { ...fields, name: thread.name ?? "", messageCount: thread.messageCount ?? 0, lastReplyAt: thread.lastReplyAt ?? undefined,
+ return { ...fields,
...(participants ? { participants: participants.map((participant) => ({
- ...participant, name: participant.name ?? "", avatar: participant.avatar ?? avatarInitial(participant.name ?? ""), avatarVersion: participant.avatarVersion ?? 0,
+ ...participant, avatar: participant.avatar ?? avatarInitial(participant.name),
})) } : {}),
}
}
-export function projectCommunityMessageCreate(
- message: CommunityMessageCreate["message"],
- channelId: string,
- contract: 1 | 2 | 3 = 2,
-): CanonicalMessage {
- if (contract === 3) {
- const full = CommunityMessageResourceSchema.parse(message)
- if (full.channelId !== channelId) throw new Error("Message resource scope mismatch")
- return { ...full, resourceComplete: true }
- }
- const legacy = CommunityLegacyMessageCreateSchema.shape.message.parse(message)
- const attachments = legacy.attachments?.map((attachment) => ({
- id: attachment.id, name: attachment.filename, url: attachment.url,
- contentType: attachment.contentType, sizeBytes: attachment.size,
- thumbnailUrl: attachment.thumbnailUrl, width: attachment.width, height: attachment.height,
- }))
- return projectCanonicalMessage({ ...legacy, attachments }, channelId)
-}
-
-function projectCanonicalMessage(value: Record<string, unknown>, channelId: string): CanonicalMessage {
- const message = CommunityMessagePreviewSchema.strip().parse({ ...value, channelId })
- if (typeof message.seq !== "number") throw new Error("Confirmed message sequence missing")
- if (value.channelId !== undefined && value.channelId !== channelId) throw new Error("Message resource scope mismatch")
- const fields = Object.fromEntries(Object.entries(message).filter(([, value]) => value !== undefined))
- return { ...fields, id: message.id, type: message.type, channelId, seq: message.seq, resourceComplete: false }
+export function projectCommunityMessageCreate(message: unknown, channelId: string, contract: number = BUSINESS_SCHEMA_VERSION): CanonicalMessage {
+ if (contract !== BUSINESS_SCHEMA_VERSION) throw new Error("Message resource protocol mismatch")
+ const full = CommunityMessageResourceSchema.parse(message)
+ if (full.channelId !== channelId) throw new Error("Message resource scope mismatch")
+ return full
}
-export function projectPostedMessage(
- message: PostedMessage,
- clientNonce: string,
- channelId: string,
-): CanonicalMessage {
- if ("resourceComplete" in message && message.resourceComplete === true) {
- const full = CommunityMessageResourceSchema.strip().parse(message)
- if (full.channelId !== channelId || (clientNonce && full.clientNonce !== clientNonce)) throw new Error("Posted message confirmation mismatch")
- return { ...full, resourceComplete: true }
- }
- if (!("authorImage" in message)) throw new Error("Posted message confirmation missing resource contract")
- const { authorImage, type, content, embeds, ...fields } = message
- return projectCanonicalMessage({
- ...fields,
- ...projectMessageWireType(type),
- authorAvatar: canonicalUserImage(message.authorId, authorImage, message.authorAvatarVersion),
- content: content ?? "",
- embeds: Array.isArray(embeds) ? embeds : undefined,
- ...(clientNonce ? { clientNonce } : {}),
- }, channelId)
+export function projectPostedMessage(message: PostedMessage, clientNonce: string, channelId: string): CanonicalMessage {
+ const full = CommunityMessageResourceSchema.parse(message)
+ if (full.channelId !== channelId || (clientNonce && full.clientNonce !== clientNonce)) throw new Error("Posted message confirmation mismatch")
+ return full
}
diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.ts
index ffd2541b2..1429428bd 100644
--- a/src/web/src/lib/community/messages.ts
+++ b/src/web/src/lib/community/messages.ts
@@ -22,21 +22,13 @@ export function parseCommunityMessageWindow(params: URLSearchParams) {
}
// Parse cursor from query params (format: "createdAt|id")
-export function parseCursor(cursorParam: string | null): { createdAt: string; id: string } | undefined {
+function parseCursor(cursorParam: string | null): { createdAt: string; id: string } | undefined {
if (!cursorParam) return undefined
const [createdAt, id] = cursorParam.split("|")
if (createdAt && id) return { createdAt, id }
return undefined
}
-// The anchor param is a raw message id (not a cursor tuple). Empty string
-// coerces to `undefined` so `?anchor=` still routes through the legacy path.
-export function parseAnchor(anchorParam: string | null): string | undefined {
- if (!anchorParam) return undefined
- const trimmed = anchorParam.trim()
- return trimmed.length > 0 ? trimmed : undefined
-}
-
// Parse a member cursor from query params (format: "joinedAt|id"). Members
// paginate on the `joinedAt` timestamp — a sibling of `parseCursor` above
// with a different keying field, kept separate so both stay narrowly typed.
@@ -47,12 +39,6 @@ export function parseMemberCursor(cursorParam: string | null): { joinedAt: strin
return undefined
}
-// Parse page size from query params with bounds
-export function parsePageSize(limitParam: string | null): number {
- if (!limitParam) return DEFAULT_MESSAGE_PAGE_SIZE
- return Math.min(Math.max(parseInt(limitParam, 10) || DEFAULT_MESSAGE_PAGE_SIZE, 1), MAX_MESSAGE_PAGE_SIZE)
-}
-
// Parse a positive integer query param with default + ceiling.
export function parseBoundedInt(
param: string | null,
diff --git a/src/web/src/lib/community/mobile-system-notification.test.ts b/src/web/src/lib/community/mobile-system-notification.test.ts
index ea14a4a48..9fb323340 100644
--- a/src/web/src/lib/community/mobile-system-notification.test.ts
+++ b/src/web/src/lib/community/mobile-system-notification.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
acknowledgeMobileSystemNotificationRegistration,
@@ -253,7 +254,7 @@ describe("mobile notification native adapter", () => {
expect(nativeMocks.invoke).toHaveBeenCalledWith("mobile_system_notification_snapshot")
expect(fetchImpl).toHaveBeenCalledWith(
`/api/community/notifications/devices/${installationId}`,
- { method: "DELETE", credentials: "same-origin" },
+ { method: "DELETE", credentials: "same-origin", signal: undefined, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } },
)
})
})
@@ -294,7 +295,7 @@ describe("mobile notification HTTP adapter", () => {
expect(init).toMatchObject({
method: "POST",
credentials: "same-origin",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
})
expect(JSON.parse(String(init?.body))).toEqual({
installationId,
@@ -311,7 +312,7 @@ describe("mobile notification HTTP adapter", () => {
await deleteMobileSystemNotificationRegistration(installationId, fetchImpl)
expect(fetchImpl).toHaveBeenCalledWith(
`/api/community/notifications/devices/${installationId}`,
- { method: "DELETE", credentials: "same-origin" },
+ { method: "DELETE", credentials: "same-origin", signal: undefined, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } },
)
await expect(postMobileSystemNotificationRegistration(
diff --git a/src/web/src/lib/community/mobile-system-notification.ts b/src/web/src/lib/community/mobile-system-notification.ts
index baa081e1e..84df73394 100644
--- a/src/web/src/lib/community/mobile-system-notification.ts
+++ b/src/web/src/lib/community/mobile-system-notification.ts
@@ -1,4 +1,4 @@
-import { isMobile, isTauri, tauriInvoke } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION, isMobile, isTauri, tauriInvoke } from "@alook/shared"
import { createStore } from "@tanstack/store"
import { QueryClient } from "@tanstack/react-query"
@@ -216,7 +216,7 @@ export async function postMobileSystemNotificationRegistration(
method: "POST",
signal: options.signal,
credentials: "same-origin",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
body: JSON.stringify({
installationId: snapshot.installationId,
platform: snapshot.platform,
@@ -243,7 +243,7 @@ export async function deleteMobileSystemNotificationRegistration(
options.assertActive?.()
const response = await fetchImpl(
`/api/community/notifications/devices/${encodeURIComponent(installationId)}`,
- { method: "DELETE", credentials: "same-origin", signal: options.signal },
+ { method: "DELETE", credentials: "same-origin", signal: options.signal, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } },
)
options.assertActive?.()
if (!response.ok) throw new Error("unregistration_failed")
diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.ts
index 2092aea1b..e9869a710 100644
--- a/src/web/src/lib/community/models/message.ts
+++ b/src/web/src/lib/community/models/message.ts
@@ -1,8 +1,13 @@
import { z } from "zod"
-import type { CommunityChannelResource, CommunityMessageResource, CommunityMessagePreview, CommunityLegacyMessageResource, CommunityLegacyMessageAttachment, CommunityMessagesRead } from "@alook/shared"
+import type { CommunityChannelResource, CommunityMessageResource, CommunityMessageAttachment, CommunityMessagesRead } from "@alook/shared"
// ── Messages ───────────────────────────────────────────────────────────────
-type AttachmentMetadata = Pick<CommunityLegacyMessageAttachment, "name" | "url" | "contentType" | "sizeBytes">
+export type AttachmentPreview = Pick<CommunityMessageAttachment, "name" | "url"> & Partial<Omit<CommunityMessageAttachment, "name" | "url">>
+
+type AttachmentMetadata = Pick<CommunityMessageAttachment, "name" | "url"> & {
+ contentType?: NonNullable<CommunityMessageAttachment["contentType"]>
+ sizeBytes?: NonNullable<CommunityMessageAttachment["sizeBytes"]>
+}
export type FileAttachment = AttachmentMetadata & { kind: "file"; size: string }
@@ -47,11 +52,11 @@ export type Msg = Pick<CommunityMessageResource, "id" | "type"> & Partial<Omit<C
attachments?: Attachment[]
embeds?: Embed[]
authorAvatar?: string
- thread?: CommunityLegacyMessageResource["thread"]
+ thread?: CommunityMessageResource["thread"]
}
-export type MessageInput = Pick<CommunityMessagePreview, "id"> & Partial<Omit<CommunityMessagePreview, "id">> & { resourceComplete?: boolean; failed?: boolean }
-export type CanonicalMessage = CommunityMessagePreview & Pick<CommunityMessageResource, "seq"> & { resourceComplete?: boolean }
+export type MessageInput = CommunityMessageResource & { failed?: boolean }
+export type CanonicalMessage = CommunityMessageResource
export function applyMessageReaction(source: Msg["reactions"], emoji: string, userId: string, add: boolean, viewerId: string | null): Reaction[] {
const rows = (source ?? []).map((row) => ({ ...row, userIds: [...row.userIds] }))
@@ -63,7 +68,7 @@ export function applyMessageReaction(source: Msg["reactions"], emoji: string, us
return rows.filter((row) => row.userIds.length).map((row) => ({ ...row, count: row.userIds.length, me: viewerId !== null && row.userIds.includes(viewerId) }))
}
-export function messageProfileIds(message: Pick<CommunityMessagePreview, "authorId" | "replyTo" | "thread" | "approval" | "botCreation">): string[] {
+export function messageProfileIds(message: Partial<Pick<CommunityMessageResource, "authorId" | "replyTo" | "thread" | "approval" | "botCreation">>): string[] {
return [
...(message.authorId ? [message.authorId] : []),
...(message.botCreation ? [message.botCreation.requesterId, ...message.botCreation.bots.flatMap((bot) => bot.createdBot ? [bot.createdBot.id] : [])] : []),
@@ -100,7 +105,7 @@ export type ForumThread = Thread & Required<Pick<CommunityMessageResource,
openerCreatedAt?: CommunityMessageResource["createdAt"]
tags: NonNullable<NonNullable<CommunityMessageResource["thread"]>["tags"]>
preview: NonNullable<NonNullable<CommunityMessageResource["thread"]>["preview"]>
- participants: NonNullable<NonNullable<CommunityLegacyMessageResource["thread"]>["participants"]>
+ participants: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participants"]>
participantCount: NonNullable<NonNullable<CommunityMessageResource["thread"]>["participantCount"]>
}
@@ -118,11 +123,14 @@ export type MessagesPage = Partial<{ [Field in keyof CommunityMessagesRead["page
cursor?: NonNullable<CommunityMessagesRead["page"]["olderCursor"]>
}
+export type MessagesReadPage = MessagesPage & Pick<CommunityMessagesRead, "profiles">
+
export type MessagesWindowPage = Omit<MessagesPage, "messages"> & { messages: Array<Pick<CommunityMessageResource, "id"> & Partial<Pick<CommunityMessageResource, "seq">>>; newestCursor?: string }
-export function messageWindowPage(page: MessagesPage): MessagesWindowPage {
+export function messageWindowPage(page: MessagesPage | MessagesReadPage): MessagesWindowPage {
const newest = [...page.messages].filter((message) => message.createdAt).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "") || a.id.localeCompare(b.id)).at(-1)
- return { ...page, messages: page.messages.map((message) => ({ id: message.id, ...(message.seq === undefined ? {} : { seq: message.seq }) })), ...(newest?.createdAt ? { newestCursor: `${newest.createdAt}|${newest.id}` } : {}) }
+ const { profiles: _profiles, ...window } = page as MessagesReadPage
+ return { ...window, messages: page.messages.map((message) => ({ id: message.id, ...(message.seq === undefined ? {} : { seq: message.seq }) })), ...(newest?.createdAt ? { newestCursor: `${newest.createdAt}|${newest.id}` } : {}) }
}
// Discriminated pageParam. The queryFn dispatches on `mode` — the URL param
diff --git a/src/web/src/lib/community/native-system-notification-dismissal.test.ts b/src/web/src/lib/community/native-system-notification-dismissal.test.ts
index 3b7e08c12..00ce5fae5 100644
--- a/src/web/src/lib/community/native-system-notification-dismissal.test.ts
+++ b/src/web/src/lib/community/native-system-notification-dismissal.test.ts
@@ -95,16 +95,12 @@ describe("native notification conversation dismissal revisions", () => {
expect(queue.complete("desktop", "viewer_1", target, second.revision)).toBe(false)
expect(queue.pending("desktop", "viewer_1")).toHaveLength(1)
})
- it("migrates a legacy demand once in the same key and survives recreation", () => {
- const values = new Map([[key, JSON.stringify([{version:1, platform:"mobile", viewerUserId:"viewer_1", target}])]])
- const first = createNativeSystemNotificationConversationDismissalQueue(deps(values))
- const demand = first.pending("mobile", "viewer_1")[0]!
- expect(JSON.parse(values.get(key)!)[0].version).toBe(2)
- const restored = createNativeSystemNotificationConversationDismissalQueue(deps(values))
- expect(restored.pending("mobile", "viewer_1")).toEqual([demand])
- expect(restored.pending("desktop", "viewer_1")).toEqual([])
- expect(restored.complete("mobile", "viewer_1", target, demand.revision)).toBe(true)
- expect(values.size).toBe(0)
+ it("rejects and removes unversioned-old demand without conversion", () => {
+ const values = new Map([[key, JSON.stringify([{ version: 1, platform: "mobile", viewerUserId: "viewer_1", target }])]])
+ const queue = createNativeSystemNotificationConversationDismissalQueue(deps(values))
+ expect(queue.pending("mobile", "viewer_1")).toEqual([])
+ expect(values.has(key)).toBe(false)
+ expect(createNativeSystemNotificationConversationDismissalQueue(deps(values)).pending("mobile", "viewer_1")).toEqual([])
})
it("bounds scopes and rejects corrupt storage, unsafe identities, and failed writes", () => {
const values = new Map<string, string>()
diff --git a/src/web/src/lib/community/native-system-notification-dismissal.ts b/src/web/src/lib/community/native-system-notification-dismissal.ts
index 14f76ff75..92fdf7cd7 100644
--- a/src/web/src/lib/community/native-system-notification-dismissal.ts
+++ b/src/web/src/lib/community/native-system-notification-dismissal.ts
@@ -83,18 +83,14 @@ export function createNativeSystemNotificationConversationDismissalQueue(
const valid = values.every((value) => {
if (!value || typeof value !== "object" || Array.isArray(value)) return false
const entry = value as Record<string, unknown>
- return ((Object.keys(entry).length === 4 && entry.version === 1)
- || (Object.keys(entry).length === 5 && entry.version === CONVERSATION_VERSION
- && typeof entry.revision === "string" && UUID.test(entry.revision)))
+ return (Object.keys(entry).length === 5 && entry.version === CONVERSATION_VERSION
+ && typeof entry.revision === "string" && UUID.test(entry.revision))
&& (entry.platform === "desktop" || entry.platform === "mobile")
&& validSafeId(entry.viewerUserId)
&& validConversation(entry.target)
})
if (!valid) throw new Error()
- const migrated = values.map((value) => value.version === 1
- ? { ...value, version: CONVERSATION_VERSION, revision: revision() } : value) as PendingConversationDismissal[]
- if (values.some((value) => value.version === 1) && !write(migrated)) return []
- return migrated
+ return values as PendingConversationDismissal[]
} catch {
remove()
return []
diff --git a/src/web/src/lib/community/navigation-metadata.dom.test.tsx b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
index d11e04a1a..447ba13e0 100644
--- a/src/web/src/lib/community/navigation-metadata.dom.test.tsx
+++ b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
@@ -1,3 +1,4 @@
+import { dmListRowFixture } from "@/test/community-resource-fixtures"
import { writeForumTagSelection } from "./forum-tag-selection"
import React, { useEffect } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
@@ -83,7 +84,7 @@ describe("native navigation warming and DM consumer mounting", () => {
entry.selection = { reason: "read_pointer", anchorMessageId: "m28" }
entry.page.latestSeq = 28
} else {
- publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [{ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" }] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
+ publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
}
const pending = deferred<typeof entry>()
load.mockReturnValue(pending.promise)
@@ -110,7 +111,7 @@ describe("native navigation warming and DM consumer mounting", () => {
it.each(["account", "channel"] as const)("still cancels warming and rejects late data after %s retirement", async kind => {
const owner = await createCommunityQueryOwner()
const entry = dmConversationEntryFixture()
- publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [{ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" }] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
+ publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
const pending = deferred<typeof entry>()
load.mockReturnValue(pending.promise)
const warming = prepareNavigationMetadata(owner.client, "/c/me/c1", "foreground")
@@ -125,7 +126,7 @@ describe("native navigation warming and DM consumer mounting", () => {
expect(original.getObserversCount()).toBe(0)
expect(signal.aborted).toBe(true)
await act(async () => { pending.resolve(entry); await Promise.resolve() })
- expect(owner.registry.collections.channels.get("c1")?.resourceComplete).not.toBe(true)
+ expect(owner.registry.collections.channels.get("c1")?.id).toBe("c1")
expect(owner.client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries("c1") }).reduce((n, q) => n + q.getObserversCount(), 0)).toBe(0)
expect(load).toHaveBeenCalledOnce()
})
diff --git a/src/web/src/lib/community/producer-contract.test.ts b/src/web/src/lib/community/producer-contract.test.ts
index cbba27c78..e4c60ebdf 100644
--- a/src/web/src/lib/community/producer-contract.test.ts
+++ b/src/web/src/lib/community/producer-contract.test.ts
@@ -1,23 +1,25 @@
import { describe, expect, it } from "vitest"
-import { serializeMessageDeliveryBatch, type CommunityChannelMembershipChange, type MessageDeliveryBatch } from "@alook/shared"
-import { projectCommunityProducerDelivery, projectCommunityProducerEvent } from "./producer-contract"
+import { BUSINESS_SCHEMA_VERSION, serializeMessageDeliveryBatch, type CommunityChannelMembershipChange, type MessageDeliveryBatch } from "@alook/shared"
+import { messageResourceFixture } from "@/test/community-resource-fixtures"
+import { communityProducerContract, projectCommunityProducerDelivery, projectCommunityProducerEvent } from "./producer-contract"
const event: CommunityChannelMembershipChange = { type: "community:channel.membership.change", channelId: "thread", serverId: "server", userId: "peer", relation: "notify", present: true }
-const batch: MessageDeliveryBatch = { messageId: "message", messageEvent: { type: "community:message.create", channelId: "thread", serverId: "server", message: { id: "message", seq: 1, authorId: "author", authorName: "Author", authorAvatarVersion: 0, type: "chat", content: "hello", createdAt: "2026-10-07T12:00:00Z" } }, contentUserIds: ["author", "peer"], unreadPlainUserIds: [], unreadMentionUserIds: [], mentionUserIds: [], joinedParticipantUserIds: ["peer"], rosterRefreshUserId: "peer" }
+const batch: MessageDeliveryBatch = { communityContract: BUSINESS_SCHEMA_VERSION, messageId: "message", messageEvent: { type: "community:message.create", profiles: [{ id: "author", name: "Author", discriminator: "0042", avatar: null, avatarVersion: 0 }], channelId: "thread", serverId: "server", message: messageResourceFixture({ id: "message", channelId: "thread", seq: 1, authorId: "author", authorName: "Author", authorAvatarVersion: 0, content: "hello", createdAt: "2026-10-07T12:00:00Z" }) }, contentUserIds: ["author", "peer"], unreadPlainUserIds: [], unreadMentionUserIds: [], mentionUserIds: [], joinedParticipantUserIds: ["peer"], rosterRefreshUserId: "peer" }
-describe("staged community event production", () => {
- it("defaults to the exact old control shape until v2 production is enabled", () => {
- expect(projectCommunityProducerEvent(event, {})).toEqual({ type: "community:channel.member_add", channelId: "thread", serverId: "server", userId: "peer" })
- expect(projectCommunityProducerEvent(event, { COMMUNITY_EVENT_CONTRACT: "2" })).toEqual(event)
- expect(() => projectCommunityProducerEvent({ ...event, serverId: null }, {})).toThrow("requires producer contract v2")
+describe("current community event production", () => {
+ it("produces the sole current membership event including nullable DM server scope", () => {
+ expect(communityProducerContract()).toBe(BUSINESS_SCHEMA_VERSION)
+ expect(projectCommunityProducerEvent(event, {})).toEqual(event)
+ expect(projectCommunityProducerEvent({ ...event, serverId: null }, {})).toEqual({ ...event, serverId: null })
})
- it("selects the old committed-delivery shape without mutating its source", () => {
- const legacy = projectCommunityProducerDelivery(batch, {})
- expect(legacy).not.toHaveProperty("joinedParticipantUserIds")
- expect(legacy).not.toHaveProperty("rosterRefreshUserId")
- expect(legacy.memberAdded).toEqual({ channelId: "thread", serverId: "server", userId: "peer" })
- expect(() => serializeMessageDeliveryBatch(legacy)).not.toThrow()
- expect(projectCommunityProducerDelivery(batch, { COMMUNITY_EVENT_CONTRACT: "2" })).toBe(batch)
- expect(batch.joinedParticipantUserIds).toEqual(["peer"])
+ it("preserves the full current committed delivery and structural participants without mutation", () => {
+ const before = structuredClone(batch)
+ expect(projectCommunityProducerDelivery(batch, {})).toBe(batch)
+ expect(() => serializeMessageDeliveryBatch(batch)).not.toThrow()
+ expect(batch).toEqual(before)
+ })
+ it.each([1, 2, 3])("refuses old source contract %s rather than projecting it", version => {
+ expect(() => projectCommunityProducerEvent(event, {}, version)).toThrow("protocol mismatch")
+ expect(() => projectCommunityProducerDelivery({ ...batch, communityContract: version } as unknown as MessageDeliveryBatch, {})).toThrow("protocol mismatch")
})
})
diff --git a/src/web/src/lib/community/producer-contract.ts b/src/web/src/lib/community/producer-contract.ts
index 5222c132e..ce969ffa3 100644
--- a/src/web/src/lib/community/producer-contract.ts
+++ b/src/web/src/lib/community/producer-contract.ts
@@ -1,21 +1,16 @@
-import { projectCommunityEventForContract, type CommunityContract, type CommunityWsEvent, type MessageDeliveryBatch } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, projectCommunityEventForContract, type CommunityWsEvent, type MessageDeliveryBatch } from "@alook/shared"
-type ProducerEnvironment = { COMMUNITY_EVENT_CONTRACT?: string }
-
-export function communityProducerContract(env: ProducerEnvironment): CommunityContract {
- if (env.COMMUNITY_EVENT_CONTRACT === "3") return 3
- return env.COMMUNITY_EVENT_CONTRACT === "2" ? 2 : 1
+export function communityProducerContract() {
+ return BUSINESS_SCHEMA_VERSION
}
-export function projectCommunityProducerEvent(event: CommunityWsEvent, env: ProducerEnvironment, sourceContract: CommunityContract = 2) {
- const selected = projectCommunityEventForContract(event, communityProducerContract(env), sourceContract)
- if (!selected) throw new Error("Community event requires producer contract v2")
+export function projectCommunityProducerEvent(event: CommunityWsEvent, _env: unknown, sourceContract: number = BUSINESS_SCHEMA_VERSION) {
+ const selected = projectCommunityEventForContract(event, BUSINESS_SCHEMA_VERSION, sourceContract)
+ if (!selected) throw new Error("Community event protocol mismatch")
return selected
}
-export function projectCommunityProducerDelivery(batch: MessageDeliveryBatch, env: ProducerEnvironment): MessageDeliveryBatch {
- if (batch.communityContract === 3 || communityProducerContract(env) !== 1 || !batch.joinedParticipantUserIds) return batch
- const { joinedParticipantUserIds: _joined, rosterRefreshUserId, ...legacy } = batch
- if (!rosterRefreshUserId || !batch.messageEvent.serverId) throw new Error("Missing committed participant scope")
- return { ...legacy, memberAdded: { userId: rosterRefreshUserId, channelId: batch.messageEvent.channelId, serverId: batch.messageEvent.serverId } }
+export function projectCommunityProducerDelivery(batch: MessageDeliveryBatch, _env: unknown): MessageDeliveryBatch {
+ if (batch.communityContract !== BUSINESS_SCHEMA_VERSION) throw new Error("Community delivery protocol mismatch")
+ return batch
}
diff --git a/src/web/src/lib/community/profile-seed.test.ts b/src/web/src/lib/community/profile-seed.test.ts
index 53a03139b..4b6a53333 100644
--- a/src/web/src/lib/community/profile-seed.test.ts
+++ b/src/web/src/lib/community/profile-seed.test.ts
@@ -147,11 +147,10 @@ describe("profile seeding boundaries", () => {
}], registry)
expect(registry.collections.profiles.get("complete")).toMatchObject({
id: "complete", name: "Complete", discriminator: "12345", avatar, avatarVersion: 4,
- aboutMe: "actual bio", statusEmoji: null, statusText: "actual status", identityComplete: true,
+ aboutMe: "actual bio", statusEmoji: null, statusText: "actual status",
})
writeCommunityProfilePatches([{ id: "partial", identityAbout: { name: "Partial", discriminator: "67890" }, avatar: { avatarVersion: 4 } }], registry)
- expect(registry.collections.profiles.get("partial")).toMatchObject({ identityComplete: false, avatarVersion: 4 })
- expect(registry.collections.profiles.get("partial")).not.toHaveProperty("avatar")
+ expect(registry.collections.profiles.get("partial")).toBeUndefined()
})
it("writes profile patches into the canonical collection", () => {
@@ -172,6 +171,7 @@ describe("profile seeding boundaries", () => {
writeCommunityProfilePatches([{
id: "u-cache-gap",
identityAbout: { name: "Before", discriminator: "0009" },
+ avatar: { avatar: null, avatarVersion: 0 },
}], registry)
const queryKey = communityKeys.communityDbCollection(registry.scopeId, "profiles")
registry.queryClient.removeQueries({ queryKey, exact: true })
@@ -188,14 +188,14 @@ describe("profile seeding boundaries", () => {
})
})
- it("keeps a known number when a name-only or unknown-number identity is seeded", () => {
- writeCommunityProfilePatches([{ id: "numbered", identityAbout: { name: "Original", discriminator: "123456" }, status: { statusEmoji: "🌱", statusText: "Known" } }], registry)
+ it("rejects malformed empty discriminator patches without overwriting known identity", () => {
+ writeCommunityProfilePatches([{ id: "numbered", identityAbout: { name: "Original", discriminator: "123456" }, avatar: { avatar: null, avatarVersion: 0 }, status: { statusEmoji: "🌱", statusText: "Known" } }], registry)
const patch = communityUserProfilePatch("numbered", { name: "Renamed", discriminator: "", avatar: "avatar", avatarVersion: 1 })
- expect(patch.identityAbout).toEqual({ name: "Renamed" })
+ expect(patch.identityAbout).toEqual({ name: "Renamed", discriminator: "" })
expect(patch).not.toHaveProperty("status")
writeCommunityProfilePatches([patch], registry)
writeCommunityProfilePatches([{ id: "numbered", identityAbout: { name: "Latest", discriminator: "" } }], registry)
- expect(registry.collections.profiles.get("numbered")).toMatchObject({ name: "Latest", discriminator: "123456", statusEmoji: "🌱", statusText: "Known" })
+ expect(registry.collections.profiles.get("numbered")).toMatchObject({ name: "Original", discriminator: "123456", statusEmoji: "🌱", statusText: "Known" })
})
it("rejects a request snapshot captured by a different registry", async () => {
@@ -213,14 +213,15 @@ describe("profile seeding boundaries", () => {
})
it("returns the raw API object while updating its canonical profile projection", async () => {
- const raw = { member: { id: "u2", name: "API Alice" } }
+ const raw = { member: { id: "u2", name: "API Alice", discriminator: "0042", avatar: null, avatarVersion: 0 } }
apiFetch.mockResolvedValueOnce(raw)
const result = await apiFetchProfiles(
"/profiles",
(data: typeof raw) => [{
id: data.member.id,
- identityAbout: { name: data.member.name },
+ identityAbout: { name: data.member.name, discriminator: data.member.discriminator },
+ avatar: { avatar: data.member.avatar, avatarVersion: data.member.avatarVersion },
}],
undefined,
registry,
@@ -261,12 +262,37 @@ describe("profile seeding boundaries", () => {
describe("partial identity facts", () => {
- it("keeps the actual legacy avatar version and does not manufacture an unknown identity", () => {
- expect(communityUserProfilePatch("peer", { name: "Peer", avatar: "P", avatarVersion: 4 }, { legacyPresentation: true }))
- .toEqual({ id: "peer", identityAbout: { name: "Peer" }, avatar: { avatarVersion: 4 } })
+ it("keeps exact avatar facts and does not manufacture an unknown identity", () => {
+ expect(communityUserProfilePatch("peer", { name: "Peer", avatar: "P", avatarVersion: 4 }))
+ .toEqual({ id: "peer", identityAbout: { name: "Peer" }, avatar: { avatar: "P", avatarVersion: 4 } })
expect(communityUserProfilePatch("peer", {})).toEqual({ id: "peer", identityAbout: {} })
expect(communityUserProfilePatch("peer", { name: "Peer", avatar: "P", avatarVersion: 4 }).avatar).toEqual({ avatar: "P", avatarVersion: 4 })
expect(messageProfilePatches([{ thread: { id: "thread", participants: [{ id: "peer", avatar: null, avatarVersion: 4 }] } }]))
.toEqual([{ id: "peer", avatar: { avatar: null, avatarVersion: 4 } }])
})
})
+
+describe("actual card facts through canonical mapper ownership",()=>{
+ it.each(["human","other-bot","owned-bot"] as const)("keeps actual %s null/zero/false and single-field card facts",async kind=>{
+ const {CommunityUserCardReadSchema}=await import("@alook/shared")
+ const {userProfileQueryFn}=await import("@/hooks/community/use-user-profile")
+ const profile=CommunityUserCardReadSchema.parse({id:"card-peer",name:"Peer",discriminator:"0042",image:null,avatarVersion:0,aboutMe:"",bannerColor:null,statusEmoji:null,statusText:null,mutualServers:0,
+ ...(kind==="human"?{kind:"human"}:{kind:"bot",ownerProfile:{id:kind==="owned-bot"?"viewer":"other",handle:"Owner#0043"},ownedByViewer:kind==="owned-bot"})})
+ apiFetch.mockResolvedValueOnce(profile)
+ expect(await registry.queryClient.query({queryKey:communityKeys.profile(profile.id),queryFn:userProfileQueryFn(profile.id)})).toEqual({id:profile.id})
+ const canonical=registry.collections.profiles.get(profile.id)!
+ const card={ownerHandle:kind==="human"?null:"Owner#0043",mutualServers:0,ownedByViewer:kind==="owned-bot"}
+ expect(canonical).toMatchObject(card)
+ expect(communityUserProfilePatch(profile.id,canonical).card).toEqual(card)
+ for(const fields of [{ownerHandle:canonical.ownerHandle},{mutualServers:canonical.mutualServers},{ownedByViewer:canonical.ownedByViewer}]) {
+ const patch=communityUserProfilePatch(profile.id,fields)
+ expect(patch.card).toEqual(fields)
+ writeCommunityProfilePatches([patch],registry)
+ expect(registry.collections.profiles.get(profile.id)).toMatchObject(card)
+ }
+ const ordinary=communityUserProfilePatch(profile.id,{name:"New resource name",discriminator:"0042",avatar:null,avatarVersion:0})
+ expect(ordinary).not.toHaveProperty("card")
+ writeCommunityProfilePatches([ordinary],registry)
+ expect(registry.collections.profiles.get(profile.id)).toMatchObject({...card,name:"New resource name"})
+ })
+})
diff --git a/src/web/src/lib/community/profile-seed.ts b/src/web/src/lib/community/profile-seed.ts
index 0ffa2c4af..12a1226e8 100644
--- a/src/web/src/lib/community/profile-seed.ts
+++ b/src/web/src/lib/community/profile-seed.ts
@@ -4,7 +4,7 @@ import type {
CommunityProfilePatch,
} from "@/lib/community/models/people"
import type { MessageInput } from "@/lib/community/models/message"
-import { CommunityResourceProfileSchema, type CommunityResourceProfile, type FriendApprovalPayload } from "@alook/shared"
+import { canonicalCommunityUserImage, CommunityResourceProfileSchema, type CommunityResourceProfile, type FriendApprovalPayload } from "@alook/shared"
import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import {
@@ -13,7 +13,7 @@ import {
import { profileSchema, type ProfileRow } from "@/lib/community-db/schema"
import { writeCommunityCollectionRows } from "@/lib/community-db/write"
import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
-import { avatarInitial } from "@/lib/community/avatar"
+
type ProfileFieldRevisions = {
identityAbout: number
@@ -25,6 +25,8 @@ type ProfileFieldRevisions = {
type ProfileRevisionState = {
revision: number
fieldsByUserId: Map<string, ProfileFieldRevisions>
+ pendingFieldsByUserId: Map<string, Partial<Omit<CommunityResourceProfile, "id">>>
+ pendingOwner: string
}
export type CommunityProfileSeedSnapshot = {
@@ -32,9 +34,8 @@ export type CommunityProfileSeedSnapshot = {
revision: number
}
-const profileIdentitySchema = CommunityResourceProfileSchema.pick({ id: true, name: true, discriminator: true, avatar: true, avatarVersion: true }).extend({ discriminator: CommunityResourceProfileSchema.shape.discriminator.unwrap() })
-
-const createProfileRevisions = () => createStore<ProfileRevisionState>({ revision: 0, fieldsByUserId: new Map() })
+const createProfileRevisions = () => createStore<ProfileRevisionState>({ revision: 0, fieldsByUserId: new Map(), pendingFieldsByUserId: new Map(), pendingOwner: "" })
+const profileFactsSchema = CommunityResourceProfileSchema.partial()
const profileRevisionState = new WeakMap<CommunityDbRegistry, ReturnType<typeof createProfileRevisions>>()
function revisionState(registry: CommunityDbRegistry) {
@@ -52,21 +53,29 @@ export function beginCommunityProfileSeed(
return { registry, revision: registry ? revisionState(registry).get().revision : 0 }
}
-type CommunityUserProfileSeed = Partial<Pick<CommunityResourceProfile, "name" | "discriminator" | "avatarVersion" | "statusEmoji" | "statusText" | "avatar">>
+type CommunityUserProfileSeed = Partial<Omit<CommunityResourceProfile, "id">>
export function communityUserProfilePatch(
userId: string,
row: CommunityUserProfileSeed,
- options?: { legacyPresentation?: boolean },
): CommunityProfilePatch {
- const statusText = options?.legacyPresentation && row.statusText === "" ? undefined : row.statusText
+ const statusText = row.statusText
return {
id: userId,
identityAbout: {
...(row.name !== undefined ? { name: row.name } : {}),
- ...(row.discriminator ? { discriminator: row.discriminator } : {}),
+ ...(row.discriminator === undefined ? {} : { discriminator: row.discriminator }),
+ ...(row.aboutMe === undefined ? {} : { aboutMe: row.aboutMe }),
+ ...(row.bannerColor === undefined ? {} : { bannerColor: row.bannerColor }),
+ ...(row.kind === undefined ? {} : { kind: row.kind }),
+ ...(row.ownerUserId === undefined ? {} : { ownerUserId: row.ownerUserId }),
},
- ...(row.avatarVersion === undefined ? {} : { avatar: { avatarVersion: row.avatarVersion, ...(row.avatar === undefined || options?.legacyPresentation && row.avatar === avatarInitial(row.name ?? "") ? {} : { avatar: row.avatar }) } }),
+ ...(row.avatarVersion === undefined ? {} : { avatar: { avatarVersion: row.avatarVersion, ...(row.avatar === undefined ? {} : { avatar: row.avatar }) } }),
+ ...(row.ownerHandle === undefined && row.mutualServers === undefined && row.ownedByViewer === undefined ? {} : { card: {
+ ...(row.ownerHandle === undefined ? {} : { ownerHandle: row.ownerHandle }),
+ ...(row.mutualServers === undefined ? {} : { mutualServers: row.mutualServers }),
+ ...(row.ownedByViewer === undefined ? {} : { ownedByViewer: row.ownedByViewer }),
+ } }),
...(row.statusEmoji === undefined && statusText === undefined
? {}
: { status: {
@@ -127,7 +136,7 @@ export function approvalProfilePatches(
discriminator: profile.discriminator,
},
avatar: {
- avatar: profile.image,
+ avatar: canonicalCommunityUserImage(profile.id, profile.image, profile.avatarVersion),
avatarVersion: profile.avatarVersion,
},
}] : [])
@@ -136,9 +145,9 @@ export function approvalProfilePatches(
export function writeCommunityProfilePatches(
patches: readonly CommunityProfilePatch[],
registry: CommunityDbRegistry | null,
- options?: { snapshot?: CommunityProfileSeedSnapshot; event?: boolean; command?: boolean },
+ options?: { snapshot?: CommunityProfileSeedSnapshot; event?: boolean; command?: boolean; resourceSeed?: boolean },
) {
- if (!registry || patches.length === 0) return
+ if (!registry || patches.length === 0 || !registry.runtime.lifecycle.get().active) return
if (options?.snapshot && options.snapshot.registry !== registry) return
const queryKey = communityKeys.communityDbCollection(registry.scopeId, "profiles")
const cached = registry.queryClient.getQueryData<ProfileRow[]>(queryKey)
@@ -146,12 +155,19 @@ export function writeCommunityProfilePatches(
const profiles = new Map(cached.map((profile) => [profile.id, profile]))
const revisionStore = revisionState(registry)
const previous = revisionStore.get()
- const revisions = { ...previous, fieldsByUserId: new Map(previous.fieldsByUserId) }
+ const pendingOwner = JSON.stringify([registry.runtime.ws.get().profileAccountEpoch, registry.runtime.lifecycle.get().generation])
+ const revisions = { ...previous, fieldsByUserId: new Map(previous.fieldsByUserId), pendingFieldsByUserId: previous.pendingOwner === pendingOwner ? new Map(previous.pendingFieldsByUserId) : new Map<string, Partial<Omit<CommunityResourceProfile, "id">>>(), pendingOwner }
const guardedRevision = options?.snapshot?.revision
- const writeRevision = guardedRevision === undefined || options?.command ? revisions.revision + 1 : null
+ const writeRevision = options?.resourceSeed ? null : guardedRevision === undefined || options?.command ? revisions.revision + 1 : null
let advanced = false
for (const patch of patches) {
const current = profiles.get(patch.id)
+ const known = { ...current, ...revisions.pendingFieldsByUserId.get(patch.id) }
+ const seedFields = <T extends object>(fields: T | undefined): T | undefined => {
+ if (!fields || !options?.resourceSeed) return fields
+ const selected = Object.fromEntries(Object.entries(fields).filter(([key, value]) => value !== undefined && known[key as keyof typeof known] === undefined)) as T
+ return Object.keys(selected).length ? selected : undefined
+ }
const fieldRevisions = revisions.fieldsByUserId.get(patch.id) ?? {
identityAbout: 0,
avatar: 0,
@@ -162,48 +178,29 @@ export function writeCommunityProfilePatches(
guardedRevision === undefined || fieldRevisions[field] <= guardedRevision
)
const identityAbout = patch.identityAbout && accepts("identityAbout")
- ? patch.identityAbout
+ ? seedFields(patch.identityAbout)
: undefined
- const status = patch.status && accepts("status") ? patch.status : undefined
- const card = patch.card && accepts("card") ? patch.card : undefined
+ const status = patch.status && accepts("status") ? seedFields(patch.status) : undefined
+ const card = patch.card && accepts("card") ? seedFields(patch.card) : undefined
const incomingAvatar = patch.avatar && accepts("avatar") && (
- current === undefined
- || patch.avatar.avatarVersion > (current.avatarVersion ?? -1)
- || (!options?.event && patch.avatar.avatarVersion === current.avatarVersion)
+ known.avatarVersion === undefined
+ || patch.avatar.avatarVersion > known.avatarVersion
+ || (!options?.event && !options?.resourceSeed && patch.avatar.avatarVersion === known.avatarVersion)
) ? patch.avatar : undefined
const fields = {
- id: patch.id,
- name: identityAbout?.name ?? current?.name,
- discriminator: identityAbout?.discriminator || current?.discriminator,
- avatar: incomingAvatar?.avatar === undefined ? current?.avatar : incomingAvatar.avatar,
- avatarVersion: incomingAvatar?.avatarVersion ?? current?.avatarVersion,
- 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,
- ownerHandle: card?.ownerHandle === undefined ? current?.ownerHandle : card.ownerHandle,
- mutualServers: card?.mutualServers ?? current?.mutualServers,
- ownedByViewer: card?.ownedByViewer ?? current?.ownedByViewer,
- statusEmoji: status?.statusEmoji === undefined
- ? current?.statusEmoji
- : status.statusEmoji,
- statusText: status?.statusText === undefined
- ? current?.statusText
- : status.statusText,
+ ...known, id: patch.id,
+ ...Object.fromEntries(Object.entries({ ...identityAbout, ...incomingAvatar, ...status, ...card }).filter(([, value]) => value !== undefined)),
+ }
+ const facts = profileFactsSchema.safeParse(Object.fromEntries(Object.entries(fields).filter(([key, value]) => value !== undefined && !key.startsWith("$"))))
+ if (!facts.success) continue
+ const parsed = profileSchema.safeParse(facts.data)
+ if (parsed.success) {
+ profiles.set(patch.id, parsed.data)
+ revisions.pendingFieldsByUserId.delete(patch.id)
+ } else if (!current && !options?.resourceSeed) {
+ const { id: _id, ...pending } = facts.data
+ revisions.pendingFieldsByUserId.set(patch.id, pending)
}
- const identity = profileIdentitySchema.safeParse({
- id: fields.id,
- name: fields.name,
- discriminator: fields.discriminator,
- avatar: fields.avatar,
- avatarVersion: fields.avatarVersion,
- })
- const next = profileSchema.parse({ ...Object.fromEntries(Object.entries(fields).filter(([, field]) => field !== undefined)), identityComplete: current?.identityComplete === true || identity.success })
- profiles.set(patch.id, next)
if (writeRevision !== null) {
const nextRevisions = { ...fieldRevisions }
if (identityAbout) nextRevisions.identityAbout = writeRevision
@@ -217,7 +214,7 @@ export function writeCommunityProfilePatches(
}
}
if (advanced && writeRevision !== null) revisions.revision = writeRevision
- if (advanced) revisionStore.setState(() => revisions)
+ revisionStore.setState(() => revisions)
const rows = [...profiles.values()]
writeCommunityCollectionRows(registry, "profiles", rows, (row) => row.id)
}
diff --git a/src/web/src/lib/community/read-contract.test.ts b/src/web/src/lib/community/read-contract.test.ts
index 2e4addc0f..002cf6e05 100644
--- a/src/web/src/lib/community/read-contract.test.ts
+++ b/src/web/src/lib/community/read-contract.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER, normalizeCommunityChannelResource, type CommunityConversationEntryRead } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, type CommunityConversationEntryRead } from "@alook/shared"
+import { channelResourceFixture, messageResourceFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
import { writeCommunityChannelRead, writeCommunityMessagesRead, writeCommunityConversationEntryRead } from "./read-contract"
import { decodeCommunityReadResponse } from "./read-response"
import { parseCommunityMessageWindow } from "./messages"
@@ -8,26 +9,21 @@ import { projectCommunityMessageCreate } from "./message-wire"
import { communityKeys } from "@/lib/query-keys"
const request = (version?: string) => new Request("https://alook.test/api/community/channels/channel", { headers: version ? { [COMMUNITY_CONTRACT_HEADER]: version } : {} })
-const channel = { id: "channel", type: "dm", serverId: null, name: null, archived: 0, createdAt: "2026-10-07T12:00:00Z" }
+const channel = channelResourceFixture({ id: "channel", type: "dm", serverId: null, name: null })
describe("common reading negotiation", () => {
- it("keeps legacy metadata and confirms the complete v2 read", async () => {
+ it("emits current metadata and requires exact response confirmation", async () => {
const access = { canRead: true, canSend: false, canCreateDiscussion: false }
- const old = writeCommunityChannelRead(request(), "channel", channel, access)
- expect(await old.json()).toEqual(channel)
- const current = writeCommunityChannelRead(request("2"), "channel", channel, access)
- expect(current.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")
+ const current = writeCommunityChannelRead(request(String(BUSINESS_SCHEMA_VERSION)), "channel", channel, access)
+ expect(current.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
const body = await current.json()
- const decoded = decodeCommunityReadResponse("/api/community/channels/channel", "GET", current, body)
- expect(decoded).toMatchObject({ id: "channel", accessDecision: { canRead: true, canSend: false } })
- expect(decoded).not.toHaveProperty("readContractVersion")
+ expect(decodeCommunityReadResponse("/api/community/channels/channel", "GET", current, body)).toEqual({ ...channel, accessDecision: { channelId: "channel", ...access } })
expect(() => decodeCommunityReadResponse("/api/community/channels/other", "GET", current, body)).toThrow("scope mismatch")
expect(() => decodeCommunityReadResponse("/api/community/channels/channel", "GET", new Response(), body)).toThrow("confirmation mismatch")
- expect(decodeCommunityReadResponse("/api/community/channels/channel", "GET", new Response(), { ...channel, readContractVersion: 2, accessDecision: access })).not.toHaveProperty("readContractVersion")
})
it.each(["channel", "forum", "thread", "dm"] as const)("uses the same message resource for %s", async (surfaceKind) => {
- const message = { id: "m1", seq: 1, authorId: "user", createdAt: "2026-10-07T12:00:00Z", content: "hello", type: "chat" }
- const response = writeCommunityMessagesRead(request("2"), "channel", { messages: [message], latestSeq: 1, hasMore: true, cursor: "cursor", surfaceReceipt: { channelId: "channel", surfaceKind } })
+ const message = messageResourceFixture({ id: "m1", channelId: "channel", authorId: "user", content: "hello" })
+ const response = writeCommunityMessagesRead(request(String(BUSINESS_SCHEMA_VERSION)), "channel", { messages: [message], profiles: [profileResourceFixture({ id: "user", name: "User" })], latestSeq: 1, hasMore: true, cursor: "cursor", surfaceReceipt: { channelId: "channel", surfaceKind } })
const body = await response.json()
expect(body.messages[0]).toMatchObject({ channelId: "channel", clientNonce: null, replyToId: null, attachments: [] })
expect(body.messages[0]).not.toHaveProperty("resourceComplete")
@@ -38,12 +34,12 @@ describe("common reading negotiation", () => {
expect(communityKeys.channelMeta(null, "channel")).toEqual(communityKeys.channelMeta("server", "channel"))
expect(communityKeys.channelMembers("channel", "access")).not.toEqual(communityKeys.channelMembers("channel", "notify"))
})
- it("normalizes legacy message bytes with the same core resource validator", () => {
- const message = { id: "message", authorId: "author", seq: 1, createdAt: "2026-10-07T12:00:00Z", type: "chat", content: "hello" }
- const decoded = decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", new Response(), { messages: [message], latestSeq: 1 })
- expect(decoded).toMatchObject({ latestSeq: 1, messages: [{ ...message, channelId: "channel", resourceComplete: false }] })
- expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", new Response(), { messages: [{ ...message, seq: undefined }] })).toThrow()
- expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", new Response(), { messages: [{ ...message, channelId: "foreign" }] })).toThrow("scope mismatch")
+ it("rejects old message bytes without creating missing resource facts", () => {
+ const partial = { id: "message", authorId: "author", seq: 1, createdAt: "now", type: "chat", content: "hello" }
+ const path = "/api/community/channels/channel/messages"
+ expect(() => decodeCommunityReadResponse(path, "GET", new Response(), { messages: [partial] })).toThrow("confirmation mismatch")
+ const response = new Response(null, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+ expect(() => decodeCommunityReadResponse(path, "GET", response, { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "channel", messages: [partial] })).toThrow()
})
it("validates window exclusivity, cursors and limits", () => {
expect(parseCommunityMessageWindow(new URLSearchParams("window=after&cursor=2026-10-07T12%3A00%3A00Z%7Cm1&limit=10"))).toMatchObject({ since: { id: "m1" }, pageSize: 10 })
@@ -52,42 +48,42 @@ describe("common reading negotiation", () => {
})
-describe("explicit resource 3 ingress", () => {
+describe("current resource ingress", () => {
it.each(["channel", "forum", "thread", "dm"] as const)("converges HTTP and WS raw facts for %s", async (surfaceKind) => {
const attachments = [{ id: "a2", name: "first", url: "/first", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }, { id: "a1", name: "second", url: "/second", thumbnailUrl: null, contentType: "image/png", sizeBytes: 1024, width: 40, height: 50 }]
const row = { id: "full", seq: 2, authorId: "peer", authorName: "Peer", authorImage: null, authorAvatarVersion: 4, createdAt: "now", type: "chat", content: "body", clientNonce: "nonce", replyToId: null, mentionType: null, embeds: [null, { unsupported: true }] }
- const full = mapMessageForWs(row, { replyMap: new Map(), attachments: [], resourceAttachments: attachments, clientNonce: "nonce" }, 3, "channel")
- const response = writeCommunityMessagesRead(request("3"), "channel", { messages: [full], latestSeq: 2, surfaceReceipt: { channelId: "channel", surfaceKind } })
+ const full = mapMessageForWs(row, { replyMap: new Map(), attachments: [], resourceAttachments: attachments, clientNonce: "nonce" }, BUSINESS_SCHEMA_VERSION, "channel")
+ const response = writeCommunityMessagesRead(request(String(BUSINESS_SCHEMA_VERSION)), "channel", { messages: [full], profiles: [profileResourceFixture({ id: "peer", name: "Peer", avatarVersion: 4 })], latestSeq: 2, surfaceReceipt: { channelId: "channel", surfaceKind } })
const body = await response.json()
- const http = decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body, 3) as { messages: unknown[] }
- const ws = projectCommunityMessageCreate(full, "channel", 3)
+ const http = decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body, BUSINESS_SCHEMA_VERSION) as { messages: unknown[] }
+ const ws = projectCommunityMessageCreate(full, "channel", BUSINESS_SCHEMA_VERSION)
expect(http.messages).toEqual([ws])
- expect(ws).toMatchObject({ resourceComplete: true, authorAvatar: null, attachments, embeds: row.embeds, clientNonce: "nonce" })
+ expect(ws).toMatchObject({ authorAvatar: null, attachments, embeds: row.embeds, clientNonce: "nonce" })
const missing = { ...body, messages: [{ ...full, attachments: undefined }] }
- expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, missing, 3)).toThrow()
- expect(() => projectCommunityMessageCreate({ ...full, channelId: "foreign" }, "channel", 3)).toThrow("scope mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, missing, BUSINESS_SCHEMA_VERSION)).toThrow()
+ expect(() => projectCommunityMessageCreate({ ...full, channelId: "foreign" }, "channel", BUSINESS_SCHEMA_VERSION)).toThrow("scope mismatch")
})
})
-describe("opt-in conversation entry ingress", () => {
+describe("current conversation entry ingress", () => {
const entry = (): CommunityConversationEntryRead => ({
- contractVersion: 3, channelId: "channel", viewerId: "viewer", peer: { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0 },
- channel: normalizeCommunityChannelResource(channel),
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "channel", viewerId: "viewer", peer: { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0 },
+ channel: channel,
access: { channelId: "channel", canRead: true, canSend: false, canCreateDiscussion: false },
readState: { channelId: "channel", lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },
readStateRevision: 0, selection: { reason: "tail", anchorMessageId: null },
- surfaceReceipt: { channelId: "channel", surfaceKind: "dm" }, messages: [],
+ surfaceReceipt: { channelId: "channel", surfaceKind: "dm" }, messages: [], profiles: [],
page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 },
})
it("decodes an explicit entry without changing the ordinary message contract", async () => {
const value = entry()
const response = writeCommunityConversationEntryRead(value)
- expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("3")
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
const body = await response.json()
- expect(decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", response, body, 3)).toEqual(value)
- expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body, 3)).toThrow()
- expect(() => decodeCommunityReadResponse("/api/community/channels/foreign/messages?entry=1", "GET", response, body, 3)).toThrow("scope mismatch")
+ expect(decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", response, body, BUSINESS_SCHEMA_VERSION)).toEqual(value)
+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body, BUSINESS_SCHEMA_VERSION)).toThrow()
+ expect(() => decodeCommunityReadResponse("/api/community/channels/foreign/messages?entry=1", "GET", response, body, BUSINESS_SCHEMA_VERSION)).toThrow("scope mismatch")
})
it("rejects a legacy response, wrong contract or unsupported opt-in value", async () => {
@@ -98,15 +94,15 @@ describe("opt-in conversation entry ingress", () => {
["/api/community/channels/channel/messages?entry=0", 3],
["/api/community/channels/channel/messages?entry=", 3],
] as const) expect(() => decodeCommunityReadResponse(path, "GET", response, value, version)).toThrow("confirmation mismatch")
- expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", new Response(), value, 3)).toThrow("confirmation mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", new Response(), value, BUSINESS_SCHEMA_VERSION)).toThrow("confirmation mismatch")
})
it("qualifies complete message rows only after entry scope validation", () => {
const value = entry()
const message = { id: "m1", channelId: "channel", seq: 1, authorId: "peer", createdAt: "now", type: "chat", content: "body", clientNonce: null, replyToId: null, attachments: [] }
- const body = { ...value, messages: [message] }
- const response = new Response(null, { headers: { [COMMUNITY_CONTRACT_HEADER]: "3" } })
- expect(decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", response, body, 3)).toMatchObject({ messages: [{ ...message, resourceComplete: true }] })
- expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", response, { ...body, messages: [{ ...message, channelId: "foreign" }] }, 3)).toThrow("scope mismatch")
+ const body = { ...value, messages: [message], profiles: [profileResourceFixture({ id: "peer", name: "Peer" })] }
+ const response = new Response(null, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+ expect(decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", response, body, BUSINESS_SCHEMA_VERSION)).toMatchObject({ messages: [{ ...message }] })
+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1", "GET", response, { ...body, messages: [{ ...message, channelId: "foreign" }] }, BUSINESS_SCHEMA_VERSION)).toThrow("scope mismatch")
})
})
diff --git a/src/web/src/lib/community/read-contract.ts b/src/web/src/lib/community/read-contract.ts
index a0c5df4b5..407da1e78 100644
--- a/src/web/src/lib/community/read-contract.ts
+++ b/src/web/src/lib/community/read-contract.ts
@@ -1,52 +1,51 @@
import { NextResponse } from "next/server"
import {
- COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestedCommunityContract, communityReadSchemas, communityChannelResourceFromStorage, CommunityMessageResourceSchema,
- normalizeCommunityChannelResource, normalizeCommunityMessageResource, CommunityConversationEntryReadSchema, CommunityMessagesReadSchema,
+ COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, type CommunityContract, communityReadSchemas, communityChannelResourceFromStorage, CommunityMessageResourceSchema,
+ CommunityConversationEntryReadSchema, CommunityMessagesReadSchema,
type CommunityAccessDecision, type CommunityMessageSurfaceReceipt, type CommunityMessagesRead,
type CommunityConversationEntryRead,
} from "@alook/shared"
-import { writeJSON } from "@/lib/middleware/helpers"
-function versionedJSON(data: unknown, contract: 2 | 3 = COMMUNITY_CONTRACT_VERSION): NextResponse {
+function versionedJSON(data: unknown, contract: CommunityContract = COMMUNITY_CONTRACT_VERSION): NextResponse {
return NextResponse.json(data, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(contract) } })
}
-export function writeCommunityChannelRead(request: Request, channelId: string, channel: unknown,
+export function writeCommunityChannelRead(_request: Request, channelId: string, channel: unknown,
access: Omit<CommunityAccessDecision, "channelId">) {
- const contract = requestedCommunityContract(request.headers)
- if (contract !== 2 && contract !== 3) return writeJSON(channel)
+ const contract = COMMUNITY_CONTRACT_VERSION
return versionedJSON(communityReadSchemas(contract).channel.parse({ contractVersion: contract, channelId,
- channel: contract === 3 ? communityChannelResourceFromStorage(channel) : normalizeCommunityChannelResource(channel),
+ channel: communityChannelResourceFromStorage(channel),
access: { channelId, ...access } }), contract)
}
export type MessagePage = Pick<CommunityMessagesRead["page"], "latestSeq"> & Partial<{ [Field in Exclude<keyof CommunityMessagesRead["page"], "latestSeq">]: NonNullable<CommunityMessagesRead["page"][Field]> }> & {
messages: unknown[]
+ profiles: CommunityMessagesRead["profiles"]
cursor?: NonNullable<CommunityMessagesRead["page"]["olderCursor"]>
hasMore?: CommunityMessagesRead["page"]["hasMoreOlder"]
surfaceReceipt: CommunityMessageSurfaceReceipt
}
-export function writeCommunityMessagesRead(request: Request, channelId: string, page: MessagePage) {
- const contract = requestedCommunityContract(request.headers)
- if (contract !== 2 && contract !== 3) return writeJSON(page)
+export function writeCommunityMessagesRead(_request: Request, channelId: string, page: MessagePage) {
+ const contract = COMMUNITY_CONTRACT_VERSION
return versionedJSON(communityReadSchemas(contract).messages.parse(messageReadPayload(channelId, page, contract)), contract)
}
-function messageReadPayload(channelId: string, page: MessagePage, contract: 2 | 3) {
+function messageReadPayload(channelId: string, page: MessagePage, contract: CommunityContract) {
return { contractVersion: contract, channelId,
- messages: page.messages.map((message) => contract === 3 ? CommunityMessageResourceSchema.parse(message) : normalizeCommunityMessageResource(message, channelId)),
+ profiles: page.profiles,
+ messages: page.messages.map((message) => CommunityMessageResourceSchema.parse(message)),
page: { olderCursor: page.olderCursor ?? page.cursor ?? null, newerCursor: page.newerCursor ?? null,
hasMoreOlder: page.hasMoreOlder ?? page.hasMore ?? false, hasMoreNewer: page.hasMoreNewer ?? false,
latestSeq: page.latestSeq }, surfaceReceipt: page.surfaceReceipt }
}
export function communityMessagesReadFromPage(channelId: string, page: MessagePage) {
- return CommunityMessagesReadSchema.parse(messageReadPayload(channelId, page, 3))
+ return CommunityMessagesReadSchema.parse(messageReadPayload(channelId, page, COMMUNITY_CONTRACT_VERSION))
}
export function writeCommunityConversationEntryRead(entry: CommunityConversationEntryRead) {
- return versionedJSON(CommunityConversationEntryReadSchema.parse(entry), 3)
+ return versionedJSON(CommunityConversationEntryReadSchema.parse(entry), COMMUNITY_CONTRACT_VERSION)
}
export { versionedJSON as writeCommunityContractJSON }
diff --git a/src/web/src/lib/community/read-response.test.ts b/src/web/src/lib/community/read-response.test.ts
index 1360d0950..fbe01baaa 100644
--- a/src/web/src/lib/community/read-response.test.ts
+++ b/src/web/src/lib/community/read-response.test.ts
@@ -1,35 +1,33 @@
import { describe, expect, it } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER, normalizeCommunityChannelResource, normalizeCommunityMessageResource } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import { communityReadTarget, decodeCommunityReadResponse } from "./read-response"
-const parent = normalizeCommunityChannelResource({ id: "forum", type: "forum", serverId: "server", name: "Forum", archived: 0, createdAt: "2026-10-07T12:00:00Z" })
-const child = normalizeCommunityChannelResource({ ...parent, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "viewer", lastMessageAt: "2026-10-07T13:00:00Z" })
-const profile = { id: "viewer", name: "Viewer", discriminator: null, avatar: null, avatarVersion: 0, statusEmoji: null, statusText: "" }
+const parent = channelResourceFixture({ id: "forum", type: "forum", serverId: "server", name: "Forum", archived: false, createdAt: "2026-10-07T12:00:00Z" })
+const child = channelResourceFixture({ ...parent, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "viewer", lastMessageAt: "2026-10-07T13:00:00Z" })
+const profile = { id: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 0, statusEmoji: null, statusText: "" }
const member = { channelId: "thread", userId: "viewer", relation: "notify" as const, source: "spoke", isCreator: true, role: null, memberId: null }
-const message = (id: string, channelId: string) => normalizeCommunityMessageResource({ id, channelId, seq: 1, authorId: "viewer", authorAvatar: "avatar", createdAt: "2026-10-07T12:00:00Z", type: "chat", content: id }, channelId)
-const confirmed = () => new Response(null, { headers: { [COMMUNITY_CONTRACT_HEADER]: "2" } })
-const threads = () => ({ contractVersion: 2, channelId: "forum", channel: { ...parent }, threads: [{ ...child }],
+const message = (id: string, channelId: string) => messageResourceFixture({ id, channelId, authorAvatar: "avatar", content: id })
+const confirmed = () => new Response(null, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
+const threads = () => ({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "forum", channel: { ...parent }, threads: [{ ...child }],
included: { messages: [message("opener", "forum"), message("reply", "thread")], members: [{ ...member }], profiles: [{ ...profile }], tags: [{ messageId: "opener", tag: "bug" }], participantCounts: [{ channelId: "thread", count: 7 }] },
page: { hasMore: true, nextCursor: "next" as string | null } })
const decodeThreads = (body: unknown) => decodeCommunityReadResponse("/api/community/channels/forum/threads", "GET", confirmed(), body)
-const members = () => ({ contractVersion: 2, channelId: "thread", relation: "notify" as const, members: [{ ...member }], profiles: [{ ...profile }] })
+const members = () => ({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "thread", relation: "notify" as const, members: [{ ...member }], profiles: [{ ...profile }] })
const decodeMembers = (body: unknown, path = "/api/community/channels/thread/members?relation=notify") => decodeCommunityReadResponse(path, "GET", confirmed(), body)
describe("common read response publication", () => {
- it("admits a legacy single-message preview only with an explicit valid scope", () => {
- const value = { id: "legacy", channelId: "thread", seq: 1, authorId: "viewer", createdAt: "now", type: "chat", content: "body" }
- expect(decodeCommunityReadResponse("/api/community/messages/legacy", "GET", new Response(), value))
- .toEqual({ ...value, resourceComplete: false })
- for (const invalid of [null, {}, { ...value, channelId: undefined }, { ...value, channelId: 4 }, { ...value, channelId: "" }]) {
- expect(() => decodeCommunityReadResponse("/api/community/messages/legacy", "GET", new Response(), invalid)).toThrow()
- }
+ it("rejects unconfirmed single-message resources and incomplete current messages", () => {
+ const value = message("message", "thread")
+ expect(() => decodeCommunityReadResponse("/api/community/messages/message", "GET", new Response(), value)).toThrow("confirmation mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/messages/message", "GET", confirmed(), { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "thread", message: { id: "message" } })).toThrow()
})
it("recognizes only complete read routes and decodes their encoded channel identity", () => {
expect(communityReadTarget("/api/community/channels/a%2Fb/read?lastReadSeq=4", "put")).toEqual({ channelId: "a/b", resource: "read" })
expect(communityReadTarget("/api/community/channels/thread/members?relation=notify")).toEqual({ channelId: "thread", resource: "members" })
for (const [path, method] of [["/api/community/channels/thread/read", "GET"], ["/api/community/channels/thread/read-state", "GET"], ["/api/community/channels/thread/messages/extra", "GET"], ["/api/community/channels/thread", "PUT"], ["/api/community/messages/search?q=term", "GET"], ["/api/community/messages/batch", "GET"]]) {
expect(communityReadTarget(path!, method)).toBeNull()
- const body = { contractVersion: 2, private: "unrelated endpoint" }
+ const body = { contractVersion: BUSINESS_SCHEMA_VERSION, private: "unrelated endpoint" }
expect(decodeCommunityReadResponse(path!, method, confirmed(), body)).toBe(body)
}
})
@@ -38,14 +36,14 @@ describe("common read response publication", () => {
const channel = threads().channel
const access = { channelId: channel.id, canRead: false, canSend: false, canCreateDiscussion: false }
const path = `/api/community/channels/${channel.id}`
- const current = decodeCommunityReadResponse(path, "GET", confirmed(), { contractVersion: 2, channelId: channel.id, channel, access })
- expect(current).toEqual({ ...channel, resourceComplete: true, accessDecision: access })
+ const current = decodeCommunityReadResponse(path, "GET", confirmed(), { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: channel.id, channel, access })
+ expect(current).toEqual({ ...channel, accessDecision: access })
expect(current).not.toHaveProperty("readContractVersion")
- expect(decodeCommunityReadResponse(path, "GET", new Response(), { ...channel, readContractVersion: 2, accessDecision: access })).toEqual(channel)
+ expect(() => decodeCommunityReadResponse(path, "GET", new Response(), { ...channel, accessDecision: access })).toThrow("confirmation mismatch")
})
it("publishes only a confirmed scoped read-waterline advancement", () => {
- const body = { contractVersion: 2, channelId: "thread", changed: false, targetSeq: 8, revision: 12 }
+ const body = { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "thread", changed: false, targetSeq: 8, revision: 12 }
expect(decodeCommunityReadResponse("/api/community/channels/thread/read", "PUT", confirmed(), body)).toEqual({ changed: false, targetSeq: 8, revision: 12 })
expect(() => decodeCommunityReadResponse("/api/community/channels/other/read", "PUT", confirmed(), body)).toThrow("scope mismatch")
expect(() => decodeCommunityReadResponse("/api/community/channels/thread/read", "PUT", confirmed(), { ...body, targetSeq: -1 })).toThrow()
@@ -100,36 +98,36 @@ describe("common read response publication", () => {
expect(() => decodeMembers({ ...body, profiles: [] })).toThrow("profile missing")
})
- it("keeps legacy nonmessage resources but rejects unconfirmed version claims", () => {
+ it("rejects unconfirmed nonmessage resources and old claims", () => {
const legacy = { relation: "notify", members: [] }
- expect(decodeCommunityReadResponse("/api/community/channels/thread/members", "GET", new Response(), legacy)).toBe(legacy)
+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/members", "GET", new Response(), legacy)).toThrow("confirmation mismatch")
expect(() => decodeMembers({ ...members(), contractVersion: 1 })).toThrow("confirmation mismatch")
- expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "GET", new Response(), {})).toThrow("resource missing")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "GET", new Response(), {})).toThrow("confirmation mismatch")
})
})
-describe("explicit v3 HTTP confirmation", () => {
+describe("current HTTP confirmation", () => {
const full = { ...message("message", "thread"), authorAvatar: null, attachments: [
{ id: "a2", name: "unknown", url: "/a2", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null },
{ id: "a1", name: "photo", url: "/a1", thumbnailUrl: null, contentType: "image/png", sizeBytes: 12, width: 1, height: 1 },
], embeds: [null, { raw: "unknown" }] }
const response = (version: string | null) => new Response(null, { headers: version === null ? {} : { [COMMUNITY_CONTRACT_HEADER]: version } })
- const body = { contractVersion: 3, channelId: "thread", message: full, deduped: false }
- it("retains full POST and single-read resources with exact positive v3 claims", () => {
+ const body = { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "thread", message: full, profiles: [profile], deduped: false }
+ it("retains full POST and single-read resources with exact current claims", () => {
expect(communityReadTarget("/api/community/channels/thread/messages", "POST")).toEqual({ channelId: "thread", resource: "posted" })
- expect(decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response("3"), body, 3)).toEqual({ message: { ...full, resourceComplete: true }, deduped: false })
+ expect(decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(String(BUSINESS_SCHEMA_VERSION)), body, BUSINESS_SCHEMA_VERSION)).toEqual({ message: { ...full }, profiles: [profile], deduped: false })
const { deduped: _deduped, ...read } = body
- expect(decodeCommunityReadResponse("/api/community/messages/message", "GET", response("3"), read, 3)).toEqual({ ...full, resourceComplete: true })
- expect(() => decodeCommunityReadResponse("/api/community/messages/other", "GET", response("3"), read, 3)).toThrow("scope mismatch")
- expect(() => decodeCommunityReadResponse("/api/community/channels/other/messages", "POST", response("3"), body, 3)).toThrow("scope mismatch")
- expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response("3"), { ...body, message: { ...full, attachments: undefined } }, 3)).toThrow()
+ expect(decodeCommunityReadResponse("/api/community/messages/message", "GET", response(String(BUSINESS_SCHEMA_VERSION)), read, BUSINESS_SCHEMA_VERSION)).toEqual(read)
+ expect(() => decodeCommunityReadResponse("/api/community/messages/other", "GET", response(String(BUSINESS_SCHEMA_VERSION)), read, BUSINESS_SCHEMA_VERSION)).toThrow("scope mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/other/messages", "POST", response(String(BUSINESS_SCHEMA_VERSION)), body, BUSINESS_SCHEMA_VERSION)).toThrow("scope mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(String(BUSINESS_SCHEMA_VERSION)), { ...body, message: { ...full, attachments: undefined } }, BUSINESS_SCHEMA_VERSION)).toThrow()
})
- it("refuses missing, mixed and unknown confirmation without downgrading a v3 request", () => {
- for (const header of [null, "1", "2", "4"]) expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(header), body, 3)).toThrow("confirmation mismatch")
- for (const contractVersion of [undefined, 1, 2, 4]) expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response("3"), { ...body, contractVersion }, 3)).toThrow("confirmation mismatch")
- expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(null), { message: full }, 3)).toThrow("confirmation mismatch")
+ it("refuses missing, mixed and unknown confirmation without accepting an old request", () => {
+ for (const header of [null, "1", "2", "4"]) expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(header), body, BUSINESS_SCHEMA_VERSION)).toThrow("confirmation mismatch")
+ for (const contractVersion of [undefined, 1, 2, 4]) expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(String(BUSINESS_SCHEMA_VERSION)), { ...body, contractVersion }, BUSINESS_SCHEMA_VERSION)).toThrow("confirmation mismatch")
+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(null), { message: full }, BUSINESS_SCHEMA_VERSION)).toThrow("confirmation mismatch")
const old = { message: { id: "old" } }
- expect(decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(null), old, 2)).toBe(old)
+ expect(() => decodeCommunityReadResponse("/api/community/channels/thread/messages", "POST", response(null), old, 2)).toThrow("confirmation mismatch")
})
})
diff --git a/src/web/src/lib/community/read-response.ts b/src/web/src/lib/community/read-response.ts
index 0abf01f92..c35b7ad10 100644
--- a/src/web/src/lib/community/read-response.ts
+++ b/src/web/src/lib/community/read-response.ts
@@ -1,7 +1,6 @@
import {
- COMMUNITY_CONTRACT_HEADER, communityReadSchemas, communityMessagePreviewFromLegacy,
+ COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION, communityReadSchemas,
CommunityMessagePostedSchema, CommunityMessageReadSchema, CommunityConversationEntryReadSchema,
- type CommunityContract,
} from "@alook/shared"
export function communityReadTarget(path: string, method = "GET") {
@@ -22,32 +21,12 @@ export function communityReadTarget(path: string, method = "GET") {
return { channelId: decodeURIComponent(matched[1]), resource: resource === "messages" && new URL(path, "https://alook.invalid").searchParams.has("entry") ? "entry" : resource }
}
-export function decodeCommunityReadResponse(path: string, method: string | undefined, response: Response, value: unknown, requestedContract: CommunityContract = 2): unknown {
+export function decodeCommunityReadResponse(path: string, method: string | undefined, response: Response, value: unknown, requestedContract: number = BUSINESS_SCHEMA_VERSION): unknown {
const target = communityReadTarget(path, method)
if (!target) return value
- if (target.resource === "entry" && (requestedContract !== 3 || new URL(path, "https://alook.invalid").searchParams.get("entry") !== "1")) throw new Error("Community entry protocol confirmation mismatch")
+ if (target.resource === "entry" && new URL(path, "https://alook.invalid").searchParams.get("entry") !== "1") throw new Error("Community entry protocol confirmation mismatch")
const bodyVersion = typeof value === "object" && value !== null && "contractVersion" in value ? value.contractVersion : undefined
- const headerVersion = response.headers.get(COMMUNITY_CONTRACT_HEADER)
- if (headerVersion === null && bodyVersion === undefined) {
- if (requestedContract === 3) throw new Error("Community read protocol confirmation mismatch")
- if (target.resource === "messages") {
- const legacy = value as { messages?: unknown[] }
- if (!Array.isArray(legacy.messages)) throw new Error("Community message resource missing")
- return { ...legacy, messages: legacy.messages.map((message) => {
- return { ...communityMessagePreviewFromLegacy(message, target.channelId), resourceComplete: false }
- }) }
- }
- if (target.resource === "message") {
- if (typeof value !== "object" || value === null || !("channelId" in value) || typeof value.channelId !== "string") throw new Error("Community message scope missing")
- return { ...communityMessagePreviewFromLegacy(value, value.channelId), resourceComplete: false }
- }
- if (target.resource === "metadata" && typeof value === "object" && value !== null) {
- const { readContractVersion: _version, accessDecision: _access, ...legacy } = value as Record<string, unknown>
- return legacy
- }
- return value
- }
- if ((requestedContract !== 2 && requestedContract !== 3) || headerVersion !== String(requestedContract) || bodyVersion !== requestedContract) throw new Error("Community read protocol confirmation mismatch")
+ if (requestedContract !== BUSINESS_SCHEMA_VERSION || response.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION) || bodyVersion !== BUSINESS_SCHEMA_VERSION) throw new Error("Community read protocol confirmation mismatch")
const schemas = communityReadSchemas(requestedContract)
const assertScope = (channelId: string) => {
if (channelId !== target.channelId) throw new Error("Community read resource scope mismatch")
@@ -55,32 +34,28 @@ export function decodeCommunityReadResponse(path: string, method: string | undef
if (target.resource === "entry") {
const data = CommunityConversationEntryReadSchema.parse(value)
assertScope(data.channelId)
- return { ...data, messages: data.messages.map((message) => ({ ...message, resourceComplete: true })) }
+ return { ...data, messages: data.messages }
}
if (target.resource === "message") {
- if (requestedContract !== 3) throw new Error("Community message protocol confirmation mismatch")
const data = CommunityMessageReadSchema.parse(value)
if (data.channelId !== data.message.channelId || data.message.id !== target.messageId) throw new Error("Community message resource scope mismatch")
- return { ...data.message, resourceComplete: true }
+ return data
}
if (target.resource === "metadata") {
const data = schemas.channel.parse(value)
assertScope(data.channelId); assertScope(data.channel.id); assertScope(data.access.channelId)
- return { ...data.channel, resourceComplete: true, accessDecision: data.access }
+ return { ...data.channel, accessDecision: data.access }
}
if (target.resource === "posted") {
- if (requestedContract !== 3) throw new Error("Community posted protocol confirmation mismatch")
const data = CommunityMessagePostedSchema.parse(value)
assertScope(data.channelId); assertScope(data.message.channelId)
- return { message: { ...data.message, resourceComplete: true }, deduped: data.deduped, ...(data.threadId ? { threadId: data.threadId } : {}) }
+ return { profiles: data.profiles, message: data.message, deduped: data.deduped, ...(data.threadId ? { threadId: data.threadId } : {}) }
}
if (target.resource === "messages") {
const data = schemas.messages.parse(value)
assertScope(data.channelId); assertScope(data.surfaceReceipt.channelId)
for (const message of data.messages) assertScope(message.channelId)
- return { messages: data.messages.map((message) => requestedContract === 3
- ? { ...message, resourceComplete: true }
- : { ...communityMessagePreviewFromLegacy(message, target.channelId), resourceComplete: false }),
+ return { profiles: data.profiles, messages: data.messages,
olderCursor: data.page.olderCursor ?? undefined, newerCursor: data.page.newerCursor ?? undefined,
hasMoreOlder: data.page.hasMoreOlder, hasMoreNewer: data.page.hasMoreNewer, latestSeq: data.page.latestSeq,
surfaceReceipt: data.surfaceReceipt }
diff --git a/src/web/src/lib/community/reading.routes.test.ts b/src/web/src/lib/community/reading.routes.test.ts
index 795c5da15..5fa02be7c 100644
--- a/src/web/src/lib/community/reading.routes.test.ts
+++ b/src/web/src/lib/community/reading.routes.test.ts
@@ -1,6 +1,7 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
-import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
const mocks = vi.hoisted(() => ({ db: {}, access: vi.fn(), channel: vi.fn(), friends: vi.fn(), resolve: vi.fn(), participants: vi.fn(), users: vi.fn(), members: vi.fn(),
children: vi.fn(), threads: vi.fn(), openers: vi.fn(), first: vi.fn(), tags: vi.fn(), threadParticipants: vi.fn(), attachments: vi.fn(), reactions: vi.fn(), replies: vi.fn() }))
@@ -17,18 +18,19 @@ vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import(
communityThread: { listThreadParticipants: mocks.participants, listForumThreadsByCreatedAt: mocks.threads, listParticipantsForChannels: mocks.threadParticipants },
communityMessage: { getMessagesByIdsInScope: mocks.openers, getFirstMessageResourcesByChannelIds: mocks.first, getMessagesByIdsInChannels: mocks.replies },
communityMessageTag: { listTagsForMessages: mocks.tags }, communityAttachment: { listByMessageIds: mocks.attachments }, communityReaction: { listReactionsByMessageIds: mocks.reactions },
+ communityUserProfile: { getResourceProfiles: async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 0 })) },
user: { getUsersByIds: mocks.users }, communityMember: { getMembersByUserIds: mocks.members },
} }))
import { GET as metadata } from "@/app/api/community/channels/[id]/route"
import { GET as roster } from "@/app/api/community/channels/[id]/members/route"
import { GET as threadList } from "@/app/api/community/channels/[id]/threads/route"
-const parent = { id: "forum", type: "forum", serverId: "server", name: "Forum", archived: 0, createdAt: "2026-10-07T12:00:00Z" }
+const parent = { ...channelResourceFixture({ id: "forum", type: "forum", serverId: "server", name: "Forum", createdAt: "2026-10-07T12:00:00Z" }), archived: 0 }
const child = { ...parent, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "viewer" }
const ctx = (id: string) => ({ params: Promise.resolve({ id }) })
-const req = (path: string, bot = false) => new NextRequest(`https://alook.test/api/community/channels/${path}`, { headers: { [COMMUNITY_CONTRACT_HEADER]: "2", ...(bot ? { Authorization: "Bearer crk_unit_fixture" } : {}) } })
+const req = (path: string, bot = false) => new NextRequest(`https://alook.test/api/community/channels/${path}`, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), ...(bot ? { Authorization: "Bearer crk_unit_fixture" } : {}) } })
const row = (id: string, channelId: string) => ({ id, channelId, seq: 1, authorId: "viewer", authorName: "Viewer", authorImage: null, authorAvatarVersion: 0, content: id,
- type: "default", mentionType: null, replyToId: null, embeds: [], clientNonce: null, createdAt: "2026-10-07T12:00:00Z" })
+ type: "chat", mentionType: null, replyToId: null, embeds: [], clientNonce: null, createdAt: "2026-10-07T12:00:00Z" })
beforeEach(() => {
vi.resetAllMocks()
@@ -44,7 +46,7 @@ describe("negotiated complete read route boundaries", () => {
mocks.channel.mockResolvedValue({ ...parent, id: "dm", type: "dm", serverId: null, name: null })
mocks.friends.mockResolvedValue(friends)
const response = await metadata(req("dm"), ctx("dm"))
- expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(await response.json()).toMatchObject({ channelId: "dm", channel: { id: "dm", type: "dm" }, access: { channelId: "dm", canRead: true, canSend: friends, canCreateDiscussion: false } })
expect(mocks.channel).toHaveBeenCalledWith(mocks.db, "dm", "viewer")
expect(mocks.friends).toHaveBeenCalledWith(mocks.db, "viewer", "peer")
@@ -60,9 +62,9 @@ describe("negotiated complete read route boundaries", () => {
it.each([false, true])("resolves a current human/bot roster through the complete reader: bot=%s", async (bot) => {
mocks.access.mockResolvedValue({ ok: true, value: { surface: "channel", channel: child } })
mocks.participants.mockResolvedValue([{ userId: "viewer", source: "spoke" }])
- mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", image: null, avatarVersion: 0 }])
+ mocks.users.mockResolvedValue([{ id: "viewer", name: "Viewer", discriminator: "0042", image: null, avatarVersion: 0 }])
const response = await roster(req(`thread/members?relation=notify${bot ? "&ref=%2Fserver%2Fthread" : ""}`, bot), ctx("thread"))
- expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(await response.json()).toMatchObject({ channelId: "thread", relation: "notify", members: [{ userId: "viewer", source: "spoke" }] })
expect(mocks.resolve).toHaveBeenCalledWith(mocks.db, bot ? "bot" : "viewer", bot ? { ref: "/server/thread" } : { id: "thread" }, bot ? "bot" : "human")
})
@@ -78,7 +80,7 @@ describe("negotiated complete read route boundaries", () => {
mocks.access.mockResolvedValue({ ok: true, value: { surface: "dm", dm: { otherUserId: "peer" } } })
mocks.channel.mockResolvedValue({ ...parent, id: "dm", type: "dm", serverId: null, name: null })
const response = await threadList(req("dm/threads"), ctx("dm"))
- expect(await response.json()).toMatchObject({ contractVersion: 2, channelId: "dm", threads: [], included: { messages: [] } })
+ expect(await response.json()).toMatchObject({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "dm", threads: [], included: { messages: [] } })
expect(mocks.children).not.toHaveBeenCalled()
})
@@ -97,7 +99,7 @@ describe("negotiated complete read route boundaries", () => {
mocks.tags.mockResolvedValue([{ messageId: "opener", tag: "bug" }])
mocks.threadParticipants.mockResolvedValue([{ channelId: "thread", userId: "viewer", userName: "Viewer", discriminator: "123456", userImage: null, userAvatarVersion: 0, participantCount: 1 }])
const response = await threadList(req("forum/threads?order=createdAt&include=parentMessage,firstMessage,tags,participants&limit=1"), ctx("forum"))
- expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
const body = await response.json()
expect(body).toMatchObject({ channelId: "forum", threads: [{ id: "thread" }], included: { messages: [{ id: "opener", channelId: "forum", seq: 1 }, { id: "first", channelId: "thread", seq: 1 }],
profiles: [{ id: "viewer", discriminator: "123456" }], members: [{ userId: "viewer", relation: "notify" }], tags: [{ messageId: "opener", tag: "bug" }] }, page: { hasMore: true, nextCursor: expect.any(String) } })
diff --git a/src/web/src/lib/community/resource-profiles.server.ts b/src/web/src/lib/community/resource-profiles.server.ts
new file mode 100644
index 000000000..62e46c382
--- /dev/null
+++ b/src/web/src/lib/community/resource-profiles.server.ts
@@ -0,0 +1,5 @@
+import { queries, type Database } from "@alook/shared"
+
+export function readCommunityResourceProfiles(db: Database, userIds: readonly string[]) {
+ return queries.communityUserProfile.getResourceProfiles(db, userIds)
+}
diff --git a/src/web/src/lib/community/self-profile.server.ts b/src/web/src/lib/community/self-profile.server.ts
index fb359c7c8..5a4b89f26 100644
--- a/src/web/src/lib/community/self-profile.server.ts
+++ b/src/web/src/lib/community/self-profile.server.ts
@@ -1,21 +1,16 @@
-import { queries, withD1Retry, type Database } from "@alook/shared"
+import { CommunitySelfProfileReadSchema, queries, withD1Retry, type Database } from "@alook/shared"
import { canonicalUserImage } from "./storage"
-import { avatarInitial } from "./avatar"
export async function readCommunitySelfProfile(db: Database, userId: string) {
const [profile, viewer] = await Promise.all([
withD1Retry(() => queries.communityUserProfile.getProfile(db, userId), { route: "community/profile:self-profile" }),
withD1Retry(() => queries.user.getUserSelf(db, userId), { route: "community/profile:self-user" }),
])
- const name = viewer?.name ?? ""
- return { viewer, profile: {
- id: userId, name,
- aboutMe: profile?.aboutMe ?? "",
- avatar: viewer ? canonicalUserImage(viewer.id, viewer.image, viewer.avatarVersion) ?? avatarInitial(name) : avatarInitial(name),
- avatarVersion: viewer?.avatarVersion ?? 0,
- bannerColor: profile?.bannerColor ?? null,
- discriminator: viewer?.discriminator ?? "0000",
- statusEmoji: profile?.statusEmoji ?? null,
- statusText: profile?.statusText ?? "",
- } }
+ if (!viewer) return null
+ return { viewer, profile: CommunitySelfProfileReadSchema.parse({
+ id: viewer.id, name: viewer.name, aboutMe: profile?.aboutMe ?? "",
+ avatar: canonicalUserImage(viewer.id, viewer.image, viewer.avatarVersion), avatarVersion: viewer.avatarVersion,
+ bannerColor: profile?.bannerColor ?? null, discriminator: viewer.discriminator,
+ statusEmoji: profile?.statusEmoji ?? null, statusText: profile?.statusText ?? null,
+ }) }
}
diff --git a/src/web/src/lib/community/self-profile.sql.test.ts b/src/web/src/lib/community/self-profile.sql.test.ts
new file mode 100644
index 000000000..26cf1c6c4
--- /dev/null
+++ b/src/web/src/lib/community/self-profile.sql.test.ts
@@ -0,0 +1,24 @@
+import { afterEach, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+import { assertCaseProfileBaseline } from "@/test/e2e-ui/_fixtures/case-profile-baseline"
+
+const state = vi.hoisted(() => ({ db: null as unknown }))
+vi.mock("@/lib/db", () => ({ getDb: () => state.db }))
+vi.mock("@/lib/auth", () => ({ getAuth: vi.fn() }))
+vi.mock("@/lib/community/fanout", () => ({ fanOutProfileUpdate: vi.fn(), fanOutStatusUpdate: vi.fn() }))
+vi.mock("@/lib/middleware/community-actor", () => ({ withCommunityActor: (handler: (req: NextRequest, ctx: unknown) => Promise<Response>) => (req: NextRequest) => handler(req, { env: {}, actor: { kind: "human", userId: "new-user" } }) }))
+import { GET } from "@/app/api/community/users/me/profile/route"
+
+const fixtures: ReturnType<typeof createCommunitySqliteDb>[] = []
+afterEach(() => { for (const fixture of fixtures) fixture.sqlite.close(); fixtures.length = 0 })
+it("accepts the actual new-user DB facts through the current self GET and case baseline", async () => {
+ const fixture = createCommunitySqliteDb(); fixtures.push(fixture); state.db = fixture.db
+ fixture.sqlite.exec(`INSERT INTO user (id,email,name,discriminator,"avatarVersion") VALUES ('new-user','[email protected]','New User','0042',0)`)
+ expect(fixture.sqlite.prepare("SELECT * FROM community_user_profile WHERE user_id=?").get("new-user")).toBeUndefined()
+ const response = await GET(new NextRequest("https://app.example.test/api/community/users/me/profile"), {} as never)
+ expect(response.status).toBe(200)
+ const profile = await response.json()
+ expect(profile).toEqual({ id: "new-user", name: "New User", discriminator: "0042", avatar: null, avatarVersion: 0, aboutMe: "", bannerColor: null, statusEmoji: null, statusText: null })
+ expect(() => assertCaseProfileBaseline(profile, { userId: "new-user", name: "New User" }, "viewer")).not.toThrow()
+})
diff --git a/src/web/src/lib/community/server-directory-window.test.ts b/src/web/src/lib/community/server-directory-window.test.ts
new file mode 100644
index 000000000..72875e67a
--- /dev/null
+++ b/src/web/src/lib/community/server-directory-window.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, categorySchema, channelSchema, serverSchema } from "@alook/shared"
+import { readServerDirectoryWindow, serverDirectoryWindowComplete, ServerDirectorySnapshotSchema } from "./server-directory-window"
+
+const server = serverSchema.parse({ id: "s", position: 0, name: "Server", discriminator: "0042", description: "", ownerId: "viewer", icon: null, official: false, isOwner: true })
+const category = categorySchema.parse({ id: "category", serverId: "s", name: "Category", position: 0, private: false, creatorId: null, pending: false })
+const channel = channelSchema.parse({ id: "channel", serverId: "s", categoryId: "category", name: "Channel", type: "text", topic: "", parentChannelId: null, parentMessageId: null, creatorId: "viewer", position: 0, archived: false, createdAt: "2026-10-28T00:00:00Z", lastMessageAt: null, messageCount: 0, muted: false, tags: [], pending: false })
+const window = { schemaVersion: BUSINESS_SCHEMA_VERSION, accountId: "viewer", serverId: "s", categoryIds: [category.id], channelIds: [channel.id] }
+const rows = { servers: [server], categories: [category], channels: [channel] }
+
+describe("qualified server directory window", () => {
+ it("requires a current ID window and its full canonical closure", () => {
+ expect(readServerDirectoryWindow(window)).toEqual(window)
+ expect(serverDirectoryWindowComplete(window, rows, "viewer", "s")).toBe(true)
+ expect(serverDirectoryWindowComplete(window, { ...rows, channels: [] }, "viewer", "s")).toBe(false)
+ expect(serverDirectoryWindowComplete(window, { ...rows, categories: [] }, "viewer", "s")).toBe(false)
+ expect(serverDirectoryWindowComplete(window, { ...rows, channels: [{ ...channel, serverId: "other" }] }, "viewer", "s")).toBe(false)
+ expect(serverDirectoryWindowComplete(window, rows, "other", "s")).toBe(false)
+ expect(serverDirectoryWindowComplete(window, rows, "viewer", "other")).toBe(false)
+ })
+
+ it("does not treat an entity, old window, duplicate ID or detail flag as directory proof", () => {
+ for (const value of [server, "s", { ...window, schemaVersion: BUSINESS_SCHEMA_VERSION - 1 }, { ...window, detailComplete: true }, { ...window, channelIds: ["channel", "channel"] }]) {
+ expect(readServerDirectoryWindow(value)).toBeUndefined()
+ }
+ })
+
+ it("requires actual full resource facts in directory snapshots", () => {
+ expect(() => ServerDirectorySnapshotSchema.parse({ server, categories: [], channels: [{ id: "channel", type: "text", name: "Channel" }] })).toThrow()
+ const { position: _position, ...missingPosition } = server
+ expect(() => ServerDirectorySnapshotSchema.parse({ server: missingPosition, categories: [], channels: [] })).toThrow()
+ })
+})
diff --git a/src/web/src/lib/community/server-directory-window.ts b/src/web/src/lib/community/server-directory-window.ts
new file mode 100644
index 000000000..615f5a995
--- /dev/null
+++ b/src/web/src/lib/community/server-directory-window.ts
@@ -0,0 +1,71 @@
+import { z } from "zod"
+import { BUSINESS_SCHEMA_VERSION, CommunityChannelResourceSchema, categorySchema, serverSchema, type CommunityCollectionRows } from "@alook/shared"
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
+import { communityKeys } from "@/lib/query-keys"
+
+export const ServerDirectorySnapshotSchema = z.strictObject({
+ server: serverSchema,
+ categories: z.array(categorySchema.omit({ pending: true })),
+ channels: z.array(CommunityChannelResourceSchema),
+})
+export type ServerDirectorySnapshot = z.infer<typeof ServerDirectorySnapshotSchema>
+
+const windowSchema = z.strictObject({
+ schemaVersion: z.literal(BUSINESS_SCHEMA_VERSION), accountId: z.string().min(1), serverId: z.string().min(1),
+ categoryIds: z.array(z.string().min(1)), channelIds: z.array(z.string().min(1)),
+}).refine(window => new Set(window.categoryIds).size === window.categoryIds.length && new Set(window.channelIds).size === window.channelIds.length)
+export type ServerDirectoryWindow = z.infer<typeof windowSchema>
+
+export function readServerDirectoryWindow(value: unknown) {
+ const parsed = windowSchema.safeParse(value)
+ return parsed.success ? parsed.data : undefined
+}
+
+export function isServerDirectoryWindowKey(key: readonly unknown[]) {
+ return key.length === 3 && key[0] === "community" && key[1] === "servers" && typeof key[2] === "string"
+}
+
+export function serverDirectoryWindowComplete(window: ServerDirectoryWindow, rows: {
+ servers: readonly CommunityCollectionRows["servers"][]
+ categories: readonly CommunityCollectionRows["categories"][]
+ channels: readonly CommunityCollectionRows["channels"][]
+}, accountId: string | null, serverId: string) {
+ return window.accountId === accountId && window.serverId === serverId && rows.servers.some(row => row.id === serverId)
+ && window.categoryIds.every(id => rows.categories.some(row => row.id === id && row.serverId === serverId && !row.pending))
+ && window.channelIds.every(id => rows.channels.some(row => row.id === id && row.serverId === serverId && row.parentChannelId === null && !row.pending
+ && (row.categoryId === null || window.categoryIds.includes(row.categoryId))))
+}
+
+function directoryRows(registry: CommunityDbRegistry) {
+ return {
+ servers: registry.queryClient.getQueryData<CommunityCollectionRows["servers"][]>(communityKeys.communityDbCollection(registry.scopeId, "servers")) ?? [...registry.collections.servers.values()],
+ categories: registry.queryClient.getQueryData<CommunityCollectionRows["categories"][]>(communityKeys.communityDbCollection(registry.scopeId, "categories")) ?? [...registry.collections.categories.values()],
+ channels: registry.queryClient.getQueryData<CommunityCollectionRows["channels"][]>(communityKeys.communityDbCollection(registry.scopeId, "channels")) ?? [...registry.collections.channels.values()],
+ }
+}
+
+export function getServerDirectoryWindow(registry: CommunityDbRegistry | null | undefined, serverId: string) {
+ if (!registry) return
+ const window = readServerDirectoryWindow(registry.queryClient.getQueryData(communityKeys.server(serverId)))
+ return window && serverDirectoryWindowComplete(window, directoryRows(registry), registry.accountId, serverId) ? window : undefined
+}
+
+export function recordServerDirectoryWindow(registry: CommunityDbRegistry, serverId: string) {
+ if (!registry.accountId) return
+ const rows = directoryRows(registry)
+ const window = windowSchema.parse({
+ schemaVersion: BUSINESS_SCHEMA_VERSION, accountId: registry.accountId, serverId,
+ categoryIds: rows.categories.filter(row => row.serverId === serverId && !row.pending).map(row => row.id),
+ channelIds: rows.channels.filter(row => row.serverId === serverId && row.parentChannelId === null && !row.pending).map(row => row.id),
+ })
+ registry.queryClient.setQueryData(communityKeys.server(serverId), window)
+ return window
+}
+
+export function reconcileExistingServerDirectoryWindows(registry: CommunityDbRegistry) {
+ for (const query of registry.queryClient.getQueryCache().findAll({ queryKey: communityKeys.servers() })) {
+ if (!isServerDirectoryWindowKey(query.queryKey)) continue
+ const window = readServerDirectoryWindow(query.state.data)
+ if (window?.accountId === registry.accountId) recordServerDirectoryWindow(registry, window.serverId)
+ }
+}
diff --git a/src/web/src/lib/community/storage.ts b/src/web/src/lib/community/storage.ts
index 96491900c..51f8a0e89 100644
--- a/src/web/src/lib/community/storage.ts
+++ b/src/web/src/lib/community/storage.ts
@@ -1,3 +1,5 @@
+export { communityUserAvatarUrl as userAvatarUrl, communityBotAvatarUrl as botAvatarUrl, canonicalCommunityUserImage as canonicalUserImage } from "@alook/shared"
+
export const ATTACHMENT_PRIVATE_IMMUTABLE_CACHE = "private, max-age=31536000, immutable"
/**
@@ -52,11 +54,6 @@ export function isOwnedUserAvatarObjectKey(key: string, userId: string): boolean
return suffix.length > 0 && !suffix.includes("/")
}
-export function userAvatarUrl(userId: string, avatarVersion?: number): string {
- const base = `/api/community/users/${userId}/avatar`
- return avatarVersion && avatarVersion > 0 ? `${base}?v=${avatarVersion}` : base
-}
-
export function buildBotAvatarKey(botId: string): string {
return `bot-avatar/${botId}`
}
@@ -71,22 +68,6 @@ export function isOwnedBotAvatarObjectKey(key: string, botId: string): boolean {
return suffix.length > 0 && !suffix.includes("/")
}
-export function botAvatarUrl(botId: string, avatarVersion?: number): string {
- const base = `/api/community/bots/${botId}/avatar`
- return avatarVersion && avatarVersion > 0 ? `${base}?v=${avatarVersion}` : base
-}
-
-export function canonicalUserImage(
- userId: string,
- image: string | null,
- avatarVersion: number,
-): string | null {
- if (!image) return null
- if (image === userAvatarUrl(userId)) return userAvatarUrl(userId, avatarVersion)
- if (image === botAvatarUrl(userId)) return botAvatarUrl(userId, avatarVersion)
- return image
-}
-
/**
* Map a `communityServer` row to the public icon URL. The DB stores the R2
* key; clients need a routable URL. Returns `null` when no icon is set so
diff --git a/src/web/src/lib/community/thread-read.profile.dom.test.tsx b/src/web/src/lib/community/thread-read.profile.dom.test.tsx
new file mode 100644
index 000000000..0010fa34f
--- /dev/null
+++ b/src/web/src/lib/community/thread-read.profile.dom.test.tsx
@@ -0,0 +1,72 @@
+import { createElement } from "react"
+import { afterEach, expect, it } from "vitest"
+import { queries } from "@alook/shared"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+import { act, mockElementGeometry, render } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { readCommunityThreadsResource } from "./thread-read"
+import { readCommunityResourceBundle } from "./attention-resources.server"
+import { captureCommunityLiveSnapshotToken, publishCommunityForumFeed, publishCommunityResourceBundle } from "@/lib/community-db/sync"
+import { useCanonicalChannelsById, useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
+import { forumFeedWindow, normalizeThreadResources } from "@/hooks/community/forum-feed-window"
+import { mapForumFeedPages } from "@/hooks/community/use-forum-feed"
+import { ForumView } from "@/components/community/channels/forum-view"
+import { tid } from "@/lib/community/testids"
+
+const fixtures: ReturnType<typeof createCommunitySqliteDb>[] = []
+afterEach(() => { for (const item of fixtures) item.sqlite.close(); fixtures.length = 0 })
+
+it.each(["same-channel", "foreign-channel"])("renders the real cold post author after notify exit with %s reply", async scenario => {
+ const fixture = createCommunitySqliteDb()
+ fixtures.push(fixture)
+ const { sqlite, db } = fixture
+ const stamp = "2026-10-28T00:00:00Z"
+ const insertUser = sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt") VALUES (?,?,?,?,0,?,?)')
+ for (const [id, name] of [["viewer", "Viewer"], ["author", "Former Author"], ["reply-author", "Reply Author"]]) insertUser.run(id, `${id}@example.test`, name, "0001", stamp, stamp)
+ sqlite.exec("INSERT INTO community_user_profile (user_id,about_me,banner_color,status_emoji,status_text) VALUES ('author','Real about','#123456','🌿','Real status')")
+ sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES ('server','Server','0002','','viewer',?)").run(stamp)
+ sqlite.exec("INSERT INTO community_server_member (id,server_id,user_id,role) VALUES ('viewer-member','server','viewer','owner'),('author-member','server','author','member')")
+ const insertChannel = sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at,creator_id,parent_channel_id,parent_message_id) VALUES (?,'server',?,?,'',0,0,1,?,?,?,?)")
+ insertChannel.run("forum", "Forum", "forum", stamp, "viewer", null, null)
+ insertChannel.run("post", "Post", "thread", stamp, "author", "forum", "opener")
+ const insertMessage = sqlite.prepare("INSERT INTO community_message (id,author_id,content,type,channel_id,seq,created_at,reply_to_id) VALUES (?,?,?,'default',?,?,?,?)")
+ insertMessage.run("opener", "author", "Actual post title", "forum", 1, stamp, null)
+ insertMessage.run("first", "author", "Actual post body", "post", 2, stamp, "previous")
+ insertMessage.run("previous", "reply-author", "Previous reply", scenario === "same-channel" ? "post" : "foreign-thread", 1, stamp, null)
+ sqlite.exec("INSERT INTO community_channel_member (id,channel_id,user_id,relation,source) VALUES ('viewer-notify','post','viewer','notify','added')")
+ const parent = await queries.communityChannel.getChannel(db, "forum")
+ const children = await queries.communityChannel.getChannelsByIds(db, ["post"])
+ const messages = await queries.communityMessage.getMessagesByIdsInChannels(db, ["opener", "first"], ["forum", "post"])
+ const participants = await queries.communityThread.listParticipantsForChannels(db, ["post"])
+ expect(participants.some(row => row.userId === "author")).toBe(false)
+ const resource = await readCommunityThreadsResource(db, "viewer", parent, children, { messages, participants, tags: [] })
+ const page = normalizeThreadResources("forum", resource)
+ const window = forumFeedWindow(page)
+ const { client, registry } = await createCommunityQueryOwner("viewer")
+ expect(registry.collections.profiles.get("author")).toBeUndefined()
+ expect(registry.collections.friendships.size).toBe(0)
+ const structure = await readCommunityResourceBundle(db, "viewer", { channelIds: ["forum", "post"] })
+ await act(async () => {
+ publishCommunityResourceBundle(client, structure, { token: captureCommunityLiveSnapshotToken(client) })
+ publishCommunityForumFeed(client, "forum", page, { token: captureCommunityLiveSnapshotToken(client) })
+ })
+ function Harness() {
+ const channels = useCanonicalChannelsById()
+ const messages = useCanonicalMessagesById(["opener", "first"])
+ const profiles = useCanonicalProfilesByUserId()
+ const posts = mapForumFeedPages([window], messages ?? new Map(), channels, profiles)
+ return createElement(ForumView, { forumChannelId: "forum", posts, members: [], tag: "All", hasMore: false,
+ onTagChange: () => {}, onOpenPost: () => {}, onLoadMore: () => {},
+ onScrollRoot: root => { if (root) mockElementGeometry(root, { clientHeight: 600, clientWidth: 800, scrollHeight: 600 }) },
+ })
+ }
+ const view = render(createElement(Harness), { wrapper: ({ children }) => createElement(CommunityTestProvider, { client, userId: "viewer", retainOwner: true }, children) })
+ const card = await view.findByTestId(tid.forumThreadCard("post"))
+ expect(card.textContent).toContain("Actual post title")
+ console.info(JSON.stringify({ case: "actual-thread-read-publish-forum-cold", participantIds: participants.map(row => row.userId), includedProfileIds: resource.included.profiles.map(row => row.id), rendered: card.textContent }))
+ expect(card.textContent).toContain("Former Author")
+ expect(registry.collections.profiles.get("author")).toMatchObject({ id: "author", name: "Former Author", discriminator: "0001", avatar: null, avatarVersion: 0, aboutMe: "Real about", bannerColor: "#123456", statusEmoji: "🌿", statusText: "Real status" })
+ if (scenario === "same-channel") expect(registry.collections.profiles.get("reply-author")).toMatchObject({ id: "reply-author", name: "Reply Author" })
+ else expect(registry.collections.profiles.get("reply-author")).toBeUndefined()
+})
diff --git a/src/web/src/lib/community/thread-read.test.ts b/src/web/src/lib/community/thread-read.test.ts
index b28c2fe6e..2751a8981 100644
--- a/src/web/src/lib/community/thread-read.test.ts
+++ b/src/web/src/lib/community/thread-read.test.ts
@@ -1,8 +1,10 @@
+import { channelResourceFixture } from "@/test/community-resource-fixtures"
import { beforeEach, describe, expect, it, vi } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER, communityReadSchemas } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, communityReadSchemas } from "@alook/shared"
const mocks = vi.hoisted(() => ({ attachments: vi.fn(), reactions: vi.fn(), replies: vi.fn() }))
vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import("@alook/shared")>(), queries: {
+ communityUserProfile: { getResourceProfiles: async (_db: unknown, ids: string[]) => ids.map(id => ({ id, name: "Viewer", discriminator: "123456", avatar: null, avatarVersion: 0 })) },
communityAttachment: { listByMessageIds: mocks.attachments },
communityReaction: { listReactionsByMessageIds: mocks.reactions },
communityMessage: { getMessagesByIdsInChannels: mocks.replies },
@@ -10,7 +12,7 @@ vi.mock("@alook/shared", async (original) => ({ ...await original<typeof import(
import { writeCommunityThreadsRead } from "./thread-read"
const db = {} as never
-const parent = { id: "forum", type: "forum", serverId: "server", name: "Forum", archived: 0, createdAt: "2026-10-07T12:00:00Z" }
+const parent = { ...channelResourceFixture({ id: "forum", type: "forum", serverId: "server", name: "Forum", createdAt: "2026-10-07T12:00:00Z" }), archived: 0 }
const child = { ...parent, id: "thread", type: "thread", parentChannelId: "forum", parentMessageId: "opener", creatorId: "viewer" }
const row = (id: string, channelId: string) => ({ id, channelId, seq: 4, authorId: "viewer", authorName: "Viewer", authorImage: null, authorAvatarVersion: 0,
content: id, type: "default", mentionType: null, replyToId: null as string | null, embeds: [], createdAt: "2026-10-07T12:00:00Z", clientNonce: "client-nonce" })
@@ -31,13 +33,13 @@ describe("complete thread read resource", () => {
mocks.reactions.mockResolvedValue([{ messageId: "reply", emoji: "👍", userId: "viewer" }])
mocks.replies.mockResolvedValue([{ ...row("previous", "thread"), content: "same-channel reply" }, { ...row("previous", "foreign"), content: "foreign private body" }])
const response = await writeCommunityThreadsRead(db, "viewer", parent, [child], included(), { hasMore: true, nextCursor: "next" })
- expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe("2")
- const body = communityReadSchemas(2).threads.parse(await response.json())
- expect(body).toMatchObject({ contractVersion: 2, channelId: "forum", channel: { id: "forum" }, threads: [{ id: "thread", parentChannelId: "forum" }],
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const body = communityReadSchemas().threads.parse(await response.json())
+ expect(body).toMatchObject({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "forum", channel: { id: "forum" }, threads: [{ id: "thread", parentChannelId: "forum" }],
included: { tags: [{ messageId: "opener", tag: "bug" }], members: [{ channelId: "thread", userId: "viewer", relation: "notify", isCreator: true }],
profiles: [{ id: "viewer", name: "Viewer", discriminator: "123456", avatar: null, avatarVersion: 0 }], participantCounts: [{ channelId: "thread", count: 8 }] }, page: { hasMore: true, nextCursor: "next" } })
expect(body.included.messages.find((message) => message.id === "reply")).toMatchObject({ channelId: "thread", seq: 4, clientNonce: "client-nonce", replyToId: "previous", type: "chat",
- replyTo: { id: "previous", text: "same-channel reply", authorId: "viewer" }, attachments: [{ kind: "file", name: "note.txt", sizeBytes: 42 }], reactions: [{ emoji: "👍", me: true, count: 1, userIds: ["viewer"] }] })
+ replyTo: { id: "previous", text: "same-channel reply", authorId: "viewer" }, attachments: [{ id: "attachment", name: "note.txt", contentType: "text/plain", sizeBytes: 42, thumbnailUrl: null, width: null, height: null }], reactions: [{ emoji: "👍", me: true, count: 1, userIds: ["viewer"] }] })
expect(JSON.stringify(body)).not.toContain("foreign private body")
expect(mocks.attachments).toHaveBeenCalledWith(db, ["opener", "reply"])
expect(mocks.reactions).toHaveBeenCalledWith(db, ["opener", "reply"], "viewer")
@@ -47,7 +49,7 @@ describe("complete thread read resource", () => {
it("marks a foreign-only reply as deleted instead of disclosing its text", async () => {
mocks.replies.mockResolvedValue([{ ...row("previous", "foreign"), content: "private" }])
const response = await writeCommunityThreadsRead(db, "viewer", parent, [child], included())
- const body = communityReadSchemas(2).threads.parse(await response.json())
+ const body = communityReadSchemas().threads.parse(await response.json())
expect(body.included.messages.find((message) => message.id === "reply")?.replyTo).toEqual({ id: "previous", authorName: "Deleted user", text: "", deleted: true })
})
@@ -55,7 +57,7 @@ describe("complete thread read resource", () => {
const sibling = { ...child, id: "sibling", parentMessageId: "sibling-opener" }
mocks.replies.mockResolvedValue([{ ...row("previous", "sibling"), content: "sibling private reply" }])
const response = await writeCommunityThreadsRead(db, "viewer", parent, [child, sibling], included())
- const body = communityReadSchemas(2).threads.parse(await response.json())
+ const body = communityReadSchemas().threads.parse(await response.json())
expect(body.included.messages.find((message) => message.id === "reply")?.replyTo).toEqual({ id: "previous", authorName: "Deleted user", text: "", deleted: true })
expect(JSON.stringify(body)).not.toContain("sibling private reply")
expect(mocks.replies).toHaveBeenCalledWith(db, ["previous"], ["forum", "thread", "sibling"])
@@ -63,18 +65,18 @@ describe("complete thread read resource", () => {
it("writes empty reads with default pagination and no fabricated included resource", async () => {
const response = await writeCommunityThreadsRead(db, "viewer", parent, [])
- expect(communityReadSchemas(2).threads.parse(await response.json())).toMatchObject({ threads: [], included: { messages: [], tags: [], members: [], profiles: [], participantCounts: [] }, page: { nextCursor: null, hasMore: false } })
+ expect(communityReadSchemas().threads.parse(await response.json())).toMatchObject({ threads: [], included: { messages: [], tags: [], members: [], profiles: [], participantCounts: [] }, page: { nextCursor: null, hasMore: false } })
expect(mocks.replies).toHaveBeenCalledWith(db, [], ["forum"])
expect(mocks.attachments).toHaveBeenCalledWith(db, [])
expect(mocks.reactions).toHaveBeenCalledWith(db, [], "viewer")
})
it("deduplicates profiles while preserving the scoped participant counts", async () => {
- const participant = { channelId: "thread", userId: "viewer", userName: null, discriminator: "123456", userImage: null, userAvatarVersion: 0, participantCount: 2 }
+ const participant = { channelId: "thread", userId: "viewer", userName: "", discriminator: "123456", userImage: null, userAvatarVersion: 0, participantCount: 2 }
const otherChild = { ...child, id: "other-thread", creatorId: "other" }
const participants = [participant, { ...participant, userId: "other" }, { ...participant, channelId: "other-thread", participantCount: 1 }]
const response = await writeCommunityThreadsRead(db, "viewer", parent, [child, otherChild], { messages: [], tags: [], participants })
- const body = communityReadSchemas(2).threads.parse(await response.json())
+ const body = communityReadSchemas().threads.parse(await response.json())
expect(body.included.profiles.map((profile) => profile.id)).toEqual(["viewer", "other"])
expect(body.included.profiles[0]?.name).toBe("")
expect(body.included.participantCounts).toEqual([{ channelId: "thread", count: 2 }, { channelId: "other-thread", count: 1 }])
diff --git a/src/web/src/lib/community/thread-read.ts b/src/web/src/lib/community/thread-read.ts
index 793fe7c77..5f738bfdf 100644
--- a/src/web/src/lib/community/thread-read.ts
+++ b/src/web/src/lib/community/thread-read.ts
@@ -1,21 +1,22 @@
-import { CommunityResourceProfileSchema, communityReadSchemas, communityChannelResourceFromStorage, normalizeCommunityChannelResource, normalizeCommunityMessageResource, queries, type Database } from "@alook/shared"
+import { CommunityResourceProfileSchema, communityReadSchemas, communityChannelResourceFromStorage, COMMUNITY_CONTRACT_VERSION, type CommunityContract, queries, type Database } from "@alook/shared"
import { writeCommunityContractJSON } from "./read-contract"
import { loadApiMessageContext, mapMessageForApi } from "./message-payload"
import { canonicalUserImage } from "./storage"
import { resourceProfile, threadParticipantResources } from "./participant-resources"
+import { readCommunityResourceProfiles } from "./resource-profiles.server"
type Included = { messages: Array<Parameters<typeof mapMessageForApi>[0] & { channelId: string; replyToId: string | null }>;
tags: Array<{ messageId: string; tag: string }>;
participants: Awaited<ReturnType<typeof queries.communityThread.listParticipantsForChannels>> }
export async function writeCommunityThreadsRead(db: Database, userId: string, channel: unknown, threads: unknown[], included?: Included,
- page = { nextCursor: null as string | null, hasMore: false }, contract: 2 | 3 = 2) {
+ page = { nextCursor: null as string | null, hasMore: false }, contract: CommunityContract = COMMUNITY_CONTRACT_VERSION) {
return writeCommunityContractJSON(await readCommunityThreadsResource(db, userId, channel, threads, included, page, contract), contract)
}
export async function readCommunityThreadsResource(db: Database, userId: string, channel: unknown, threads: unknown[], included?: Included,
- page = { nextCursor: null as string | null, hasMore: false }, contract: 2 | 3 = 2) {
- const normalizeChannel = contract === 3 ? (value: unknown) => communityChannelResourceFromStorage(value) : normalizeCommunityChannelResource
+ page = { nextCursor: null as string | null, hasMore: false }, contract: CommunityContract = COMMUNITY_CONTRACT_VERSION) {
+ const normalizeChannel = communityChannelResourceFromStorage
const parent = normalizeChannel(channel)
const children = threads.map(normalizeChannel)
if (children.some((child) => child.parentChannelId !== parent.id || child.serverId !== parent.serverId)) throw new Error("Thread resource scope mismatch")
@@ -28,13 +29,16 @@ export async function readCommunityThreadsResource(db: Database, userId: string,
)
const messages = items.map((item) => {
const message = mapMessageForApi(item, contextForChannel(item.channelId), contract, item.channelId)
- return contract === 3 ? message : normalizeCommunityMessageResource(message, item.channelId)
+ return message
})
const participants = threadParticipantResources((included?.participants ?? []).map((row) => ({
channelId: row.channelId, userId: row.userId, isCreator: children.find((child) => child.id === row.channelId)?.creatorId === row.userId,
participantCount: "participantCount" in row ? Number(row.participantCount) : undefined,
- profile: resourceProfile({ id: row.userId, name: contract === 3 ? CommunityResourceProfileSchema.shape.name.parse(row.userName) : row.userName ?? "", discriminator: row.discriminator, avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion), avatarVersion: row.userAvatarVersion }),
+ profile: resourceProfile({ id: row.userId, name: CommunityResourceProfileSchema.shape.name.parse(row.userName), discriminator: row.discriminator, avatar: canonicalUserImage(row.userId, row.userImage, row.userAvatarVersion), avatarVersion: row.userAvatarVersion }),
})))
+ const profileIds = new Set(participants.profiles.map(profile => profile.id))
+ const authorIds = [...new Set(items.flatMap(item => [item.authorId, ...(item.replyToId ? [contextForChannel(item.channelId).replyMap.get(item.replyToId)?.authorId] : [])]).filter((id): id is string => !!id && !profileIds.has(id)))]
+ const authorProfiles = await readCommunityResourceProfiles(db, authorIds)
return communityReadSchemas(contract).threads.parse({ contractVersion: contract, channelId: parent.id, channel: parent, threads: children,
- included: { messages, ...participants, profiles: contract === 2 ? participants.profiles.map((profile) => ({ id: profile.id, name: profile.name, discriminator: profile.discriminator, avatar: profile.avatar, avatarVersion: profile.avatarVersion, statusEmoji: profile.statusEmoji ?? null, statusText: profile.statusText ?? "" })) : participants.profiles, tags: included?.tags ?? [] }, page })
+ included: { messages, ...participants, profiles: [...participants.profiles, ...authorProfiles], tags: included?.tags ?? [] }, page })
}
diff --git a/src/web/src/lib/community/virtual-list-position.test.ts b/src/web/src/lib/community/virtual-list-position.test.ts
deleted file mode 100644
index 759514237..000000000
--- a/src/web/src/lib/community/virtual-list-position.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { describe, expect, it } from "vitest"
-import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { captureChannelMetadataToken } from "./conversation-qualification"
-import { retireCommunityAccount } from "./account-cache-lifecycle"
-import { retireCommunityChannelReading } from "@/lib/community-db/sync"
-import { shouldDehydrateCommunityQuery } from "@/lib/query-persister"
-import { assessVirtualListPosition, readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "./virtual-list-position"
-
-const snapshot = (fingerprint = "rows"): VirtualListPositionSnapshot => ({
- version: 1, fingerprint, offset: 300, width: 320, height: 500, paddingStart: 0, paddingEnd: 48,
- anchorKey: "m3", anchorOffset: -20, at: Date.now(), measurements: [{ key: "m3", index: 3, start: 280, end: 380, size: 100, lane: 0 }],
-})
-
-describe("account-owned virtual layout lifetime", () => {
- it("isolates accounts, conversations, list shapes and tags without storing message bodies", async () => {
- const alice = await createCommunityQueryOwner("alice")
- const bob = await createCommunityQueryOwner("bob")
- const base: VirtualListPositionScope = { proof: captureChannelMetadataToken(alice.client, "A"), kind: "messages", tag: null }
- const rows = [{ key: "m1", content: "Private message text", grouped: false }]
- const fingerprint = virtualListLayoutFingerprint(rows)
- expect(assessVirtualListPosition(undefined, fingerprint)).toEqual({ snapshot: null, reason: "no_scope" })
- expect(assessVirtualListPosition(base, fingerprint)).toEqual({ snapshot: null, reason: "missing" })
- saveVirtualListPosition(base, snapshot(fingerprint))
- expect(assessVirtualListPosition(base, fingerprint)).toMatchObject({ reason: "available", snapshot: { offset: 300 } })
- expect(readVirtualListPosition(base, fingerprint)?.offset).toBe(300)
- for (const scope of [
- { ...base, proof: captureChannelMetadataToken(bob.client, "A") },
- { ...base, proof: captureChannelMetadataToken(alice.client, "B") },
- { ...base, kind: "forum" as const }, { ...base, tag: "bug" },
- ]) expect(readVirtualListPosition(scope, fingerprint)).toBeNull()
- expect(readVirtualListPosition(base, virtualListLayoutFingerprint([{ ...rows[0], grouped: true }]))).toBeNull()
- expect(assessVirtualListPosition(base, virtualListLayoutFingerprint([{ ...rows[0], grouped: true }]))).toEqual({ snapshot: null, reason: "fingerprint_mismatch" })
- expect(JSON.stringify(alice.client.getQueryData(virtualListPositionKey(base)))).not.toContain("Private message text")
- const query = alice.client.getQueryCache().find({ queryKey: virtualListPositionKey(base), exact: true })!
- expect(shouldDehydrateCommunityQuery(query)).toBe(false)
- })
-
- it("expires layout records and bounds the number and size of retained lists", async () => {
- const { client } = await createCommunityQueryOwner()
- const scopes = Array.from({ length: 33 }, (_, index): VirtualListPositionScope => ({ proof: captureChannelMetadataToken(client, `c${index}`), kind: "messages", tag: null }))
- for (const scope of scopes) saveVirtualListPosition(scope, snapshot())
- expect(client.getQueryCache().findAll({ predicate: query => query.queryKey[3] === "virtual-position" })).toHaveLength(32)
- expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()
- saveVirtualListPosition(scopes[32], { ...snapshot(), measurements: Array.from({ length: 2049 }, () => snapshot().measurements[0]) })
- expect(readVirtualListPosition(scopes[32], "rows")).toBeNull()
- saveVirtualListPosition(scopes[0], { ...snapshot(), measurements: Array.from({ length: 2049 }, () => snapshot().measurements[0]) })
- expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()
- saveVirtualListPosition(scopes[0], { ...snapshot(), at: Date.now() - 300001 })
- expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()
- expect(assessVirtualListPosition(scopes[0], "rows")).toEqual({ snapshot: null, reason: "expired" })
- })
-
- it("uses the existing account and channel retirement fences for stale capture callbacks", async () => {
- const { client, registry } = await createCommunityQueryOwner()
- const scope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
- saveVirtualListPosition(scope, snapshot())
- retireCommunityChannelReading(registry, "A", { reason: "read-denied", serverId: null })
- expect(client.getQueryData(virtualListPositionKey(scope))).toBeUndefined()
- saveVirtualListPosition(scope, snapshot())
- expect(readVirtualListPosition(scope, "rows")).toBeNull()
- expect(assessVirtualListPosition(scope, "rows")).toEqual({ snapshot: null, reason: "invalid_scope" })
- retireCommunityAccount(registry)
- saveVirtualListPosition(scope, snapshot())
- expect(client.getQueryData(virtualListPositionKey(scope))).toBeUndefined()
- })
-})
diff --git a/src/web/src/lib/community/virtual-list-position.ts b/src/web/src/lib/community/virtual-list-position.ts
deleted file mode 100644
index cca1e2e73..000000000
--- a/src/web/src/lib/community/virtual-list-position.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { hashKey } from "@tanstack/react-query"
-import type { VirtualItem } from "@tanstack/react-virtual"
-import { isChannelMetadataTokenCurrent, type captureChannelMetadataToken } from "./conversation-qualification"
-
-export type VirtualListPositionScope = {
- proof: ReturnType<typeof captureChannelMetadataToken>
- kind: "messages" | "forum"
- tag: string | null
-}
-
-export type VirtualListPositionSnapshot = {
- version: 1
- fingerprint: string
- offset: number
- width: number
- height: number
- paddingStart: number
- paddingEnd: number
- anchorKey: VirtualItem["key"]
- anchorOffset: number
- measurements: VirtualItem[]
- at: number
-}
-
-const POSITION_GC_MS = 5 * 60 * 1000
-const MAX_POSITION_LISTS = 32
-const MAX_POSITION_MEASUREMENTS = 2048
-
-export type VirtualListPositionReadReason = "no_scope" | "invalid_scope" | "missing" | "invalid_version" | "fingerprint_mismatch" | "expired" | "available"
-
-export function virtualListPositionKey({ proof, kind, tag }: VirtualListPositionScope) {
- const channelId = proof.channelId!
- const parentId = proof.channelLineage?.parentChannelId
- return ["community", "channel", channelId, "virtual-position", proof.viewerId, kind, tag,
- proof.accountEpoch, proof.accessEpoch, proof.ownerGeneration,
- proof.channelScopes.get(channelId)?.generation ?? 0,
- parentId ?? null, parentId ? proof.channelScopes.get(parentId)?.generation ?? 0 : 0] as const
-}
-
-export function virtualListLayoutFingerprint(rows: readonly unknown[]): string {
- const value = hashKey(rows)
- let first = 2166136261
- let second = 0x9e3779b9
- for (let index = 0; index < value.length; index++) {
- const code = value.charCodeAt(index)
- first = Math.imul(first ^ code, 16777619)
- second = Math.imul(second ^ code, 0x85ebca6b)
- }
- return `${value.length}:${first >>> 0}:${second >>> 0}`
-}
-
-function current(scope: VirtualListPositionScope) {
- return !!scope.proof.viewerId && !!scope.proof.channelId && isChannelMetadataTokenCurrent(scope.proof)
-}
-
-export function assessVirtualListPosition(scope: VirtualListPositionScope | undefined, fingerprint: string): { snapshot: VirtualListPositionSnapshot | null; reason: VirtualListPositionReadReason } {
- if (!scope) return { snapshot: null, reason: "no_scope" }
- if (!current(scope)) return { snapshot: null, reason: "invalid_scope" }
- const value = scope.proof.queryClient.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(scope))
- if (!value) return { snapshot: null, reason: "missing" }
- if (value.version !== 1) return { snapshot: null, reason: "invalid_version" }
- if (value.fingerprint !== fingerprint) return { snapshot: null, reason: "fingerprint_mismatch" }
- if (!(Date.now() - value.at < POSITION_GC_MS)) return { snapshot: null, reason: "expired" }
- return { snapshot: value, reason: "available" }
-}
-
-export function readVirtualListPosition(scope: VirtualListPositionScope | undefined, fingerprint: string) {
- return assessVirtualListPosition(scope, fingerprint).snapshot
-}
-
-export function saveVirtualListPosition(scope: VirtualListPositionScope | undefined, value: VirtualListPositionSnapshot) {
- if (!scope || !current(scope) || value.width <= 0 || value.height <= 0
- || !Number.isFinite(value.offset) || value.offset < 0 || !value.measurements.length) return
- const client = scope.proof.queryClient
- if (value.measurements.length > MAX_POSITION_MEASUREMENTS) {
- client.removeQueries({ queryKey: virtualListPositionKey(scope), exact: true })
- return
- }
- client.getQueryCache().build<VirtualListPositionSnapshot>(client, {
- queryKey: virtualListPositionKey(scope), gcTime: POSITION_GC_MS,
- }).setData(value)
- const records = client.getQueryCache().findAll({ predicate: query => query.queryKey[0] === "community"
- && query.queryKey[1] === "channel" && query.queryKey[3] === "virtual-position" })
- .sort((left, right) => left.state.dataUpdatedAt - right.state.dataUpdatedAt)
- for (const query of records.slice(0, Math.max(0, records.length - MAX_POSITION_LISTS))) client.getQueryCache().remove(query)
-}
diff --git a/src/web/src/lib/errors.ts b/src/web/src/lib/errors.ts
index 0fd41ff20..5be96a8c7 100644
--- a/src/web/src/lib/errors.ts
+++ b/src/web/src/lib/errors.ts
@@ -1,3 +1,8 @@
+import type { z } from "zod"
+import type { CommunityReadErrorSchema } from "@alook/shared"
+
+export type CommunityApiErrorPayload = z.infer<typeof CommunityReadErrorSchema>["error"]
+
export function isAbortError(error: unknown): error is { name: "AbortError" } {
return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
}
@@ -26,6 +31,17 @@ export class ApiError extends Error {
}
}
+export class CommunityApiError extends ApiError {
+ readonly code: CommunityApiErrorPayload["code"]
+ readonly retryable: CommunityApiErrorPayload["retryable"]
+
+ constructor(error: CommunityApiErrorPayload, status: number, message = error.message) {
+ super(message, status, error.details)
+ this.code = error.code
+ this.retryable = error.retryable
+ }
+}
+
export class UnauthorizedError extends ApiError {
constructor() { super("Unauthorized", 401) }
}
diff --git a/src/web/src/lib/middleware/auth.protocol.test.ts b/src/web/src/lib/middleware/auth.protocol.test.ts
new file mode 100644
index 000000000..13e60ff06
--- /dev/null
+++ b/src/web/src/lib/middleware/auth.protocol.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest, NextResponse } from "next/server"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { withCommunityActor } from "./community-actor"
+import { apiFetch } from "@/lib/api/client"
+import { withAuth, withCookieHumanAuth, withOptionalAuth, type OptionalAuthHandler } from "./auth"
+
+const mocks = vi.hoisted(() => ({ session: vi.fn(), signOut: vi.fn(), user: vi.fn(), machine: vi.fn(), bump: vi.fn(), bot: vi.fn() }))
+vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } })) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
+vi.mock("./community-agent-runner-auth", () => ({ resolveBotActor: mocks.bot }))
+vi.mock("@/lib/auth", () => ({ getAuth: vi.fn(() => ({ api: { getSession: mocks.session, signOut: mocks.signOut } })) }))
+vi.mock("@alook/shared", async original => {
+ const actual = await original<typeof import("@alook/shared")>()
+ return { ...actual, createDb: vi.fn(() => ({})), queries: { ...actual.queries, machineToken: { ...actual.queries.machineToken, getMachineTokenByToken: mocks.machine, updateMachineTokenLastUsed: mocks.bump }, user: { ...actual.queries.user, getUserInternal: mocks.user } } }
+})
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.session.mockResolvedValue({ headers: new Headers({ "Set-Cookie": "better-auth.session_data=refreshed; HttpOnly" }), response: { user: { id: "viewer", email: "[email protected]" } } })
+ mocks.user.mockResolvedValue({ id: "viewer", email: "[email protected]", isBot: false, deletedAt: null })
+})
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
+
+function connect(handler: ReturnType<typeof withOptionalAuth> | ReturnType<typeof withCookieHumanAuth>) {
+ let received: NextRequest | undefined, produced: Response | undefined
+ vi.stubGlobal("fetch", vi.fn(async (path: string, options?: RequestInit) => {
+ received = new NextRequest(new URL(path, "https://alook.test"), options)
+ produced = await handler(received)
+ return produced
+ }))
+ return { get request() { return received! }, get response() { return produced! } }
+}
+const sameOrigin = { Origin: "https://alook.test" }
+
+describe("current auth wrapper producer to API consumer", () => {
+ it("admits anonymous current invite info through optional auth", async () => {
+ mocks.session.mockResolvedValue({ headers: new Headers(), response: null })
+ const handler = vi.fn(async (_req: NextRequest, ctx: Parameters<OptionalAuthHandler>[1]) => NextResponse.json({ serverId: "server", anonymous: ctx.userId === undefined }))
+ const transport = connect(withOptionalAuth(handler))
+ expect(await apiFetch("/api/community/invites/token/info")).toEqual({ serverId: "server", anonymous: true })
+ expect(transport.request.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(transport.response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")
+ })
+ it("preserves optional-auth failure status and current readable error", async () => {
+ connect(withOptionalAuth(async () => NextResponse.json({ error: "invite expired" }, { status: 410 })))
+ await expect(apiFetch("/api/community/invites/token/info")).rejects.toMatchObject({ name: "ApiError", status: 410, message: "invite expired" })
+ })
+ it("confirms a live Cookie human result and forwards refreshed cookies", async () => {
+ const transport = connect(withCookieHumanAuth(async (_req, ctx) => NextResponse.json({ userId: ctx.userId, email: ctx.email })))
+ expect(await apiFetch("/api/community/billing/portal", { method: "POST", headers: sameOrigin })).toEqual({ userId: "viewer", email: "[email protected]" })
+ expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(transport.response.headers.get("Set-Cookie")).toContain("session_data=refreshed")
+ })
+ it("preserves current operation error messages through Cookie auth and apiFetch", async () => {
+ connect(withCookieHumanAuth(async () => NextResponse.json({ error: "INVALID_OTP" }, { status: 400 })))
+ await expect(apiFetch("/api/community/users/me/account-deletion", { method: "POST", headers: sameOrigin })).rejects.toMatchObject({ name: "ApiError", status: 400, message: "INVALID_OTP" })
+ })
+ it("keeps Origin rejection before session lookup", async () => {
+ connect(withCookieHumanAuth(async () => NextResponse.json({ ok: true })))
+ await expect(apiFetch("/api/community/billing/portal", { method: "POST", headers: { Origin: "https://other.test" } })).rejects.toMatchObject({ name: "ApiError", status: 403, message: "FORBIDDEN" })
+ expect(mocks.session).not.toHaveBeenCalled()
+ })
+ it("keeps a qualified401 transition and current protected response", async () => {
+ mocks.session.mockResolvedValue({ headers: new Headers(), response: null })
+ const transport = connect(withCookieHumanAuth(async () => NextResponse.json({ ok: true })))
+ const onUnauthorized = vi.fn(async () => false)
+ await expect(apiFetch("/api/community/billing/portal", { method: "POST", headers: sameOrigin, onUnauthorized })).rejects.toMatchObject({ name: "AbortError" })
+ expect(onUnauthorized).toHaveBeenCalledOnce()
+ expect(transport.response.status).toBe(401)
+ expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ })
+ it("keeps outside-community privacy Cookie operations independent", async () => {
+ const transport = connect(withCookieHumanAuth(async () => NextResponse.json({ consent: false })))
+ expect(await apiFetch("/api/privacy/analytics-consent", { method: "POST", headers: sameOrigin })).toEqual({ consent: false })
+ expect(transport.request.headers.get(COMMUNITY_CONTRACT_HEADER)).toBeNull()
+ expect(transport.response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBeNull()
+ })
+ it.each(["optional", "cookie"])("rejects an old request before the %s handler/session", async kind => {
+ const handler = vi.fn(async () => NextResponse.json({ ok: true }))
+ const wrapped = kind === "cookie" ? withCookieHumanAuth(handler) : withOptionalAuth(handler)
+ const response = await wrapped(new NextRequest("https://alook.test/api/community/operation", { method: "POST", headers: { ...sameOrigin, [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION - 1) } }))
+ expect(response.status).toBe(400)
+ expect(handler).not.toHaveBeenCalled()
+ expect(mocks.session).not.toHaveBeenCalled()
+ })
+})
+
+
+describe("independent actor qualification", () => {
+ function wrap(kind: string, handler: () => Promise<Response>) {
+ return kind === "optional" ? withOptionalAuth(handler) : kind === "actor" ? withCommunityActor(handler) : withAuth(handler)
+ }
+ it.each(["auth", "optional", "actor"].flatMap(kind => [null, BUSINESS_SCHEMA_VERSION - 1].map(version => ({ kind, version }))))("rejects an unqualified Bearer with live Cookie ($kind/$version)", async ({ kind, version }) => {
+ const handler = vi.fn(async () => NextResponse.json({ ok: true }))
+ const response = await wrap(kind, handler)(new NextRequest("https://alook.test/api/community/operation", { headers: { Cookie: "better-auth.session_token=live", Authorization: "Bearer invalid", ...(version === null ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(version) }) } }))
+ expect(response.status).toBe(400)
+ expect(handler).not.toHaveBeenCalled()
+ })
+ it.each(["auth", "optional", "actor"])("preserves current-header Cookie fallback (%s)", async kind => {
+ const handler = vi.fn(async () => NextResponse.json({ ok: true }))
+ const response = await wrap(kind, handler)(new NextRequest("https://alook.test/api/community/operation", { headers: { Cookie: "better-auth.session_token=live", Authorization: "Bearer invalid", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }))
+ expect(response.status).toBe(200); expect(handler).toHaveBeenCalledOnce()
+ expect(mocks.session).toHaveBeenCalledOnce()
+ })
+ it.each([true, false])("qualifies machine credentials before an independent request (%s)", async valid => {
+ mocks.machine.mockResolvedValue(valid ? { id: "mt", userId: "viewer", userEmail: "[email protected]", workspaceId: null } : null)
+ const handler = vi.fn(async () => NextResponse.json({ ok: true }))
+ const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/operation", { headers: { Cookie: "better-auth.session_token=live", Authorization: "Bearer al_credential" } }))
+ expect(response.status).toBe(valid ? 200 : 401)
+ expect(handler).toHaveBeenCalledTimes(valid ? 1 : 0)
+ expect(mocks.machine).toHaveBeenCalledOnce(); expect(mocks.session).not.toHaveBeenCalled()
+ })
+ it.each([true, false])("qualifies bot credentials before an independent request (%s)", async valid => {
+ mocks.bot.mockResolvedValue(valid ? { kind: "ok", actor: { botUserId: "bot", ownerUserId: "viewer", machineId: "machine", isActive: true } } : { kind: "error", response: NextResponse.json({ error: "invalid runner key" }, { status: 401 }) })
+ const handler = vi.fn(async () => NextResponse.json({ ok: true }))
+ const response = await withCommunityActor(handler)(new NextRequest("https://alook.test/api/community/operation", { headers: { Cookie: "better-auth.session_token=live", Authorization: "Bearer crk_credential" } }))
+ expect(response.status).toBe(valid ? 200 : 401)
+ expect(handler).toHaveBeenCalledTimes(valid ? 1 : 0)
+ expect(mocks.bot).toHaveBeenCalledOnce(); expect(mocks.session).not.toHaveBeenCalled()
+ })
+})
+
+describe("current independent media capability", () => {
+ it("admits the actual bot-avatar GET family after Cookie auth without a business header", async () => {
+ const handler = vi.fn(async () => new Response("png", { headers: { "Content-Type": "image/png" } }))
+ const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar?v=2", { headers: { Cookie: "better-auth.session_token=live" } }))
+ expect(response.status).toBe(200); expect(await response.text()).toBe("png")
+ expect(handler).toHaveBeenCalledOnce(); expect(mocks.session).toHaveBeenCalledOnce()
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBeNull()
+ })
+ it("keeps the same media read session-qualified", async () => {
+ mocks.session.mockResolvedValue({ headers: new Headers(), response: null })
+ const handler = vi.fn(async () => new Response("png"))
+ const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar"))
+ expect(response.status).toBe(401); expect(handler).not.toHaveBeenCalled()
+ })
+ it("requires the current JSON contract on bot-avatar upload", async () => {
+ const handler = vi.fn(async () => NextResponse.json({ url: "avatar" }))
+ const response = await withAuth(handler)(new NextRequest("https://alook.test/api/community/bots/bot/avatar", { method: "POST", headers: { Cookie: "better-auth.session_token=live" } }))
+ expect(response.status).toBe(400); expect(handler).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.ts
index 2bb3d2aac..29a18bb81 100644
--- a/src/web/src/lib/middleware/auth.test.ts
+++ b/src/web/src/lib/middleware/auth.test.ts
@@ -22,6 +22,9 @@ vi.mock("@alook/shared", async (importOriginal) => ({
user: {
getUserInternal: vi.fn(),
},
+ communityBot: {
+ getBotOwnedBy: vi.fn(),
+ },
},
}));
@@ -34,7 +37,8 @@ vi.mock("@/lib/auth", () => ({
}));
import { withAuth, withCookieHumanAuth, withOptionalAuth, warmMachineTokenCache } from "./auth";
-import { queries } from "@alook/shared";
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_BOT_ACTOR_HEADER, COMMUNITY_CONTRACT_HEADER, queries } from "@alook/shared";
+import { withCommunityActor, type CommunityActor } from "./community-actor";
const mockGetMachineTokenByHash = queries.machineToken
.getMachineTokenByToken as ReturnType<typeof vi.fn>;
@@ -842,8 +846,85 @@ describe("warmMachineTokenCache", () => {
describe("human-only bot-selection rejection", () => {
it.each([withAuth, withCookieHumanAuth, withOptionalAuth])("rejects bot selection before a human-only handler can mutate the owner (%#)", async (wrap) => {
const handler = vi.fn(async () => NextResponse.json({ ok: true }))
- const response = await wrap(handler)(new NextRequest("http://localhost/api/community/bots", { headers: { "X-Alook-Bot-Id": "bot_1" }, method: "POST" }))
+ const response = await wrap(handler)(new NextRequest("http://localhost/api/community/bots", { headers: { "X-Alook-Bot-Id": "bot_1", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST" }))
expect(response.status).toBe(403)
expect(handler).not.toHaveBeenCalled()
})
})
+
+describe("current contract with actual owner-delegated actor authentication", () => {
+ const ownedBot = queries.communityBot.getBotOwnedBy as ReturnType<typeof vi.fn>
+ const route = vi.fn(async (_request: NextRequest, context: { actor: CommunityActor }) => NextResponse.json({ actor: context.actor }))
+ const request = (version: string | null = String(BUSINESS_SCHEMA_VERSION)) => {
+ const headers = new Headers({ Cookie: "owner-session", [COMMUNITY_BOT_ACTOR_HEADER]: "selected-bot" })
+ if (version !== null) headers.set(COMMUNITY_CONTRACT_HEADER, version)
+ return new NextRequest("http://localhost/api/community/servers/channels", { headers })
+ }
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetCloudflareContext.mockResolvedValue({ env: { DB: {} }, ctx: { waitUntil: vi.fn() } })
+ mockGetSession.mockResolvedValue({ headers: new Headers(), response: { user: { id: "owner", email: "[email protected]", isBot: false, deletedAt: null } } })
+ mockGetMachineTokenByHash.mockResolvedValue(null)
+ ownedBot.mockResolvedValue({ id: "selected-bot", machineId: "machine", isActive: true })
+ })
+ it("admits the current owner session only after real auth and scoped bot resolution", async () => {
+ const response = await withCommunityActor(route)(request())
+ expect(response.status).toBe(200)
+ expect(ownedBot).toHaveBeenCalledWith({}, "selected-bot", "owner")
+ expect(await response.json()).toEqual({ actor: { kind: "bot", userId: "selected-bot", ownerUserId: "owner", machineId: "machine", isActive: true, delegatedByUserId: "owner" } })
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")
+ for (const field of ["Cookie", "Authorization", COMMUNITY_CONTRACT_HEADER, COMMUNITY_BOT_ACTOR_HEADER]) expect(response.headers.get("Vary")).toContain(field)
+ })
+ it.each([null, "2", "3", String(BUSINESS_SCHEMA_VERSION + 1)])("does not exempt a cookie request with bot selection and contract %s", async version => {
+ const response = await withCommunityActor(route)(request(version))
+ expect(response.status).toBe(400)
+ expect(mockGetSession).not.toHaveBeenCalled()
+ expect(ownedBot).not.toHaveBeenCalled()
+ expect(route).not.toHaveBeenCalled()
+ })
+ it("does not resolve or impersonate a selected bot without an authenticated owner", async () => {
+ mockGetSession.mockResolvedValue({ headers: new Headers(), response: null })
+ const response = await withCommunityActor(route)(request())
+ expect(response.status).toBe(401)
+ expect(ownedBot).not.toHaveBeenCalled()
+ expect(route).not.toHaveBeenCalled()
+ })
+ it("keeps foreign or missing bot refusal after the owner is authenticated", async () => {
+ ownedBot.mockResolvedValue(null)
+ const response = await withCommunityActor(route)(request())
+ expect(response.status).toBe(404)
+ expect(ownedBot).toHaveBeenCalledWith({}, "selected-bot", "owner")
+ expect(route).not.toHaveBeenCalled()
+ })
+ it("validates an invalid machine token before refusing missing-contract delegation", async () => {
+ const req = request(null)
+ req.headers.set("Authorization", "Bearer al_invalid-composition-control")
+ const response = await withCommunityActor(route)(req)
+ expect(response.status).toBe(401)
+ expect(mockGetMachineTokenByHash).toHaveBeenCalledWith({}, "al_invalid-composition-control")
+ expect(ownedBot).not.toHaveBeenCalled()
+ expect(route).not.toHaveBeenCalled()
+ })
+ it("allows the missing version only after a valid independent machine credential", async () => {
+ mockGetMachineTokenByHash.mockResolvedValue({ id: "machine-token", userId: "owner", userEmail: "[email protected]" })
+ const req = request(null)
+ req.headers.set("Authorization", "Bearer al_valid-composition-control")
+ const response = await withCommunityActor(route)(req)
+ expect(response.status).toBe(200)
+ expect(mockGetMachineTokenByHash).toHaveBeenCalledWith({}, "al_valid-composition-control")
+ expect(mockGetSession).not.toHaveBeenCalled()
+ expect(ownedBot).toHaveBeenCalledWith({}, "selected-bot", "owner")
+ expect(route).toHaveBeenCalledOnce()
+ })
+ it.each(["2", "3"])("refuses explicit old contract %s even after valid machine authentication", async version => {
+ mockGetMachineTokenByHash.mockResolvedValue({ id: "machine-token", userId: "owner", userEmail: "[email protected]" })
+ const req = request(version)
+ req.headers.set("Authorization", "Bearer al_valid-composition-control")
+ const response = await withCommunityActor(route)(req)
+ expect(response.status).toBe(400)
+ expect(mockGetMachineTokenByHash).toHaveBeenCalledWith({}, "al_valid-composition-control")
+ expect(ownedBot).not.toHaveBeenCalled()
+ expect(route).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/middleware/auth.ts b/src/web/src/lib/middleware/auth.ts
index fcdc3f2a4..4fcb502ce 100644
--- a/src/web/src/lib/middleware/auth.ts
+++ b/src/web/src/lib/middleware/auth.ts
@@ -245,6 +245,11 @@ function isCookieHumanSameOrigin(req: NextRequest): boolean {
}
export function withCookieHumanAuth(handler: CookieHumanAuthHandler) {
+ const authenticate = createCookieHumanAuthHandler(handler)
+ return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], await authenticate(...args))
+}
+
+function createCookieHumanAuthHandler(handler: CookieHumanAuthHandler) {
return async (
req: NextRequest,
context?: { params?: Promise<Record<string, string>> | Record<string, string> },
@@ -263,6 +268,8 @@ export function withCookieHumanAuth(handler: CookieHumanAuthHandler) {
if (req.headers.has("Authorization")) {
return accountDeletionAuthError("UNAUTHORIZED", 401)
}
+ const unsupported = rejectUnknownCommunityContract(req)
+ if (unsupported) return unsupported
const cloudflare = await getCloudflareContext({ async: true })
const cloudflareEnv = cloudflare.env as Env
@@ -309,7 +316,7 @@ export function withCookieHumanAuth(handler: CookieHumanAuthHandler) {
export function withAuth(handler: AuthenticatedHandler, options: { allowBotSelection?: boolean } = {}) {
const authenticate = createAuthenticatedHandler(handler, options)
- return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], rejectUnknownCommunityContract(args[0]) ?? await authenticate(...args))
+ return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], await authenticate(...args))
}
function createAuthenticatedHandler(handler: AuthenticatedHandler, options: { allowBotSelection?: boolean }) {
@@ -326,11 +333,14 @@ function createAuthenticatedHandler(handler: AuthenticatedHandler, options: { al
: context.params
: undefined
+ const authHeader = req.headers.get("Authorization")
+ if (!authHeader?.startsWith("Bearer al_")) {
+ const unsupported = rejectUnknownCommunityContract(req)
+ if (unsupported) return unsupported
+ }
const { env } = await getCloudflareContext({ async: true })
const cloudflareEnv = env as Env
bindCacheKV(cloudflareEnv.CACHE_KV ?? null)
-
- const authHeader = req.headers.get("Authorization")
if (authHeader?.startsWith("Bearer ")) {
const raw = authHeader.slice(7)
if (raw.startsWith("al_")) {
@@ -392,6 +402,8 @@ function createAuthenticatedHandler(handler: AuthenticatedHandler, options: { al
// failure — those throw and fall to the 503 catch below.
return NextResponse.json({ error: "invalid token" }, { status: 401 })
}
+ const unsupported = rejectUnknownCommunityContract(req, true)
+ if (unsupported) return unsupported
if (bump) {
Promise.resolve(queries.machineToken.updateMachineTokenLastUsed(db, mt.id)).catch(() => {})
}
@@ -461,6 +473,11 @@ function createAuthenticatedHandler(handler: AuthenticatedHandler, options: { al
* reusable by any future login-optional page.
*/
export function withOptionalAuth(handler: OptionalAuthHandler) {
+ const authenticate = createOptionalAuthHandler(handler)
+ return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], rejectUnknownCommunityContract(args[0]) ?? await authenticate(...args))
+}
+
+function createOptionalAuthHandler(handler: OptionalAuthHandler) {
return async (
req: NextRequest,
context?: { params?: Promise<Record<string, string>> | Record<string, string> }
diff --git a/src/web/src/lib/middleware/community-actor.test.ts b/src/web/src/lib/middleware/community-actor.test.ts
index c99c30a1e..dfcf87ba7 100644
--- a/src/web/src/lib/middleware/community-actor.test.ts
+++ b/src/web/src/lib/middleware/community-actor.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest, NextResponse } from "next/server"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
// The unified actor is a thin router over two collaborators:
// - resolveBotActor (crk_ → bot identity) — the bot path;
@@ -146,7 +147,7 @@ describe("owner selected bot", () => {
mockHumanCtx = { env: { DB: {} }, userId: "human_1", email: "[email protected]" }
mockResolveOwnedBotActor.mockResolvedValue({ kind: "bot", actor: { botUserId: "bot_1", ownerUserId: "human_1", machineId: "offline_machine", isActive: true } })
})
- const request = () => new NextRequest("http://localhost/api/community/servers/channels", { headers: { "X-Alook-Bot-Id": "bot_1" } })
+ const request = () => new NextRequest("http://localhost/api/community/servers/channels", { headers: { "X-Alook-Bot-Id": "bot_1", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
it("authenticates the owner then delegates only the selected bot identity, with a private varied response", async () => {
const response = await withCommunityActor(handler)(request())
expect(mockResolveOwnedBotActor).toHaveBeenCalledWith({}, "bot_1", "human_1", { allowInactive: undefined })
diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.ts
index 5cd3db872..367024604 100644
--- a/src/web/src/lib/middleware/community-actor.ts
+++ b/src/web/src/lib/middleware/community-actor.ts
@@ -83,7 +83,7 @@ export function withCommunityActor(
options: { allowInactiveBot?: boolean } = {},
) {
const authenticate = createCommunityActorHandler(handler, options)
- return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], rejectUnknownCommunityContract(args[0]) ?? await authenticate(...args))
+ return async (...args: Parameters<typeof authenticate>) => protectCommunityJsonResponse(args[0], await authenticate(...args))
}
function createCommunityActorHandler(
@@ -124,6 +124,8 @@ function createCommunityActorHandler(
return NextResponse.json({ error: "invalid runner key" }, { status: 401 })
}
+ const unsupported = rejectUnknownCommunityContract(req, true)
+ if (unsupported) return unsupported
return varyPrivateResponseByCredentials(await handler(req, {
env: cloudflareEnv,
actor: {
diff --git a/src/web/src/lib/middleware/response-cache.test.ts b/src/web/src/lib/middleware/response-cache.test.ts
index 35526b5dc..f567815d9 100644
--- a/src/web/src/lib/middleware/response-cache.test.ts
+++ b/src/web/src/lib/middleware/response-cache.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, it } from "vitest"
-import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { protectCommunityJsonResponse, rejectUnknownCommunityContract } from "./response-cache"
describe("protected community JSON policy", () => {
it.each([200, 400, 401, 403, 404, 409, 429, 500, 503])("protects status %s and preserves cookies and vary", async (status) => {
- const request = new Request("https://alook.test/api/community/channels/c/messages", { headers: { [COMMUNITY_CONTRACT_HEADER]: "2" } })
+ const request = new Request("https://alook.test/api/community/channels/c/messages", { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
const response = await protectCommunityJsonResponse(request, Response.json(status === 200 ? { value: 1 } : { error: "blocked" }, { status,
headers: { "Vary": "Origin, cookie", "Cache-Control": "public, max-age=600", "ETag": "old", "Last-Modified": "old", "Set-Cookie": "session=refreshed; HttpOnly" } }))
expect(response.headers.get("Cache-Control")).toBe("private, no-store, max-age=0")
@@ -12,7 +12,8 @@ describe("protected community JSON policy", () => {
expect(response.headers.get("ETag")).toBeNull()
expect(response.headers.get("Last-Modified")).toBeNull()
expect(response.headers.get("Set-Cookie")).toBe("session=refreshed; HttpOnly")
- if (status !== 200) expect(await response.json()).toMatchObject({ contractVersion: 2, error: { message: "blocked", retryable: status >= 500 || status === 429 } })
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ if (status !== 200) expect(await response.json()).toMatchObject({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { message: "blocked", retryable: status >= 500 || status === 429 } })
})
it("preserves the independent media policy and rejects unknown versions", async () => {
const request = new Request("https://alook.test/api/community/channels/c/icon", { headers: { [COMMUNITY_CONTRACT_HEADER]: "4" } })
diff --git a/src/web/src/lib/middleware/response-cache.ts b/src/web/src/lib/middleware/response-cache.ts
index 4c5f65a50..bb7e9f0fb 100644
--- a/src/web/src/lib/middleware/response-cache.ts
+++ b/src/web/src/lib/middleware/response-cache.ts
@@ -1,34 +1,43 @@
-import { COMMUNITY_BOT_ACTOR_HEADER, COMMUNITY_CONTRACT_HEADER, requestedCommunityContract, communityReadSchemas, requestsCommunityContract } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_BOT_ACTOR_HEADER, COMMUNITY_CONTRACT_HEADER, requestedCommunityContract, communityReadSchemas, requestsCommunityContract } from "@alook/shared"
-export function rejectUnknownCommunityContract(request: Request): Response | null {
+export function rejectUnknownCommunityContract(request: Request, independentActor = false): Response | null {
const version = request.headers.get(COMMUNITY_CONTRACT_HEADER)
- return new URL(request.url).pathname.startsWith("/api/community/") && version !== null && requestedCommunityContract(request.headers) === null
- ? Response.json({ error: "unsupported community contract" }, { status: 400 }) : null
+ const path = new URL(request.url).pathname
+ if (!path.startsWith("/api/community/")) return null
+ const mediaRead = ["GET", "HEAD"].includes(request.method)
+ && (/\/(?:users|servers|bots)\/[^/]+\/(?:avatar|icon)$/.test(path)
+ || /^\/api\/community\/share-image\/avatar\//.test(path)
+ || /\/channels\/[^/]+\/attachments\/[^/]+(?:\/thumbnail)?$/.test(path))
+ if (version === null && (independentActor || mediaRead)) return null
+ return requestedCommunityContract(request.headers) === BUSINESS_SCHEMA_VERSION ? null
+ : Response.json({ error: "unsupported community contract", schemaVersion: BUSINESS_SCHEMA_VERSION }, { status: 400 })
}
export async function protectCommunityJsonResponse(request: Request, response: Response): Promise<Response> {
if (!new URL(request.url).pathname.startsWith("/api/community/")) return response
const contentType = response.headers.get("Content-Type")?.split(";", 1)[0].trim().toLowerCase()
- if (contentType !== "application/json" && !contentType?.endsWith("+json")) return response
+ if (response.status !== 204 && contentType !== "application/json" && !contentType?.endsWith("+json")) return response
let result = new Response(response.body, response)
if (!response.ok && requestsCommunityContract(request.headers)) {
- const contract = requestedCommunityContract(request.headers) === 3 ? 3 : 2
+ const contract = BUSINESS_SCHEMA_VERSION
const schema = communityReadSchemas(contract).error
const body: unknown = await result.clone().json()
const alreadyVersioned = schema.safeParse(body)
if (!alreadyVersioned.success) {
const raw = typeof body === "object" && body !== null && "error" in body ? body.error : undefined
const message = typeof raw === "string" ? raw : "request failed"
+ const details = typeof body === "object" && body !== null && "details" in body && Array.isArray(body.details)
+ && body.details.every(detail => typeof detail === "string") ? body.details : undefined
const code = response.status === 401 ? "unauthenticated" : response.status === 404 ? "not_found"
: response.status === 403 ? message === "blocked" ? "blocked" : "not_allowed"
: response.status === 409 ? "idempotency_conflict" : response.status === 429 ? "rate_limited"
: response.status >= 500 ? "temporarily_unavailable" : "invalid_input"
result = new Response(JSON.stringify(schema.parse({ contractVersion: contract,
- error: { code, message, retryable: response.status === 429 || response.status >= 500 } })), result)
+ error: { code, message, retryable: response.status === 429 || response.status >= 500, ...(details ? { details } : {}) } })), result)
result.headers.delete("Content-Length")
}
- result.headers.set(COMMUNITY_CONTRACT_HEADER, String(contract))
}
+ result.headers.set(COMMUNITY_CONTRACT_HEADER, String(BUSINESS_SCHEMA_VERSION))
result.headers.set("Cache-Control", "private, no-store, max-age=0")
result.headers.delete("ETag")
result.headers.delete("Last-Modified")
diff --git a/src/web/src/lib/observability/client.dom.test.ts b/src/web/src/lib/observability/client.dom.test.ts
index 9af4d4b83..15badb0ef 100644
--- a/src/web/src/lib/observability/client.dom.test.ts
+++ b/src/web/src/lib/observability/client.dom.test.ts
@@ -1,3 +1,4 @@
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import faroPackage from "@grafana/faro-web-sdk/package.json"
import { afterEach, expect, it, vi } from "vitest"
import { act } from "@/test/react-dom-harness"
@@ -24,7 +25,7 @@ it("real Faro sessions align after interrupted import, regrant, account changes,
const url = String(_url instanceof Request ? _url.url : _url)
if (url === "https://collector.example/collect/public" && options?.body) sent.push(JSON.parse(String(options.body)))
if (url === "https://collector.example/collect/public") return new Response(null, { status: collectorStatus })
- return url.endsWith("/api/community/channels/private/messages") ? new Response("{}", { status: 201 }) : new Response(null, { status: 204 })
+ return url.endsWith("/api/community/channels/private/messages") ? new Response("{}", { status: 201, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } }) : new Response(null, { status: 204, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
}))
const { bootstrapObservability, setTelemetryUser } = await import("./client")
const { emitTelemetry, telemetryGeneration, isTelemetryEligible } = await import("./telemetry")
diff --git a/src/web/src/lib/observability/conversation-export.dom.test.tsx b/src/web/src/lib/observability/conversation-export.dom.test.tsx
index cde90761f..c613615c9 100644
--- a/src/web/src/lib/observability/conversation-export.dom.test.tsx
+++ b/src/web/src/lib/observability/conversation-export.dom.test.tsx
@@ -9,12 +9,11 @@ import { CommunityDbProvider } from "@/lib/community-db/projections"
import { communityKeys } from "@/lib/query-keys"
import { useMessages } from "@/hooks/community/use-messages"
import { announceAnalyticsConsent } from "@/lib/analytics-consent"
-import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { traceResponse } from "./trace-response"
import { useObservedRegion } from "./regions"
import { installMessageScrollFixture, restoreMessageScrollFixture, mount } from "@/test/message-scroll-fixture"
import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
-import { virtualListPositionKey, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
const native = vi.hoisted(() => {
vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")
@@ -68,12 +67,12 @@ it("exports real cache, entry, repair and request roles through installed Faro a
const respond = (body: unknown, version: number) => traceResponse(new Response(JSON.stringify(body), {
headers: { "content-type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(version) },
}), request, { isTraced: true, spanContext: () => ({ traceId: "a".repeat(32), spanId: "b".repeat(16), traceFlags: 1 }) })
- if (url.searchParams.has("entry")) return new Promise<Response>(resolve => { releaseEntry = () => resolve(respond(next, 3)) })
- const page = { contractVersion: 2, channelId: "c1", surfaceReceipt: value.surfaceReceipt,
+ if (url.searchParams.has("entry")) return new Promise<Response>(resolve => { releaseEntry = () => resolve(respond(next, BUSINESS_SCHEMA_VERSION)) })
+ const page = { profiles: value.profiles, contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", surfaceReceipt: value.surfaceReceipt,
messages: [second], page: { ...value.page, latestSeq: 2, hasMoreNewer: false } }
- if (url.searchParams.has("since")) return new Promise<Response>(resolve => { releaseRepair = () => resolve(respond(page, 2)) })
- if (url.searchParams.has("cursor")) return respond({ ...page, messages: [{ ...value.messages[0], id: "m0", seq: 0 }], page: { ...page.page, hasMoreOlder: false, olderCursor: null } }, 2)
- return respond({ ...page, messages: [...value.messages, second] }, 2)
+ if (url.searchParams.has("since")) return new Promise<Response>(resolve => { releaseRepair = () => resolve(respond(page, BUSINESS_SCHEMA_VERSION)) })
+ if (url.searchParams.has("cursor")) return respond({ ...page, messages: [{ ...value.messages[0], id: "m0", seq: 0 }], page: { ...page.page, hasMoreOlder: false, olderCursor: null } }, BUSINESS_SCHEMA_VERSION)
+ return respond({ ...page, messages: [...value.messages, second] }, BUSINESS_SCHEMA_VERSION)
}))
document.cookie = "alook_analytics_consent=v1.granted; path=/"
announceAnalyticsConsent("granted")
@@ -120,18 +119,15 @@ it("exports real cache, entry, repair and request roles through installed Faro a
native.faro!.api.pushEvent("conversation.cache", { cache_reason: "PRIVATE257-invalid", content: "PRIVATE257-content", cache_window: "ready" })
const position = mount({ scrollToMessageId: "m4", positionDataState: "ready" })
position.view.unmount()
- const positionScope = { proof: captureChannelMetadataToken(owner.client, "c1"), kind: "messages" as const, tag: null }
+ const positionScope = { proof: captureChannelMetadataToken(owner.client, "c1"), tag: null }
const saved = mount({ positionScope })
saved.move(600)
saved.view.unmount()
- const restored = mount({ positionScope })
- expect(restored.root.scrollTop).toBeCloseTo(600, 0)
- restored.view.unmount()
- owner.client.setQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope), previous => ({
- ...previous!, fingerprint: "PRIVATE257-position-fingerprint", anchorKey: "PRIVATE257-position-anchor",
- }))
- const rejected = mount({ positionScope })
- rejected.view.unmount()
+ const entered = mount({ positionScope })
+ expect(entered.root.scrollTop).not.toBe(600)
+ entered.view.unmount()
+ const readTarget = mount({ positionScope, initialPositionMessageId: "m4" })
+ readTarget.view.unmount()
native.faro!.api.pushEvent("position.finish", { position_source: "PRIVATE257-invalid", position_snapshot: "PRIVATE257-invalid", snapshot: "PRIVATE257-body" })
await act(async () => owner.registry.collections.channelMemberships.utils.writeDelete("c1:viewer:access"))
await vi.advanceTimersByTimeAsync(5000)
@@ -152,9 +148,10 @@ it("exports real cache, entry, repair and request roles through installed Faro a
const roles = new Set(events.filter(event => event.name === "request.start").map(event => event.attributes.request_role))
expect(roles).toEqual(new Set(["entry", "reconcile", "window", "pagination"]))
expect(events).toContainEqual(expect.objectContaining({ name: "region.wait_change", attributes: expect.objectContaining({ wait_reason: "position", last_wait_reason: "entry" }) }))
- expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_owner: "target", position_reason: "settled", position_source: "explicit_target", position_snapshot: "not_requested" }) }))
- expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_source: "snapshot", position_snapshot: "accepted" }) }))
- expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_source: "tail", position_snapshot: "fingerprint_mismatch" }) }))
+ expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_owner: "target", position_reason: "settled", position_source: "explicit_target" }) }))
+ expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_source: "read_anchor" }) }))
+ expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_source: "tail" }) }))
+ for (const event of events) expect(event.attributes).not.toHaveProperty("position_snapshot")
const wait = spans.find(span => span.name === "region.wait")!
expect(wait.parentSpanId).toBe(navigation.span!.spanContext().spanId)
expect(Object.fromEntries(wait.attributes.map(attribute => [attribute.key, attribute.value.stringValue]))).toMatchObject({ initial_wait_reason: "entry", last_wait_reason: "position", wait_reason: "none", outcome: "success" })
diff --git a/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx
index f48be7019..6a6086418 100644
--- a/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx
+++ b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx
@@ -1,3 +1,4 @@
+import { COMMUNITY_CONTRACT_HEADER, BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { useLayoutEffect } from "react"
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"
import { afterEach, expect, it, vi } from "vitest"
@@ -31,7 +32,7 @@ it("binds the initial navigation before ready and parents a real native HTTP spa
vi.stubGlobal("fetch", vi.fn(async (url: unknown, options?: RequestInit) => {
if (String(url) === "https://collector.example/collect/public" && options?.body) sent.push(JSON.parse(String(options.body)))
else { now = 1012; vi.setSystemTime(Date.now() - 120_000) }
- return new Response(null, { status: 204 })
+ return new Response(null, { status: 204, headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
}))
document.cookie = "alook_analytics_consent=v1.granted; path=/"
window.history.replaceState(null, "", "/c/channels/server-a/channel-a")
diff --git a/src/web/src/lib/observability/position.ts b/src/web/src/lib/observability/position.ts
index c203b9431..5247dab6f 100644
--- a/src/web/src/lib/observability/position.ts
+++ b/src/web/src/lib/observability/position.ts
@@ -1,17 +1,15 @@
-import type { VirtualListPositionReadReason, VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import type { ConversationListScope } from "@/lib/community/conversation-qualification"
import { channelHref, normalizeCommunityHref } from "@/lib/community/community-route"
import { actionAttributes, currentPageObservation, navigationForHref } from "./context"
import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "./telemetry"
export type PositionReason = "settled" | "empty" | "target_missing" | "manual_takeover" | "hidden" | "entry_changed" | "retired" | "data_error" | "cancelled" | "superseded" | "origin_changed"
type PositionOwner = "initial" | "late-new" | "target" | "present" | "idle"
-export type PositionSnapshotReason = VirtualListPositionReadReason | "not_requested" | "entry_changed" | "viewport_mismatch" | "padding_mismatch" | "anchor_missing" | "accepted"
export type PositionDecision = {
- position_source: "snapshot" | "read_anchor" | "explicit_target" | "new_divider" | "tail" | "unknown"
- position_snapshot: PositionSnapshotReason
+ position_source: "read_anchor" | "explicit_target" | "new_divider" | "tail" | "unknown"
}
-export function beginPositionObservation(kind: PositionOwner, scope?: VirtualListPositionScope, entry?: object | null) {
+export function beginPositionObservation(kind: PositionOwner, scope?: ConversationListScope, entry?: object | null) {
const start = performance.now()
const generation = telemetryGeneration()
const eligible = isTelemetryEligible()
@@ -28,7 +26,7 @@ export function beginPositionObservation(kind: PositionOwner, scope?: VirtualLis
done = true
if (!eligible || generation !== telemetryGeneration()) return
emitTelemetry("position.finish", { ...actionAttributes(action), position_owner: kind, position_reason: reason,
- position_source: decision?.position_source ?? "unknown", position_snapshot: decision?.position_snapshot ?? "not_requested",
+ position_source: decision?.position_source ?? "unknown",
start_ms: start, duration_ms: Math.max(0, performance.now() - start),
target_coverage: reason === "settled" ? "covered" : reason === "target_missing" ? "uncovered" : "unknown" })
}
diff --git a/src/web/src/lib/observability/schema.ts b/src/web/src/lib/observability/schema.ts
index 36259fb26..deae5ee7c 100644
--- a/src/web/src/lib/observability/schema.ts
+++ b/src/web/src/lib/observability/schema.ts
@@ -51,10 +51,9 @@ const enumValues: Record<string, ReadonlySet<string>> = Object.fromEntries(Objec
reconcile_stage: ["start", "settled", "error", "cancelled", "retired"],
request_role: ["entry", "window", "reconcile", "pagination"],
window_mode: ["newest", "anchor", "since", "older", "newer"],
- position_owner: ["idle", "initial", "target", "late-new", "present", "pagination", "restore"],
+ position_owner: ["idle", "initial", "target", "late-new", "present", "pagination"],
position_reason: ["settled", "empty", "target_missing", "manual_takeover", "hidden", "entry_changed", "retired", "data_error", "cancelled", "superseded", "origin_changed"],
- position_source: ["snapshot", "read_anchor", "explicit_target", "new_divider", "tail", "unknown"],
- position_snapshot: ["no_scope", "invalid_scope", "missing", "invalid_version", "fingerprint_mismatch", "expired", "available", "not_requested", "entry_changed", "viewport_mismatch", "padding_mismatch", "anchor_missing", "accepted"],
+ position_source: ["read_anchor", "explicit_target", "new_divider", "tail", "unknown"],
initial_wait_reason: ["none", "entry", "window", "projection", "identity", "restore", "position", "unknown"],
last_wait_reason: ["none", "entry", "window", "projection", "identity", "restore", "position", "unknown"],
wait_reason: ["none", "entry", "window", "projection", "identity", "restore", "position", "unknown"],
diff --git a/src/web/src/lib/query-persister.cold-restore.test.ts b/src/web/src/lib/query-persister.cold-restore.test.ts
index 07c2d6308..342a3ab10 100644
--- a/src/web/src/lib/query-persister.cold-restore.test.ts
+++ b/src/web/src/lib/query-persister.cold-restore.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import { del, get, set } from "idb-keyval"
import { afterEach, describe, expect, it, vi } from "vitest"
@@ -8,12 +9,12 @@ import { communityKeys } from "./query-keys"
import * as persistence from "./query-persister"
const key = (user: string) => `${persistence.PERSIST_CACHE_PREFIX}:${user}:client`
-const accountKey = (user: string) => `${persistence.PERSIST_CACHE_PREFIX}:${user}:account-epoch`
+const accountKey = (user: string) => `${persistence.PERSIST_ACCOUNT_PREFIX}:${user}:account-epoch`
function snapshot(user: string, content = "Cached"): PersistedClient {
const client = new QueryClient()
- client.setQueryData(communityKeys.communityDbCollection(user, "channels"), ["a", "b"].map(id => canonicalChannelRow({ id, type: "dm", name: id, preview: content })))
- client.setQueryData(communityKeys.communityDbCollection(user, "messages"), ["a", "b"].map(channelId => ({ id: `m-${channelId}`, channelId, type: "chat", resourceComplete: false, authorId: user, authorName: "Viewer", authorAvatar: "V", authorAvatarVersion: 0, seq: 1, content })))
+ client.setQueryData(communityKeys.communityDbCollection(user, "channels"), ["a", "b"].map(id => canonicalChannelRow({ ...channelResourceFixture({ id, type: "dm", serverId: null, name: id }), preview: content })))
+ client.setQueryData(communityKeys.communityDbCollection(user, "messages"), ["a", "b"].map(channelId => messageResourceFixture({ id: `m-${channelId}`, channelId, authorId: user, authorName: "Viewer", authorAvatar: "V", authorAvatarVersion: 0, seq: 1, content })))
const result = { timestamp: Date.now(), buster: persistence.PERSIST_BUSTER, clientState: dehydrate(client) }
client.clear()
return result
@@ -45,7 +46,7 @@ describe("cold IDB snapshot processing", () => {
await writer.persistClient(snapshot(user, "Old"))
const reader = persistence.createIdbPersister(user)
expect(await reader.isCurrent()).toBe(true)
- await set(key(user), JSON.stringify({ ...snapshot(user, "New"), version: persistence.PERSIST_VERSION, channelFences: [] }))
+ await set(key(user), JSON.stringify({ ...JSON.parse((await get<string>(key(user)))!), ...snapshot(user, "New"), version: persistence.PERSIST_VERSION, channelFences: [] }))
expect(messages(await reader.restoreClient())).toEqual(expect.arrayContaining([expect.objectContaining({ content: "New" })]))
})
@@ -56,7 +57,7 @@ describe("cold IDB snapshot processing", () => {
await reader.isCurrent()
if (kind === "removed") await del(key(user))
else if (kind === "corrupt") await set(key(user), "{")
- else await set(key(user), JSON.stringify({ ...snapshot(user), version: kind === "version" ? 5 : persistence.PERSIST_VERSION, buster: kind === "buster" ? "old" : persistence.PERSIST_BUSTER, channelFences: [] }))
+ else await set(key(user), JSON.stringify({ ...JSON.parse((await get<string>(key(user)))!), ...snapshot(user), version: kind === "version" ? 5 : persistence.PERSIST_VERSION, buster: kind === "buster" ? "old" : persistence.PERSIST_BUSTER, channelFences: [] }))
expect(await reader.restoreClient()).toBeUndefined()
expect(await get(key(user))).toBeUndefined()
})
diff --git a/src/web/src/lib/query-persister.forum-window.test.ts b/src/web/src/lib/query-persister.forum-window.test.ts
index db4689d76..6e26b0c06 100644
--- a/src/web/src/lib/query-persister.forum-window.test.ts
+++ b/src/web/src/lib/query-persister.forum-window.test.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { channelResourceFixture, messageResourceFixture, serverResourceFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import { afterEach, describe, expect, it } from "vitest"
import { dehydrate, QueryClient } from "@tanstack/react-query"
@@ -15,31 +17,34 @@ function setup(empty = false) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
owners.push(client)
const rows = {
- servers: [serverSchema.parse({ id: serverId, name: "Server", discriminator: "0001", description: "", ownerId: accountId,
- icon: null, official: false, isOwner: true, unread: false, mentions: 0, detailComplete: true })],
- channels: [canonicalChannelRow({ id: "forum", type: "forum", serverId }),
- ...empty ? [] : [canonicalChannelRow({ id: "post", type: "thread", serverId, parentChannelId: "forum", parentMessageId: "opener" })]],
- messages: empty ? [] : [messageSchema.parse({ id: "opener", channelId: "forum", type: "chat", content: "Canonical title", seq: 1 })],
- channelMemberships: empty ? [] : [canonicalChannelMembershipRow("post", accountId, "notify")],
+ servers: [serverResourceFixture({ id: serverId, name: "Server", discriminator: "0001", ownerId: accountId })],
+ channels: [canonicalChannelRow(channelResourceFixture({ id: "forum", type: "forum", serverId })),
+ ...empty ? [] : [canonicalChannelRow(channelResourceFixture({ id: "post", type: "thread", serverId, parentChannelId: "forum", parentMessageId: "opener" }))]],
+ messages: empty ? [] : [messageResourceFixture({ id: "opener", channelId: "forum", content: "Canonical title", seq: 1 })],
+ channelMemberships: empty ? [] : [canonicalChannelMembershipRow("post", accountId, "notify", { source: "spoke" })],
}
for (const [name, data] of Object.entries(rows)) client.setQueryData(communityKeys.communityDbCollection(accountId, name), data)
+ const directory = { schemaVersion: BUSINESS_SCHEMA_VERSION, accountId, serverId, categoryIds: [], channelIds: ["forum"] }
+ client.setQueryData(communityKeys.server(serverId), directory)
const result = {
threads: [{ id: "duplicated-entity", title: "Must not persist" }], verifiedEpoch: 99,
serverNow: new Date().toISOString(), serverClockOffsetMs: 0,
- window: { version: 1 as const, accountId, serverId, parents: ["forum"],
+ window: { version: BUSINESS_SCHEMA_VERSION, accountId, serverId, parents: ["forum"],
base: empty ? [] : [{ id: "post", parentChannelId: "forum", parentMessageId: "opener" }], retained: null },
}
client.setQueryData(key, result)
const snapshot = () => ({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client, { shouldDehydrateQuery: shouldDehydrateCommunityQuery }) })
- return { client, rows, result, snapshot }
+ return { client, rows: { ...rows, directory }, result, snapshot }
}
describe("scoped forum window persistence", () => {
it("refreshes a restored forum-only window when visible text parents are missing", () => {
const owner = setup()
- const rows = { ...owner.rows, channels: [...owner.rows.channels, canonicalChannelRow({ id: "text", serverId, type: "text" })] }
+ const rows = { ...owner.rows, directory: { ...owner.rows.directory, channelIds: ["forum", "text"] },
+ channels: [...owner.rows.channels, canonicalChannelRow(channelResourceFixture({ id: "text", serverId, type: "text" }))] }
expect(forumSidebarWindowComplete(owner.result.window, rows, accountId, serverId)).toBe(false)
expect(forumSidebarWindowComplete({ ...owner.result.window, parents: ["forum", "text"] }, rows, accountId, serverId)).toBe(true)
+ expect(forumSidebarWindowComplete({ ...owner.result.window, parents: ["forum", "text"] }, { ...rows, directory: owner.rows.directory }, accountId, serverId)).toBe(false)
})
it.each([false, true])("restores only a complete minimal %s window without entity copies or access proof", async empty => {
@@ -55,11 +60,11 @@ describe("scoped forum window persistence", () => {
expect(forumSidebarWindowComplete(readForumSidebarWindowResult(state.data)!.window, owner.rows, accountId, serverId)).toBe(true)
})
- it.each(["messages", "channelMemberships", "parent", "server", "detail"])("rejects a descriptor with missing %s before hydrate", async missing => {
+ it.each(["messages", "channelMemberships", "parent", "server", "directory"])("rejects a descriptor with missing %s before hydrate", async missing => {
const owner = setup()
if (missing === "parent") owner.client.setQueryData(communityKeys.communityDbCollection(accountId, "channels"), owner.rows.channels.filter(row => row.id !== "forum"))
else if (missing === "server") owner.client.setQueryData(communityKeys.communityDbCollection(accountId, "servers"), [])
- else if (missing === "detail") owner.client.setQueryData(communityKeys.communityDbCollection(accountId, "servers"), owner.rows.servers.map(row => ({ ...row, detailComplete: false })))
+ else if (missing === "directory") owner.client.removeQueries({ queryKey: communityKeys.server(serverId), exact: true })
else owner.client.setQueryData(communityKeys.communityDbCollection(accountId, missing), [])
const persister = createIdbPersister(accountId)
await persister.persistClient(owner.snapshot())
@@ -105,9 +110,9 @@ describe("scoped forum window persistence", () => {
it("checks a realtime visible child closure even when the last successful base was empty", async () => {
const owner = setup(true)
owner.client.setQueryData(communityKeys.communityDbCollection(accountId, "channels"), [
- ...owner.rows.channels, canonicalChannelRow({ id: "realtime-post", type: "thread", serverId, parentChannelId: "forum", parentMessageId: "missing-opener", lastMessageAt: new Date().toISOString() }),
+ ...owner.rows.channels, canonicalChannelRow(channelResourceFixture({ id: "realtime-post", type: "thread", serverId, parentChannelId: "forum", parentMessageId: "missing-opener", lastMessageAt: new Date().toISOString() })),
])
- owner.client.setQueryData(communityKeys.communityDbCollection(accountId, "channelMemberships"), [canonicalChannelMembershipRow("realtime-post", accountId, "notify")])
+ owner.client.setQueryData(communityKeys.communityDbCollection(accountId, "channelMemberships"), [canonicalChannelMembershipRow("realtime-post", accountId, "notify", { source: "spoke" })])
const persister = createIdbPersister(accountId)
await persister.persistClient(owner.snapshot())
expect((await persister.restoreClient())!.clientState.queries.some(query => JSON.stringify(query.queryKey) === JSON.stringify(key))).toBe(false)
diff --git a/src/web/src/lib/query-persister.old-owner.test.ts b/src/web/src/lib/query-persister.old-owner.test.ts
new file mode 100644
index 000000000..ecd76855f
--- /dev/null
+++ b/src/web/src/lib/query-persister.old-owner.test.ts
@@ -0,0 +1,184 @@
+import "fake-indexeddb/auto"
+import { createHash } from "node:crypto"
+import { readFileSync } from "node:fs"
+import * as ts from "typescript"
+import * as idb from "idb-keyval"
+import * as nativeStore from "@tanstack/store"
+import * as asyncPersister from "@tanstack/query-async-storage-persister"
+import { QueryClient, dehydrate } from "@tanstack/react-query"
+import type { PersistedClient } from "@tanstack/react-query-persist-client"
+import { describe, expect, it } from "vitest"
+import * as forum from "@/lib/community/forum-sidebar-window"
+import * as messages from "@/lib/community/models/message"
+import * as legacyCache from "@/lib/legacy-chat-persistence"
+import * as workerCache from "@/lib/service-worker/public-cache-storage"
+import * as restore from "@/lib/observability/restore"
+import * as lists from "@/lib/community/list-persistence"
+import * as schemas from "@/lib/community-db/schema"
+import { communityKeys } from "@/lib/query-keys"
+import { createIdbPersister, PERSIST_BUSTER, PERSIST_CACHE_PREFIX, PERSIST_VERSION, type QualifiedPersister } from "./query-persister"
+
+function oldDocument() {
+ const source = readFileSync(new URL("./test-fixtures/query-persister-07fa.ts.txt", import.meta.url), "utf8")
+ expect(createHash("sha256").update(source).digest("hex")).toBe("d1e237f2265acd04afa98d58f28b118930b76bfd7056382de40a8e4afe4672e6")
+ const modules: Record<string, unknown> = {
+ "idb-keyval": idb, "@tanstack/store": nativeStore,
+ "@tanstack/query-async-storage-persister": asyncPersister,
+ "@/lib/community/forum-sidebar-window": forum,
+ "@/lib/community/models/message": messages,
+ "@/lib/legacy-chat-persistence": legacyCache,
+ "@/lib/service-worker/public-cache-storage": workerCache,
+ "@/lib/observability/restore": restore,
+ "@/lib/community/list-persistence": lists,
+ "@/lib/community-db/schema": schemas,
+ }
+ const output = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
+ const exports: { createIdbPersister?: (userId: string) => QualifiedPersister; clearAllPersistedCaches?: () => Promise<void> } = {}
+ new Function("require", "exports", output)((name: string) => {
+ if (!(name in modules)) throw new Error(`Unexpected frozen source import: ${name}`)
+ return modules[name]
+ }, exports)
+ return exports as Required<typeof exports>
+}
+
+function snapshot(userId: string): PersistedClient {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.communityDbCollection(userId, "profiles"), [
+ { id: userId, name: "Current identity", discriminator: "1234", avatar: null, avatarVersion: 2 },
+ ])
+ const result = { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(queryClient) }
+ queryClient.clear()
+ return result
+}
+
+const key = (userId: string) => `${PERSIST_CACHE_PREFIX}:${userId}:client`
+
+describe("frozen 07fa document against current IDB owner", () => {
+ it("keeps current payload and qualification after actual old constructor reconstruction", async () => {
+ const userId = crypto.randomUUID()
+ const current = createIdbPersister(userId)
+ const value = snapshot(userId)
+ await current.persistClient(value)
+ const before = await idb.get(key(userId))
+ expect(before).toBeTypeOf("string")
+ const old = oldDocument().createIdbPersister(userId)
+ await old.restoreClient()
+ expect(await idb.get(key(userId))).toBe(before)
+ expect(await current.isCurrent()).toBe(true)
+ expect(await current.restoreClient()).toEqual(value)
+ })
+
+ it("executes old wrong-version deletion including its legacy-prefix scan without touching the current payload", async () => {
+ const userId = crypto.randomUUID()
+ const current = createIdbPersister(userId)
+ const value = snapshot(userId)
+ await current.persistClient(value)
+ const before = await idb.get(key(userId))
+ const oldKey = `alook:qc:cache:${userId}:client`
+ const scannedKey = `alook:qc:different:${userId}:client`
+ await idb.set(oldKey, before)
+ await idb.set(`${oldKey}:epoch`, { version: 7, epoch: crypto.randomUUID() })
+ await idb.set(scannedKey, "legacy scan control")
+ await oldDocument().createIdbPersister(userId).restoreClient()
+ expect(await idb.get(oldKey)).toBeUndefined()
+ expect(await idb.get(scannedKey)).toBeUndefined()
+ expect(await idb.get(key(userId))).toBe(before)
+ expect(await current.isCurrent()).toBe(true)
+ })
+
+ it("fences current owner on actual old account retirement", async () => {
+ const userId = crypto.randomUUID()
+ const current = createIdbPersister(userId)
+ await current.persistClient(snapshot(userId))
+ const old = oldDocument().createIdbPersister(userId)
+ await old.restoreClient()
+ await old.retireAccount()
+ expect(await current.isCurrent()).toBe(false)
+ expect(await current.restoreClient()).toBeUndefined()
+ expect(await createIdbPersister(userId).restoreClient()).toBeUndefined()
+ })
+
+ it("fences current owner on actual old device clear", async () => {
+ const userId = crypto.randomUUID()
+ const current = createIdbPersister(userId)
+ await current.persistClient(snapshot(userId))
+ await oldDocument().clearAllPersistedCaches()
+ expect(await current.isCurrent()).toBe(false)
+ expect(await current.restoreClient()).toBeUndefined()
+ expect(await createIdbPersister(userId).restoreClient()).toBeUndefined()
+ })
+
+ it("scrubs a retired channel after actual old channel retirement", async () => {
+ const userId = crypto.randomUUID()
+ const channelId = crypto.randomUUID()
+ const value = snapshot(userId)
+ const channel = schemas.canonicalChannelRow({ id: channelId, type: "dm", serverId: null, categoryId: null,
+ name: null, topic: "", parentChannelId: null, parentMessageId: null, creatorId: userId,
+ position: 0, archived: false, createdAt: "2026-10-28T00:00:00Z", lastMessageAt: null, messageCount: 0 })
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.communityDbCollection(userId, "channels"), [channel])
+ value.clientState.queries.push(...dehydrate(queryClient).queries)
+ queryClient.clear()
+ const current = createIdbPersister(userId)
+ await current.persistClient(value)
+ const old = oldDocument().createIdbPersister(userId)
+ await old.restoreClient()
+ await old.retireChannels([channelId], true)
+ expect(await current.isCurrent()).toBe(true)
+ const restored = await current.restoreClient()
+ expect(restored?.clientState.queries.find(query => query.queryKey[3] === "channels")?.state.data).toEqual([])
+ await current.persistClient(value)
+ expect((await current.restoreClient())?.clientState.queries.find(query => query.queryKey[3] === "channels")?.state.data).toEqual([])
+ })
+ it("fences the actual frozen old writer captured before current qualification", async () => {
+ const userId = crypto.randomUUID()
+ const old = oldDocument().createIdbPersister(userId)
+ const value = snapshot(userId)
+ await old.persistClient({ ...value, buster: "6" })
+ const oldKey = `alook:qc:cache:${userId}:client`
+ expect(await idb.get(oldKey)).toBeTypeOf("string")
+ const current = createIdbPersister(userId)
+ expect(await current.restoreClient()).toBeUndefined()
+ await current.persistClient(value)
+ expect(await old.isCurrent()).toBe(false)
+ await old.persistClient({ ...value, buster: "6", timestamp: 99 })
+ expect(await idb.get(oldKey)).toBeUndefined()
+ expect(await current.restoreClient()).toEqual(value)
+ })
+
+ it("cleans only this account's older business payloads and never restores their late recreation", async () => {
+ const userId = crypto.randomUUID(), otherId = crypto.randomUUID()
+ const current = createIdbPersister(userId), other = createIdbPersister(otherId)
+ const value = snapshot(userId), otherValue = snapshot(otherId)
+ await current.persistClient(value)
+ await other.persistClient(otherValue)
+ const before = await idb.get(key(userId)), otherBefore = await idb.get(key(otherId))
+ const futureKey = `alook:business:v${PERSIST_VERSION + 1}:${userId}:client`
+ const futureScope = { version: PERSIST_VERSION + 1, epoch: crypto.randomUUID() }
+ await idb.set(futureKey, "future-owned-payload")
+ await idb.set(`${futureKey}:epoch`, futureScope)
+ const oldKeys = ["", ":application"].map(domain => `alook:business:v${PERSIST_VERSION - 1}:${userId}${domain}:client`)
+ const epochs = oldKeys.map(() => ({ version: PERSIST_VERSION - 1, epoch: crypto.randomUUID() }))
+ for (const [index, oldKey] of oldKeys.entries()) {
+ await idb.set(oldKey, "older-owned-payload")
+ await idb.set(`${oldKey}:epoch`, epochs[index])
+ }
+ const fresh = createIdbPersister(userId)
+ expect(await fresh.restoreClient()).toEqual(value)
+ for (const [index, oldKey] of oldKeys.entries()) {
+ expect(await idb.get(oldKey)).toBeUndefined()
+ expect(await idb.get(`${oldKey}:epoch`)).not.toEqual(epochs[index])
+ await idb.set(oldKey, "late-older-recreation")
+ }
+ expect(await current.isCurrent()).toBe(true)
+ expect(await fresh.restoreClient()).toEqual(value)
+ expect(await idb.get(key(userId))).toBe(before)
+ expect(await idb.get(key(otherId))).toBe(otherBefore)
+ expect(await other.isCurrent()).toBe(true)
+ expect(await idb.get(futureKey)).toBe("future-owned-payload")
+ expect(await idb.get(`${futureKey}:epoch`)).toEqual(futureScope)
+ expect(await createIdbPersister(userId).restoreClient()).toEqual(value)
+ for (const oldKey of oldKeys) expect(await idb.get(oldKey)).toBeUndefined()
+ })
+
+})
diff --git a/src/web/src/lib/query-persister.race.test.ts b/src/web/src/lib/query-persister.race.test.ts
index 1bc17495b..c73464d08 100644
--- a/src/web/src/lib/query-persister.race.test.ts
+++ b/src/web/src/lib/query-persister.race.test.ts
@@ -1,3 +1,4 @@
+import { channelResourceFixture, messageResourceFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import { createStore, del, get, promisifyRequest, set } from "idb-keyval"
import { afterEach, describe, expect, it, vi } from "vitest"
@@ -7,7 +8,7 @@ import { canonicalChannelRow } from "@/lib/community-db/schema"
import type { PersistedClient } from "@tanstack/react-query-persist-client"
import { clearPersistedCache, createIdbPersister, PERSIST_BUSTER,
PERSIST_VERSION,
- PERSIST_CACHE_PREFIX, cacheInvalidation } from "./query-persister"
+ PERSIST_CACHE_PREFIX, PERSIST_ACCOUNT_PREFIX, cacheInvalidation } from "./query-persister"
const client: PersistedClient = {
timestamp: 1,
@@ -121,7 +122,7 @@ describe("native IDB persistence retirement", () => {
const user = "u_missing_account_epoch"
const stale = createIdbPersister(user)
await stale.restoreClient()
- await del(`${blobKey(user)}:epoch`)
+ await del(`${PERSIST_ACCOUNT_PREFIX}:${user}:account-epoch`)
await stale.persistClient(client)
expect(await get(blobKey(user))).toBeUndefined()
})
@@ -144,10 +145,10 @@ describe("qualified native owner disk retirement", () => {
function readingSnapshot(user: string): PersistedClient {
const queryClient = new QueryClient()
const setRows = (name: string, rows: unknown[]) => queryClient.setQueryData(communityKeys.communityDbCollection(user, name), rows)
- setRows("channels", ["dm-A", "dm-B"].map((id) => canonicalChannelRow({ id, type: "dm", name: id, preview: `body-${id}`, unread: true })))
+ setRows("channels", ["dm-A", "dm-B"].map((id) => canonicalChannelRow({ ...channelResourceFixture({ id, type: "dm", serverId: null, name: id }), preview: `body-${id}` })))
setRows("attentionScopes", ["dm-A", "dm-B"].map(channelId => ({ scopeId: channelId, channelId, serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 1, attentionCount: 0, lastAttentionSeq: null })))
- setRows("messages", ["dm-A", "dm-B"].map((channelId) => ({ id: `m-${channelId}`, channelId, type: "chat", resourceComplete: false, authorId: user, authorName: "Viewer", authorAvatar: "V", authorAvatarVersion: 0, seq: 1, content: `body-${channelId}` })))
- setRows("channelMemberships", ["dm-A", "dm-B"].map((channelId) => ({ id: `${channelId}:peer:access`, channelId, userId: "peer", relation: "access" })))
+ setRows("messages", ["dm-A", "dm-B"].map((channelId) => messageResourceFixture({ id: `m-${channelId}`, channelId, authorId: user, authorName: "Viewer", authorAvatar: "V", authorAvatarVersion: 0, seq: 1, content: `body-${channelId}` })))
+ setRows("channelMemberships", ["dm-A", "dm-B"].map((channelId) => ({ id: `${channelId}:peer:access`, channelId, userId: "peer", relation: "access", source: "added" })))
return { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(queryClient) }
}
function readingRows(snapshot: PersistedClient | undefined, name: string) {
@@ -157,7 +158,7 @@ function readingRows(snapshot: PersistedClient | undefined, name: string) {
describe("native channel persistence fence", () => {
it.each([
["account", false], ["account", true], ["channel", false], ["channel", true],
- ] as const)("retires existing v3 eligibility on %s retirement with payload=%s", async (kind, hasPayload) => {
+ ] as const)("retires existing v3 payload scopes on %s retirement with payload=%s", async (kind, hasPayload) => {
const user = `u_v3_qualified_${kind}_${hasPayload}`
await clearPersistedCache(user)
const owner = createIdbPersister(user)
@@ -178,7 +179,10 @@ describe("native channel persistence fence", () => {
if (!hasPayload) expect(await get(`${oldNamespace}:client`)).toBeUndefined()
if (kind === "account") await owner.retireAccount()
else await owner.retireChannels(["dm-A"])
- for (let i = 0; i < oldKeys.length; i++) expect(await get(oldKeys[i]!)).not.toBe(epochs[i])
+ for (let i = 0; i < oldKeys.length; i++) {
+ if (kind === "channel" && i === 0) expect(await get(oldKeys[i]!)).toBe(epochs[i])
+ else expect(await get(oldKeys[i]!)).not.toBe(epochs[i])
+ }
expect(await get(`${oldNamespace}:client`)).toBeUndefined()
expect(await get(otherKey)).toBe(otherEpoch)
expect(await get(unrelated)).toBe("keep")
@@ -357,7 +361,7 @@ describe("v6 community scope qualification", () => {
const user = `u_v6_scope_${hasPayload}`
const owner = createIdbPersister(user)
await owner.restoreClient()
- const namespace = `${PERSIST_CACHE_PREFIX}:${user}`
+ const namespace = `${PERSIST_ACCOUNT_PREFIX}:${user}`
const device = await get("alook:qc:device-epoch")
const account = await get(`${namespace}:account-epoch`)
const fences = new Map([["channel", { epoch: crypto.randomUUID(), deleted: true }]])
@@ -366,7 +370,7 @@ describe("v6 community scope qualification", () => {
await set(`${blobKey(user)}:epoch`, oldScope)
if (hasPayload) await set(blobKey(user), JSON.stringify({ ...client, version: 5, buster: "5", channelFences: [] }))
else await del(blobKey(user))
- const applicationKey = `${namespace}:application:client`
+ const applicationKey = `${PERSIST_CACHE_PREFIX}:${user}:application:client`
const applicationScope = crypto.randomUUID()
await set(applicationKey, "application payload")
await set(`${applicationKey}:epoch`, applicationScope)
@@ -409,7 +413,7 @@ describe("v6 community scope qualification", () => {
const fresh = createIdbPersister(user)
expect(await fresh.restoreClient()).toBeUndefined()
const qualified = await get<{ version: number; epoch: string }>(`${blobKey(user)}:epoch`)
- expect(qualified).toEqual({ version: 6, epoch: expect.any(String) })
+ expect(qualified).toEqual({ version: PERSIST_VERSION, epoch: expect.any(String) })
expect(qualified!.epoch).not.toBe(oldScope)
expect(await get("alook:qc:device-epoch")).toBe(device)
expect(await get(`${namespace}:account-epoch`)).toBe(account)
diff --git a/src/web/src/lib/query-persister.restore.test.ts b/src/web/src/lib/query-persister.restore.test.ts
index c5575ebf0..ddc0756d7 100644
--- a/src/web/src/lib/query-persister.restore.test.ts
+++ b/src/web/src/lib/query-persister.restore.test.ts
@@ -6,9 +6,9 @@ import { createCommunityRestorePersister, PERSIST_BUSTER, PERSIST_MAX_AGE_MS } f
function snapshot(): PersistedClient {
const client = new QueryClient()
- client.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [{ id: "peer", identityComplete: false, name: "Disk" }], { updatedAt: 0 })
+ client.setQueryData(communityKeys.communityDbCollection("viewer", "profiles"), [{ id: "peer", name: "Disk", discriminator: "0042", avatar: null, avatarVersion: 0 }], { updatedAt: 0 })
client.setQueryData(communityKeys.communityDbCollection("viewer", "messages"), [])
- client.setQueryData(communityKeys.communityDbCollection("other", "profiles"), [{ id: "private", identityComplete: false, name: "Other" }])
+ client.setQueryData(communityKeys.communityDbCollection("other", "profiles"), [{ id: "private", name: "Other", discriminator: "0042", avatar: null, avatarVersion: 0 }])
client.setQueryData(communityKeys.communityDbCollection("viewer", "folders"), [{ invalid: true }])
client.setQueryData(["resource-window"], { ids: ["id"] })
const value = { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(client) }
@@ -23,13 +23,13 @@ describe("community native restore input", () => {
const restore = createCommunityRestorePersister(original, "viewer")
const client = new QueryClient()
const profileKey = communityKeys.communityDbCollection("viewer", "profiles")
- client.setQueryData(profileKey, [{ id: "peer", identityComplete: false, name: "RSC" }])
+ client.setQueryData(profileKey, [{ id: "peer", name: "RSC", discriminator: "0042", avatar: null, avatarVersion: 0 }])
await persistQueryClientRestore({ queryClient: client, persister: restore.persister, buster: PERSIST_BUSTER, maxAge: PERSIST_MAX_AGE_MS })
- expect(client.getQueryData(profileKey)).toEqual([{ id: "peer", identityComplete: false, name: "RSC" }])
+ expect(client.getQueryData(profileKey)).toEqual([{ id: "peer", name: "RSC", discriminator: "0042", avatar: null, avatarVersion: 0 }])
expect(client.getQueryData(["resource-window"])).toEqual({ ids: ["id"] })
const input = restore.takeCollections()
expect(Object.keys(input).sort()).toEqual(["messages", "profiles"])
- expect(input.profiles).toEqual({ rows: [{ id: "peer", identityComplete: false, name: "Disk" }], updatedAt: 0 })
+ expect(input.profiles).toEqual({ rows: [{ id: "peer", name: "Disk", discriminator: "0042", avatar: null, avatarVersion: 0 }], updatedAt: 0 })
expect(input.messages?.rows).toEqual([])
expect(restore.takeCollections()).toEqual({})
await restore.persister.persistClient(disk)
diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.ts
index 05b02bebe..09b1321a4 100644
--- a/src/web/src/lib/query-persister.test.ts
+++ b/src/web/src/lib/query-persister.test.ts
@@ -1,3 +1,4 @@
+import { messageResourceFixture, serverResourceFixture } from "@/test/community-resource-fixtures"
import "fake-indexeddb/auto"
import { describe, expect, it, beforeEach } from "vitest"
import { del, get, set } from "idb-keyval"
@@ -41,7 +42,7 @@ describe("shouldPersistQueryKey", () => {
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)
+ expect(shouldPersistQueryKey(communityKeys.server("srv_1"))).toBe(true)
})
it("does NOT persist channel entry qualification", () => {
@@ -59,8 +60,8 @@ describe("shouldPersistQueryKey", () => {
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(shouldPersistQuery(communityKeys.server("__none__"), undefined)).toBe(false)
+ expect(shouldPersistQuery(communityKeys.server("__pending__"), undefined)).toBe(false)
expect(shouldPersistQueryKey(communityKeys.friends())).toBe(false)
expect(shouldPersistQueryKey(communityKeys.inbox())).toBe(false)
})
@@ -74,7 +75,7 @@ describe("shouldPersistQueryKey", () => {
expect(shouldPersistQueryKey(communityKeys.forumSidebarThreads("srv_1"))).toBe(true)
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(shouldPersistQuery(communityKeys.channelRefDirectory(), undefined)).toBe(false)
expect(shouldPersistQueryKey(communityKeys.presence("srv_1"))).toBe(false)
expect(shouldPersistQueryKey(
communityKeys.communityDbCollection("u_1", "channels"),
@@ -172,12 +173,20 @@ function validServerDetail(id = "srv_1") {
async function readPersistedBlob(userId: string | null): Promise<PersistedClient> {
const raw = await get<string>(
- `alook:qc:cache:${userId ?? "anon"}:client`,
+ `${PERSIST_CACHE_PREFIX}:${userId ?? "anon"}:client`,
)
if (!raw) throw new Error("no persisted blob")
return JSON.parse(raw) as PersistedClient
}
+async function injectQualifiedSnapshot(userId: string, snapshot: PersistedClient) {
+ const owner = createIdbPersister(userId)
+ await owner.persistClient({ ...snapshot, clientState: { mutations: [], queries: [] } })
+ const key = `${PERSIST_CACHE_PREFIX}:${userId}:client`
+ const current = JSON.parse((await get<string>(key))!)
+ await set(key, JSON.stringify({ ...current, ...snapshot }))
+}
+
describe("createIdbPersister — serialize filter", () => {
beforeEach(async () => {
await clearPersistedCache("u_1")
@@ -298,15 +307,15 @@ describe("createIdbPersister — serialize filter", () => {
expect(blob.clientState.queries.map((query) => query.queryKey)).toEqual([])
})
- it("round trips full nullable raw resources through qualified version 6", async () => {
+ it("round trips full nullable raw resources through qualified current version", async () => {
const qc = new QueryClient()
- const channel = canonicalChannelRow({ id: "dm_1", type: "dm", serverId: null, categoryId: null, name: null, topic: "Raw topic", parentChannelId: null, parentMessageId: null, creatorId: null, position: 0, archived: false, createdAt: "2026-10-11T00:00:00Z", lastMessageAt: null, messageCount: 1, resourceComplete: true })
- const message = { id: "raw", channelId: channel.id, seq: 1, type: "chat", authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 4, createdAt: channel.createdAt, content: "raw", replyToId: null, clientNonce: "nonce", resourceComplete: true,
+ const channel = canonicalChannelRow({ id: "dm_1", type: "dm", serverId: null, categoryId: null, name: null, topic: "Raw topic", parentChannelId: null, parentMessageId: null, creatorId: null, position: 0, archived: false, createdAt: "2026-10-11T00:00:00Z", lastMessageAt: null, messageCount: 1 })
+ const message = { id: "raw", channelId: channel.id, seq: 1, type: "chat", authorId: "peer", authorName: "Peer", authorAvatar: null, authorAvatarVersion: 4, createdAt: channel.createdAt, content: "raw", replyToId: null, clientNonce: "nonce",
attachments: [{ id: "second", name: "raw", url: "/raw", thumbnailUrl: null, contentType: null, sizeBytes: null, width: null, height: null }, { id: "first", name: "image", url: "/image", thumbnailUrl: null, contentType: "image/png", sizeBytes: 1024, width: 20, height: 30 }], embeds: [null, { unsupported: true }] }
const data: Record<string, unknown[]> = {
channels: [channel], messages: [message],
- profiles: [{ id: "peer", name: "Peer", discriminator: "0002", avatar: null, avatarVersion: 4, identityComplete: true }],
- channelMemberships: [{ id: "dm_1:u_1:access", channelId: "dm_1", userId: "u_1", relation: "access" }],
+ profiles: [{ id: "peer", name: "Peer", discriminator: "0002", avatar: null, avatarVersion: 4 }],
+ channelMemberships: [{ id: "dm_1:u_1:access", channelId: "dm_1", userId: "u_1", relation: "access", source: "explicit" }],
}
const keys = Object.entries(data).map(([name, rows]) => {
const key = communityKeys.communityDbCollection("u_1", name)
@@ -315,8 +324,8 @@ describe("createIdbPersister — serialize filter", () => {
})
const owner = createIdbPersister("u_1")
await owner.persistClient({ timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { mutations: [], queries: keys.map((queryKey) => ({ queryKey, queryHash: JSON.stringify(queryKey), state: qc.getQueryState(queryKey)! })) } })
- const raw = JSON.parse((await get<string>("alook:qc:cache:u_1:client"))!)
- expect(raw.version).toBe(6)
+ const raw = JSON.parse((await get<string>(`${PERSIST_CACHE_PREFIX}:u_1:client`))!)
+ expect(raw.version).toBe(PERSIST_VERSION)
const restored = await createIdbPersister("u_1").restoreClient()
const collection = (name: string) => restored!.clientState.queries.find((query) => query.queryKey[3] === name)!.state.data
expect(collection("channels")).toEqual([expect.objectContaining(channel)])
@@ -341,8 +350,8 @@ describe("createIdbPersister — serialize filter", () => {
creatorId: null,
position: 0,
archived: false,
+ topic: "", createdAt: "2026-09-01T00:00:00.000Z", messageCount: 0,
muted: false,
- unread: false,
tags: [],
pending: false,
lastMessageAt: null,
@@ -400,7 +409,7 @@ describe("createIdbPersister — serialize filter", () => {
},
)
const collectionData = {
- servers: Array.from({ length: 7 }, (_, index) => ({
+ servers: Array.from({ length: 7 }, (_, index) => serverResourceFixture({ position: index,
id: `srv_${index}`,
name: `Server ${index}`,
discriminator: "0001",
@@ -409,8 +418,6 @@ describe("createIdbPersister — serialize filter", () => {
icon: null,
official: false,
isOwner: false,
- unread: false,
- mentions: 0,
})),
channels: [...dmChannels, ...serverChannels],
categories: Array.from({ length: 7 }, (_, index) => ({
@@ -419,23 +426,23 @@ describe("createIdbPersister — serialize filter", () => {
name: "Channels",
position: 0,
private: false,
- pending: false,
+ creatorId: null, pending: false,
})),
- messages,
+ messages: messages.map(row => messageResourceFixture(row)),
profiles: [
...Array.from({ length: MAX_PERSISTED_MESSAGE_SCOPES + 2 }, (_, index) => ({
id: `author_${index}`,
name: `Author ${index}`,
discriminator: "0001",
avatar: "A",
- avatarVersion: 0, identityComplete: true,
+ avatarVersion: 0,
})),
...Array.from({ length: 7 }, (_, index) => ({
id: `owner_${index}`,
name: `Owner ${index}`,
discriminator: "0001",
avatar: "O",
- avatarVersion: 0, identityComplete: true,
+ avatarVersion: 0,
})),
...[
"approval_other", "approval_bot", "approval_waiting", "reply_author",
@@ -446,23 +453,23 @@ describe("createIdbPersister — serialize filter", () => {
name: userId,
discriminator: "0001",
avatar: "P",
- avatarVersion: 0, identityComplete: true,
+ avatarVersion: 0,
}),
),
- { id: "u_1", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 0, identityComplete: true },
- { id: "orphan", name: "Orphan", discriminator: "0001", avatar: "O", avatarVersion: 0, identityComplete: true },
+ { id: "u_1", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 0 },
+ { id: "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 },
+ { id: "srv_6:u_1", serverId: "srv_6", userId: "u_1", memberId: "member-viewer", role: "member", viewer: true },
+ { id: "srv_6:roster_only", serverId: "srv_6", userId: "roster_only", memberId: "member-roster", 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" },
+ { id: "dm_0:u_1:access", channelId: "dm_0", userId: "u_1", relation: "access", source: "explicit" },
+ { id: "dm_0:dm_peer:access", channelId: "dm_0", userId: "dm_peer", relation: "access", source: "added" },
+ { id: "dm_0:notify_only:notify", channelId: "dm_0", userId: "notify_only", relation: "notify", source: "spoke" },
+ { id: "ch_6:u_1:access", channelId: "ch_6", userId: "u_1", relation: "access", source: "explicit" },
+ { id: "ch_6:u_1:notify", channelId: "ch_6", userId: "u_1", relation: "notify", source: "spoke" },
+ { id: "ch_6:roster_only:access", channelId: "ch_6", userId: "roster_only", relation: "access", source: "explicit" },
],
readStates: [
{ channelId: "ch_0", lastReadMessageId: "old", lastReadAt: "2026-09-01T00:00:00.000Z", lastReadSeq: 1 },
@@ -521,7 +528,7 @@ describe("createIdbPersister — serialize filter", () => {
position: row.position,
}))).toEqual(Array.from({ length: 7 }, (_, index) => ({
id: `srv_${index}`,
- position: undefined,
+ position: index,
})))
expect((collection("channels") as Array<{ serverId: string | null }>).filter(
(row) => row.serverId !== null,
@@ -549,10 +556,10 @@ describe("createIdbPersister — serialize filter", () => {
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.objectContaining({ channelId: "dm_0", userId: "u_1", relation: "access", source: "explicit" }),
+ expect.objectContaining({ channelId: "dm_0", userId: "dm_peer", relation: "access", source: "added" }),
+ expect.objectContaining({ channelId: "ch_6", userId: "u_1", relation: "access", source: "explicit" }),
+ expect.objectContaining({ channelId: "ch_6", userId: "u_1", relation: "notify", source: "spoke" }),
]))
expect(collection("channelMemberships")).toHaveLength(4)
expect((collection("readStates") as Array<{ channelId: string }>).map((row) => row.channelId))
@@ -581,7 +588,7 @@ describe("createIdbPersister — serialize filter", () => {
})),
},
}
- await set("alook:qc:cache:u_1:client", JSON.stringify({ ...injected, version: PERSIST_VERSION, channelFences: [] }))
+ await injectQualifiedSnapshot("u_1", injected)
expect((await createIdbPersister("u_1").restoreClient())?.clientState.queries).toEqual([])
})
@@ -642,7 +649,7 @@ describe("createIdbPersister — serialize filter", () => {
}],
},
}
- await set("alook:qc:cache:u_1:client", JSON.stringify({ ...injected, version: PERSIST_VERSION, channelFences: [] }))
+ await injectQualifiedSnapshot("u_1", injected)
expect((await createIdbPersister("u_1").restoreClient())?.clientState.queries).toEqual([])
})
@@ -713,7 +720,7 @@ describe("createIdbPersister — user scoping", () => {
await clearPersistedCache("u_alice")
// Alice's blob is gone but Bob's is untouched.
- expect(await get(`alook:qc:cache:u_alice:client`)).toBeUndefined()
+ expect(await get(`${PERSIST_CACHE_PREFIX}:u_alice:client`)).toBeUndefined()
const bobBlob = await readPersistedBlob("u_bob")
expect(bobBlob.timestamp).toBe(2)
})
@@ -728,7 +735,7 @@ describe("createIdbPersister — user scoping", () => {
await persister.removeClient()
- expect(await get("alook:qc:cache:u_remove:client")).toBeUndefined()
+ expect(await get(`${PERSIST_CACHE_PREFIX}:u_remove:client`)).toBeUndefined()
})
it("blocks a delayed writer created before clear", async () => {
@@ -739,7 +746,7 @@ describe("createIdbPersister — user scoping", () => {
buster: PERSIST_BUSTER,
clientState: { mutations: [], queries: [] },
})
- expect(await get(`alook:qc:cache:u_alice:client`)).toBeUndefined()
+ expect(await get(`${PERSIST_CACHE_PREFIX}:u_alice:client`)).toBeUndefined()
})
})
@@ -755,7 +762,8 @@ describe("all-account persisted cache management", () => {
const persister = createIdbPersister("u-version-source")
const client = { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: { mutations: [], queries: [] } }
await persister.persistClient(client)
- expect(await get(`${PERSIST_CACHE_PREFIX}:u-version-source:client`)).toBe(JSON.stringify({ ...client, version: PERSIST_VERSION, channelFences: [] }))
+ const raw = JSON.parse((await get<string>(`${PERSIST_CACHE_PREFIX}:u-version-source:client`))!)
+ expect(raw).toEqual({ ...client, version: PERSIST_VERSION, ownerEpochs: { device: expect.any(String), account: expect.any(String) }, channelFences: [] })
await expect(persister.restoreClient()).resolves.toEqual(client)
})
diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.ts
index 958ed304d..4f3319836 100644
--- a/src/web/src/lib/query-persister.ts
+++ b/src/web/src/lib/query-persister.ts
@@ -1,3 +1,5 @@
+import { isServerDirectoryWindowKey, readServerDirectoryWindow, serverDirectoryWindowComplete, type ServerDirectoryWindow } from "@/lib/community/server-directory-window"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { forumSidebarWindowComplete, isForumSidebarWindowKey, readForumSidebarWindowResult } from "@/lib/community/forum-sidebar-window"
import { messageProfileIds, type Msg } from "@/lib/community/models/message"
import { clearLegacyChatCaches, getLegacyChatCacheSizeBytes } from "@/lib/legacy-chat-persistence"
@@ -17,9 +19,10 @@ import {
type CommunityCollectionRows,
} from "@/lib/community-db/schema"
-export const PERSIST_VERSION = 6
+export const PERSIST_VERSION = BUSINESS_SCHEMA_VERSION
export const PERSIST_BUSTER = String(PERSIST_VERSION)
-export const PERSIST_CACHE_PREFIX = "alook:qc:cache"
+export const PERSIST_CACHE_PREFIX = `alook:business:v${BUSINESS_SCHEMA_VERSION}`
+export const PERSIST_ACCOUNT_PREFIX = "alook:qc:cache"
const IDB_PREFIX = PERSIST_CACHE_PREFIX
/** Persister max-age; queries older than this are discarded on restore. */
@@ -40,7 +43,7 @@ function isCommunityDbCollectionKey(queryKey: readonly unknown[]): boolean {
}
export function shouldPersistQueryKey(queryKey: readonly unknown[]): boolean {
- return isCommunityDbCollectionKey(queryKey) || isCommunityListResourceKey(queryKey) || isForumSidebarWindowKey(queryKey)
+ return isCommunityDbCollectionKey(queryKey) || isCommunityListResourceKey(queryKey) || isForumSidebarWindowKey(queryKey) || isServerDirectoryWindowKey(queryKey)
}
export function shouldPersistQuery(
@@ -48,6 +51,7 @@ export function shouldPersistQuery(
data: unknown,
): boolean {
return isCommunityDbCollectionKey(queryKey) || persistentCommunityListResource(queryKey, data) !== undefined
+ || isServerDirectoryWindowKey(queryKey) && readServerDirectoryWindow(data)?.serverId === queryKey[2]
|| isForumSidebarWindowKey(queryKey) && readForumSidebarWindowResult(data)?.window.serverId === queryKey[2]
}
@@ -70,8 +74,7 @@ export function readCommunityRestoredCollections(snapshot: PersistedClient | und
if (!schema) continue
const parsed = schema.array().safeParse(query.state.data)
if (!parsed.success) continue
- const rows = name === "servers" ? parsed.data.map((row, position) => ({ ...row, position: (row as CommunityCollectionRows["servers"]).position ?? position })) : parsed.data
- Object.assign(collections, { [name]: { rows, updatedAt: query.state.dataUpdatedAt } })
+ Object.assign(collections, { [name]: { rows: parsed.data, updatedAt: query.state.dataUpdatedAt } })
}
return collections
}
@@ -231,6 +234,15 @@ function scrubDehydratedClient(
const data = windowed[collectionName]
if (data) queries.push({ ...q, state: { ...q.state, data } })
}
+ const qualifiedDirectories = new Map<string, ServerDirectoryWindow>()
+ for (const q of client.clientState.queries) {
+ if (!userId || !isServerDirectoryWindowKey(q.queryKey)) continue
+ const directory = readServerDirectoryWindow(q.state.data)
+ if (!directory || directory.serverId !== q.queryKey[2] || directory.channelIds.some(id => retired.has(id))
+ || !serverDirectoryWindowComplete(directory, { servers: rows("servers"), categories: rows("categories"), channels: retainedChannels }, userId, directory.serverId)) continue
+ qualifiedDirectories.set(directory.serverId, directory)
+ queries.push({ ...q, state: { ...q.state, data: directory } })
+ }
const retiredServerIds = new Set(rows("channels").filter(row => retired.has(row.id)).map(row => row.serverId))
for (const q of client.clientState.queries) {
if (!userId || !isForumSidebarWindowKey(q.queryKey)) continue
@@ -238,7 +250,7 @@ function scrubDehydratedClient(
if (!data || data.window.serverId !== q.queryKey[2] || retiredServerIds.has(data.window.serverId)
|| data.window.parents.some(id => retired.has(id))
|| [...data.window.base, ...(data.window.retained?.disposition === "eligible" ? [data.window.retained.reference] : [])].some(row => retired.has(row.id) || retired.has(row.parentChannelId))
- || !forumSidebarWindowComplete(data.window, { servers: rows("servers"), channels: retainedChannels, channelMemberships: retainedChannelMemberships, messages: retainedMessages }, userId, data.window.serverId, null, Date.now() + data.serverClockOffsetMs)) continue
+ || !forumSidebarWindowComplete(data.window, { directory: qualifiedDirectories.get(data.window.serverId), servers: rows("servers"), channels: retainedChannels, channelMemberships: retainedChannelMemberships, messages: retainedMessages }, userId, data.window.serverId, null, Date.now() + data.serverClockOffsetMs)) continue
queries.push({ ...q, state: { ...q.state, data, status: "success", error: null, errorUpdatedAt: 0,
errorUpdateCount: 0, isInvalidated: true, fetchFailureCount: 0, fetchFailureReason: null, fetchStatus: "idle", fetchMeta: null } })
}
@@ -267,7 +279,7 @@ function blobKeyFor(userId: string | null, domain: PersistDomain = "community"):
}
function isPersistedCacheBlobKey(key: IDBValidKey): key is string {
- return typeof key === "string" && /^alook:qc:[^:]+:[^:]+(?::application)?:client$/.test(key)
+ return typeof key === "string" && /^alook:(?:qc:[^:]+|business:v\d+):[^:]+(?::application)?:client$/.test(key)
}
export function formatBytes(bytes: number): string {
@@ -287,7 +299,7 @@ export function formatBytes(bytes: number): string {
const cacheStore = createStore("keyval-store", "keyval")
const DEVICE_EPOCH_KEY = "alook:qc:device-epoch"
const scopeEpochKey = (key: string) => `${key}:epoch`
-const accountEpochKey = (userId: string | null) => `${namespaceFor(userId)}:account-epoch`
+const accountEpochKey = (userId: string | null) => `${PERSIST_ACCOUNT_PREFIX}:${userId ?? "anon"}:account-epoch`
type ChannelDiskFence = { epoch: string; deleted: boolean }
type PersistEligibility = { device: string; scope: string; account: string; channels: Map<string, ChannelDiskFence> }
const channelFenceKey = (userId: string | null) => `${accountEpochKey(userId)}:channels`
@@ -301,11 +313,11 @@ function changedChannelFences(current: Map<string, ChannelDiskFence>, expected:
function decodeDiskSnapshot(raw: unknown) {
try {
if (typeof raw !== "string") return undefined
- const { version, channelFences, ...snapshot } = JSON.parse(raw) as PersistedClient & { version?: unknown; channelFences?: unknown }
- if (version !== PERSIST_VERSION || snapshot.buster !== PERSIST_BUSTER || !Array.isArray(channelFences)
+ const { version, channelFences, ownerEpochs, ...snapshot } = JSON.parse(raw) as PersistedClient & { version?: unknown; channelFences?: unknown; ownerEpochs?: { device?: unknown; account?: unknown } }
+ if (version !== PERSIST_VERSION || snapshot.buster !== PERSIST_BUSTER || !ownerEpochs || !isEpoch(ownerEpochs.device) || !isEpoch(ownerEpochs.account) || !Array.isArray(channelFences)
|| !channelFences.every((entry) => Array.isArray(entry) && entry.length === 2)) return undefined
const fences = new Map(channelFences)
- return isChannelFences(fences) ? { snapshot, fences } : undefined
+ return isChannelFences(fences) ? { snapshot, fences, ownerEpochs: { device: ownerEpochs.device, account: ownerEpochs.account } } : undefined
} catch { return undefined }
}
@@ -365,7 +377,7 @@ function qualifyPersister(key: string, userId: string | null, captureSnapshot: (
const channels = intact ? current.channels as Map<string, ChannelDiskFence> : new Map<string, ChannelDiskFence>()
const currentScope = communityScopeEpoch(current.scope)
const decoded = decodeDiskSnapshot(raw)
- const compatiblePayload = raw === undefined || Boolean(decoded)
+ const compatiblePayload = raw === undefined || Boolean(decoded && decoded.ownerEpochs.device === device && decoded.ownerEpochs.account === account)
let scope = currentScope && compatiblePayload ? currentScope : crypto.randomUUID()
if (!intact) {
for (const domain of ["community", "application"] as const) {
@@ -381,7 +393,7 @@ function qualifyPersister(key: string, userId: string | null, captureSnapshot: (
if (!isEpoch(current.device) || !currentScope || !compatiblePayload) store.delete(key)
if (!isEpoch(current.device)) store.put(device, DEVICE_EPOCH_KEY)
store.put({ version: PERSIST_VERSION, epoch: scope }, scopeEpochKey(key))
- if (intact && isEpoch(current.device) && currentScope && decoded && typeof raw === "string") captureSnapshot(raw, decoded)
+ if (intact && isEpoch(current.device) && currentScope && compatiblePayload && decoded && typeof raw === "string") captureSnapshot(raw, decoded)
return { device, scope, account, channels }
})
}
@@ -418,7 +430,8 @@ export function createIdbPersister(userId: string | null): QualifiedPersister {
setItem: (_k: string, value: string) => withEligiblePersister(
key, userId, eligibility, "readwrite", undefined, async (store, current, expected) => {
const snapshot = scrubDehydratedClient(JSON.parse(value) as PersistedClient, userId, changedChannelFences(current, expected))
- store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, channelFences: [...current] }), key)
+ const { device, account } = await eligibility
+ store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, ownerEpochs: { device, account }, channelFences: [...current] }), key)
},
),
// Expiry/buster removal removes only this payload. It does not retire
@@ -438,7 +451,8 @@ export function createIdbPersister(userId: string | null): QualifiedPersister {
const raw = await promisifyRequest<unknown>(store.get(key))
const decoded = initialSnapshot && initialSnapshot.raw === raw ? initialSnapshot.decoded : decodeDiskSnapshot(raw)
discardInitialSnapshot()
- if (!decoded) { store.delete(key); return undefined }
+ const expected = await eligibility
+ if (!decoded || decoded.ownerEpochs.device !== expected.device || decoded.ownerEpochs.account !== expected.account) { store.delete(key); return undefined }
return { ...decoded, retired: changedChannelFences(current, decoded.fences) }
}), persister)
return input && observeRestoreDecode(persister, () => scrubDehydratedClient(input.snapshot, userId, input.retired), PERSIST_BUSTER, PERSIST_MAX_AGE_MS)
@@ -476,11 +490,16 @@ async function clearAccountRows(store: IDBObjectStore, userId: string | null, le
request.onsuccess = () => {
const cursor = request.result
if (!cursor) { resolve(); return }
- const match = typeof cursor.key === "string" && /^(alook:qc:[^:]+):([^:]+):((?:application:)?client(?::epoch)?|account-epoch(?::channels)?)$/.exec(cursor.key)
- if (match && match[2] === (userId ?? "anon") && (!legacyOnly || match[1] !== IDB_PREFIX)) {
- if (match[3] === "account-epoch:channels") store.put(new Map(), cursor.key)
- else if (match[3]?.endsWith("epoch")) store.put(crypto.randomUUID(), cursor.key)
- else store.delete(cursor.key)
+ const match = typeof cursor.key === "string" && /^(alook:(?:qc:[^:]+|business:v[1-9]\d*)):([^:]+):((?:application:)?client(?::epoch)?|account-epoch(?::channels)?)$/.exec(cursor.key)
+ if (match && match[2] === (userId ?? "anon")) {
+ const version = /^alook:(?:business|qc):v([1-9]\d*)$/.exec(match[1])
+ const older = match[1] === PERSIST_ACCOUNT_PREFIX || Boolean(version && Number.isSafeInteger(Number(version[1])) && Number(version[1]) < PERSIST_VERSION)
+ const payload = match[3].startsWith("client") || match[3].startsWith("application:client")
+ if (legacyOnly ? older && payload : older || match[1] === IDB_PREFIX) {
+ if (match[3] === "account-epoch:channels") store.put(new Map(), cursor.key)
+ else if (match[3].endsWith("epoch")) store.put(crypto.randomUUID(), cursor.key)
+ else store.delete(cursor.key)
+ }
}
cursor.continue()
}
@@ -497,7 +516,7 @@ async function retireChannelRows(store: IDBObjectStore, key: string, userId: str
const decoded = decodeDiskSnapshot(await promisifyRequest<unknown>(store.get(key)))
if (decoded) {
const snapshot = scrubDehydratedClient(decoded.snapshot, userId, changedChannelFences(fences, decoded.fences))
- store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, channelFences: [...fences] }), key)
+ store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, ownerEpochs: decoded.ownerEpochs, channelFences: [...fences] }), key)
} else store.delete(key)
}
diff --git a/src/web/src/lib/service-worker/business-upgrade.test.ts b/src/web/src/lib/service-worker/business-upgrade.test.ts
new file mode 100644
index 000000000..92710d4fb
--- /dev/null
+++ b/src/web/src/lib/service-worker/business-upgrade.test.ts
@@ -0,0 +1,95 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
+import { businessDocumentVersionBootstrapScript, businessUpdateUrl, probeBusinessVersion, upgradeBusinessWindow } from "./business-upgrade"
+
+afterEach(() => vi.useRealTimers())
+
+function client(version?: number, url = "https://alook.test/c/me") {
+ return {
+ url,
+ navigate: vi.fn().mockResolvedValue({}),
+ postMessage: vi.fn((_message: unknown, ports: MessagePort[]) => {
+ if (version !== undefined) ports[0].postMessage({ schemaVersion: version })
+ }),
+ } as unknown as WindowClient
+}
+
+describe("business document replacement", () => {
+ it.each(["before-probe", "queued-before-bootstrap"])("keeps the current document with its actual bootstrap %s", async timing => {
+ const container = new EventTarget()
+ const pending: MessageEvent[] = []
+ let started = false
+ const startMessages = vi.fn(() => {
+ started = true
+ for (const event of pending.splice(0)) container.dispatchEvent(event)
+ })
+ const navigator = { serviceWorker: Object.assign(container, { startMessages }) }
+ const install = () => new Function("navigator", businessDocumentVersionBootstrapScript)(navigator)
+ const target = {
+ url: "https://alook.test/c/me", navigate: vi.fn().mockResolvedValue({}),
+ postMessage: (data: unknown, ports: MessagePort[]) => {
+ const event = new MessageEvent("message", { data, ports })
+ if (started) container.dispatchEvent(event)
+ else pending.push(event)
+ },
+ } as unknown as WindowClient
+ if (timing === "before-probe") install()
+ const upgrading = upgradeBusinessWindow(target, "https://alook.test")
+ if (timing === "queued-before-bootstrap") {
+ expect(pending).toHaveLength(1)
+ install()
+ }
+ expect(await upgrading).toBe(false)
+ expect(startMessages).toHaveBeenCalledOnce()
+ expect(target.navigate).not.toHaveBeenCalled()
+ })
+
+ it("keeps a document that actually confirms the current compiled version", async () => {
+ const current = client(BUSINESS_SCHEMA_VERSION)
+ expect(await upgradeBusinessWindow(current, "https://alook.test")).toBe(false)
+ expect(current.postMessage).toHaveBeenCalledTimes(1)
+ expect(current.navigate).not.toHaveBeenCalled()
+ })
+
+ it("replaces a mismatched document and carries its version attempt marker", async () => {
+ const old = client(BUSINESS_SCHEMA_VERSION - 1)
+ expect(await upgradeBusinessWindow(old, "https://alook.test")).toBe(true)
+ expect(old.navigate).toHaveBeenCalledWith(`https://alook.test/c/me?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}`)
+ })
+
+ it("bounds a missing old-page listener and replaces that document once", async () => {
+ vi.useFakeTimers()
+ const old = client()
+ const upgrade = upgradeBusinessWindow(old, "https://alook.test")
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(await upgrade).toBe(true)
+ const attempted = client(undefined, `https://alook.test/c/me?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}`)
+ const again = upgradeBusinessWindow(attempted, "https://alook.test")
+ await vi.advanceTimersByTimeAsync(1500)
+ expect(await again).toBe(false)
+ expect(attempted.navigate).not.toHaveBeenCalled()
+ })
+
+ it("updates the actual public invite entry without routing it through a private shell", async () => {
+ const page = client(BUSINESS_SCHEMA_VERSION - 1, "https://alook.test/c/invite/token")
+ expect(await upgradeBusinessWindow(page, "https://alook.test")).toBe(true)
+ expect(page.navigate).toHaveBeenCalledWith(`https://alook.test/c/invite/token?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}`)
+ const attempted = client(BUSINESS_SCHEMA_VERSION, `https://alook.test/c/invite/token?__alook_schema_update=${BUSINESS_SCHEMA_VERSION}`)
+ expect(await upgradeBusinessWindow(attempted, "https://alook.test", true, true)).toBe(true)
+ })
+
+ it("does not navigate another origin or a public page", async () => {
+ for (const url of ["https://other.test/c/me", "https://alook.test/sign-in"]) {
+ const page = client(undefined, url)
+ expect(await upgradeBusinessWindow(page, "https://alook.test", true)).toBe(false)
+ expect(page.postMessage).not.toHaveBeenCalled()
+ expect(page.navigate).not.toHaveBeenCalled()
+ }
+ expect(businessUpdateUrl("https://alook.test/", BUSINESS_SCHEMA_VERSION)).toBeNull()
+ })
+
+ it("treats an invalid reply as missing version without accepting a shape", async () => {
+ const target = { postMessage: (_message: unknown, ports: Transferable[]) => (ports[0] as MessagePort).postMessage({ schemaVersion: "old" }) }
+ expect(await probeBusinessVersion(target, "probe")).toBeNull()
+ })
+})
diff --git a/src/web/src/lib/service-worker/business-upgrade.ts b/src/web/src/lib/service-worker/business-upgrade.ts
new file mode 100644
index 000000000..4d7c93fad
--- /dev/null
+++ b/src/web/src/lib/service-worker/business-upgrade.ts
@@ -0,0 +1,60 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared/business-schema-version"
+import { resolveCommunityModulePlan } from "../community/community-route"
+import { isCommunityApplicationPath } from "../community/application-route"
+
+export const BUSINESS_UPDATE_MARKER = "__alook_schema_update"
+export const DOCUMENT_VERSION_PROBE = "alook:document-version"
+export const WORKER_VERSION_PROBE = "alook:worker-version"
+export const CURRENT_DOCUMENT_REQUEST = "alook:current-document"
+
+export const businessDocumentVersionBootstrapScript = `
+try {
+ if ("serviceWorker" in navigator) {
+ const container = navigator.serviceWorker;
+ container.addEventListener("message", (event) => {
+ if (event.data?.type === ${JSON.stringify(DOCUMENT_VERSION_PROBE)}) {
+ event.ports[0]?.postMessage({ schemaVersion: ${BUSINESS_SCHEMA_VERSION} });
+ }
+ });
+ container.startMessages();
+ }
+} catch {}
+`
+
+type MessageTarget = { postMessage(message: unknown, transfer: Transferable[]): void }
+
+export function probeBusinessVersion(target: MessageTarget, type: string, timeout = 1500): Promise<number | null> {
+ return new Promise(resolve => {
+ const channel = new MessageChannel()
+ const finish = (version: number | null) => {
+ clearTimeout(timer)
+ channel.port1.close()
+ channel.port2.close()
+ resolve(version)
+ }
+ const timer = setTimeout(() => finish(null), timeout)
+ channel.port1.onmessage = event => finish(Number.isSafeInteger(event.data?.schemaVersion) ? event.data.schemaVersion : null)
+ try { target.postMessage({ type }, [channel.port2]) } catch { finish(null) }
+ })
+}
+
+function isBusinessDocumentPath(pathname: string) {
+ return isCommunityApplicationPath(pathname) || resolveCommunityModulePlan(pathname).route === "public-invite"
+}
+
+export function businessUpdateUrl(href: string, version: number): string | null {
+ const url = new URL(href)
+ if (!isBusinessDocumentPath(url.pathname) || url.searchParams.get(BUSINESS_UPDATE_MARKER) === String(version)) return null
+ url.searchParams.set(BUSINESS_UPDATE_MARKER, String(version))
+ return url.href
+}
+
+export async function upgradeBusinessWindow(client: MessageTarget & { url: string; navigate(url: string): Promise<unknown> }, origin: string, force = false, explicitRetry = false): Promise<boolean> {
+ const url = new URL(client.url)
+ if (url.origin !== origin || !isBusinessDocumentPath(url.pathname)) return false
+ if (!force && await probeBusinessVersion(client, DOCUMENT_VERSION_PROBE) === BUSINESS_SCHEMA_VERSION) return false
+ if (explicitRetry) url.searchParams.delete(BUSINESS_UPDATE_MARKER)
+ const next = businessUpdateUrl(url.href, BUSINESS_SCHEMA_VERSION)
+ if (!next) return false
+ return Boolean(await client.navigate(next))
+}
diff --git a/src/web/src/lib/services/task-payload-builder.test.ts b/src/web/src/lib/services/task-payload-builder.test.ts
index 26ba08e6c..8d77e6eea 100644
--- a/src/web/src/lib/services/task-payload-builder.test.ts
+++ b/src/web/src/lib/services/task-payload-builder.test.ts
@@ -202,3 +202,21 @@ describe("TaskPayloadBuilder", () => {
expect(mockGetMemberByUserAndWorkspace).toHaveBeenCalledTimes(1);
});
});
+
+it.each(["same", "foreign", "missing"])("binds the actual task sender identity cache loader to its requested user: %s", async mode => {
+ const { cached } = await import("@/lib/cache")
+ const mock = vi.mocked(cached)
+ const previous = mock.getMockImplementation()
+ mock.mockImplementation(async (_key, _ttl, load, schema) => schema.parse(await load()))
+ mockGetAllAgentsForWorkspace.mockResolvedValue([])
+ mockGetAllEmailAccountsForWorkspace.mockResolvedValue([])
+ mockGetAllColleaguesForWorkspace.mockResolvedValue([])
+ mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "sender1", channel: "slack" }])
+ mockGetUser.mockResolvedValue(mode === "missing" ? null : { id: mode === "same" ? "sender1" : "foreign", name: "Sender", email: "[email protected]" })
+ try {
+ const operation = new TaskPayloadBuilder({} as never).buildFullPayloads([makeTask({ type: "user_dm_message" })], "w1")
+ if (mode === "foreign") await expect(operation).rejects.toThrow()
+ else expect((await operation)[0]!.sender).toEqual(mode === "missing" ? null : { name: "Sender", email: "[email protected]", is_owner: false })
+ expect(mockGetUser).toHaveBeenLastCalledWith({}, "sender1")
+ } finally { if (previous) mock.mockImplementation(previous) }
+})
diff --git a/src/web/src/lib/services/task-payload-builder.ts b/src/web/src/lib/services/task-payload-builder.ts
index 1362fe131..fab7adf35 100644
--- a/src/web/src/lib/services/task-payload-builder.ts
+++ b/src/web/src/lib/services/task-payload-builder.ts
@@ -1,5 +1,5 @@
import type { Database, ClaimedTaskRow } from "@alook/shared";
-import { queries, TASK_TYPES, toAlookAddress } from "@alook/shared";
+import { queries, TASK_TYPES, toAlookAddress, TaskEmailAddressCacheSchema, TaskMemberInstructionCacheSchema, TaskUserIdentityCacheSchema } from "@alook/shared";
import { taskToResponse } from "@/lib/api/responses";
import { cached, cacheKeys } from "@/lib/cache";
@@ -13,7 +13,7 @@ export class TaskPayloadBuilder {
const [allAgents, allEmailAccounts, allColleagues] = agentIds.length > 0
? await Promise.all([
queries.agent.getAllAgentsForWorkspace(this.db, workspaceId),
- cached(cacheKeys.allEmailAccounts(workspaceId), 600, () => queries.emailAccount.getAllEmailAccountsForWorkspace(this.db, workspaceId)),
+ cached(cacheKeys.allEmailAccounts(workspaceId), 600, async () => (await queries.emailAccount.getAllEmailAccountsForWorkspace(this.db, workspaceId)).map(({ workspaceId, agentId, emailAddress }) => ({ workspaceId, agentId, emailAddress })), TaskEmailAddressCacheSchema.refine(rows => rows.every(row => row.workspaceId === workspaceId))),
queries.agentLink.getAllColleaguesForWorkspace(this.db, workspaceId).catch(() => [] as Awaited<ReturnType<typeof queries.agentLink.getAllColleaguesForWorkspace>>),
]).then(([agents, emails, colleagues]) => {
const agentIdSet = new Set(agentIds);
@@ -69,7 +69,11 @@ export class TaskPayloadBuilder {
const m = await cached(
cacheKeys.member(workspaceId, agent.ownerId),
600,
- () => queries.member.getMemberByUserAndWorkspace(this.db, agent.ownerId!, workspaceId),
+ async () => {
+ const row = await queries.member.getMemberByUserAndWorkspace(this.db, agent.ownerId!, workspaceId);
+ return row ? { workspaceId: row.workspaceId, userId: row.userId, globalInstruction: row.globalInstruction } : null;
+ },
+ TaskMemberInstructionCacheSchema.refine(row => row === null || row.workspaceId === workspaceId && row.userId === agent.ownerId),
);
memberCache.set(agent.ownerId, m ? { globalInstruction: m.globalInstruction } : null);
}
@@ -85,7 +89,11 @@ export class TaskPayloadBuilder {
const u = await cached(
cacheKeys.user(agent.ownerId),
1800,
- () => queries.user.getUserSelf(this.db, agent.ownerId!),
+ async () => {
+ const row = await queries.user.getUserSelf(this.db, agent.ownerId!);
+ return row ? { id: row.id, name: row.name, email: row.email } : null;
+ },
+ TaskUserIdentityCacheSchema.refine(row => row === null || row.id === agent.ownerId),
);
userCache.set(agent.ownerId, u ? { name: u.name, email: u.email } : null);
}
@@ -101,7 +109,11 @@ export class TaskPayloadBuilder {
const u = await cached(
cacheKeys.user(convo.userId),
1800,
- () => queries.user.getUserSelf(this.db, convo!.userId!),
+ async () => {
+ const row = await queries.user.getUserSelf(this.db, convo!.userId!);
+ return row ? { id: row.id, name: row.name, email: row.email } : null;
+ },
+ TaskUserIdentityCacheSchema.refine(row => row === null || row.id === convo!.userId),
);
userCache.set(convo.userId, u ? { name: u.name, email: u.email } : null);
}
diff --git a/src/web/src/lib/test-fixtures/query-persister-07fa.ts.txt b/src/web/src/lib/test-fixtures/query-persister-07fa.ts.txt
new file mode 100644
index 000000000..958ed304d
--- /dev/null
+++ b/src/web/src/lib/test-fixtures/query-persister-07fa.ts.txt
@@ -0,0 +1,549 @@
+import { forumSidebarWindowComplete, isForumSidebarWindowKey, readForumSidebarWindowResult } from "@/lib/community/forum-sidebar-window"
+import { messageProfileIds, type Msg } from "@/lib/community/models/message"
+import { clearLegacyChatCaches, getLegacyChatCacheSizeBytes } from "@/lib/legacy-chat-persistence"
+import { clearPublicWorkerCaches, getPublicWorkerCacheSizeBytes } from "@/lib/service-worker/public-cache-storage"
+import { observeRestoreRead, observeRestoreDecode } from "@/lib/observability/restore"
+import { createStore as createNativeStore } from "@tanstack/store"
+import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"
+import type {
+ PersistedClient,
+ Persister,
+} from "@tanstack/react-query-persist-client"
+import { createStore, get, promisifyRequest } from "idb-keyval"
+import { isCommunityListResourceKey, persistentCommunityListResource } from "@/lib/community/list-persistence"
+import {
+ communityCollectionSchemas,
+ type CommunityCollectionName,
+ type CommunityCollectionRows,
+} from "@/lib/community-db/schema"
+
+export const PERSIST_VERSION = 6
+export const PERSIST_BUSTER = String(PERSIST_VERSION)
+export const PERSIST_CACHE_PREFIX = "alook:qc:cache"
+const IDB_PREFIX = PERSIST_CACHE_PREFIX
+
+/** Persister max-age; queries older than this are discarded on restore. */
+export const PERSIST_MAX_AGE_MS = 24 * 60 * 60 * 1000
+
+export const MAX_PERSISTED_MESSAGE_SCOPES = 20
+export const MAX_PERSISTED_MESSAGES_PER_SCOPE = 50
+const MAX_PERSISTED_ATTENTION_ITEMS = 200
+
+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 {
+ return isCommunityDbCollectionKey(queryKey) || isCommunityListResourceKey(queryKey) || isForumSidebarWindowKey(queryKey)
+}
+
+export function shouldPersistQuery(
+ queryKey: readonly unknown[],
+ data: unknown,
+): boolean {
+ return isCommunityDbCollectionKey(queryKey) || persistentCommunityListResource(queryKey, data) !== undefined
+ || isForumSidebarWindowKey(queryKey) && readForumSidebarWindowResult(data)?.window.serverId === queryKey[2]
+}
+
+export function shouldDehydrateCommunityQuery(query: { queryKey: readonly unknown[]; state: { status: string; data: unknown } }) {
+ return (query.state.status === "success" || isForumSidebarWindowKey(query.queryKey))
+ && shouldPersistQuery(query.queryKey, query.state.data)
+}
+
+export type CommunityRestoredCollections = Partial<{
+ [N in CommunityCollectionName]: { rows: CommunityCollectionRows[N][]; updatedAt: number }
+}>
+
+export function readCommunityRestoredCollections(snapshot: PersistedClient | undefined, userId: string | null): CommunityRestoredCollections {
+ const collections: CommunityRestoredCollections = {}
+ if (!userId || !snapshot) return collections
+ for (const query of snapshot.clientState.queries) {
+ if (!isCommunityDbCollectionKey(query.queryKey) || query.queryKey[2] !== userId) continue
+ const name = query.queryKey[3] as CommunityCollectionName
+ const schema = communityCollectionSchemas[name]
+ if (!schema) continue
+ const parsed = schema.array().safeParse(query.state.data)
+ if (!parsed.success) continue
+ const rows = name === "servers" ? parsed.data.map((row, position) => ({ ...row, position: (row as CommunityCollectionRows["servers"]).position ?? position })) : parsed.data
+ Object.assign(collections, { [name]: { rows, updatedAt: query.state.dataUpdatedAt } })
+ }
+ return collections
+}
+
+export function createCommunityRestorePersister(original: Persister, userId: string | null) {
+ let collections: CommunityRestoredCollections = {}
+ const takeCollections = () => {
+ const input = collections
+ collections = {}
+ return input
+ }
+ const persister: Persister = {
+ persistClient: (client) => original.persistClient(client),
+ restoreClient: async () => {
+ collections = {}
+ const restored = await original.restoreClient()
+ collections = readCommunityRestoredCollections(restored, userId)
+ return restored && { ...restored, clientState: {
+ ...restored.clientState,
+ queries: restored.clientState.queries.filter((query) => !isCommunityDbCollectionKey(query.queryKey)),
+ } }
+ },
+ removeClient: () => { collections = {}; return original.removeClient() },
+ }
+ return { persister, takeCollections }
+}
+
+/**
+ * Retain the bounded canonical read closure without mutating the live cache.
+ */
+function scrubDehydratedClient(
+ client: PersistedClient,
+ userId: string | null,
+ retired: ReadonlyMap<string, ChannelDiskFence> = new Map(),
+): PersistedClient {
+ const queries: typeof client.clientState.queries = []
+ const canonical = new Map<CommunityCollectionName, unknown[]>()
+ for (const q of client.clientState.queries) {
+ if (userId) {
+ const data = persistentCommunityListResource(q.queryKey, q.state.data)
+ if (data) queries.push({ ...q, state: { ...q.state, data } })
+ }
+ 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
+ }
+ }
+
+ const rows = <N extends CommunityCollectionName>(name: N) => (canonical.get(name) ?? []) as CommunityCollectionRows[N][]
+ const retainedServerIds = new Set(rows("servers").map((row) => row.id))
+ const channels = rows("channels").flatMap((row) => {
+ const fence = retired.get(row.id)
+ if (!fence) return [row]
+ return row.type === "dm" && !fence.deleted
+ ? [{ ...row, preview: "" }]
+ : []
+ })
+ const attentionScopes = rows("attentionScopes").filter((row) => !retired.has(row.channelId))
+ const attentionCandidates = rows("attentionItems").filter((row) => !Boolean(row.scopeId && retired.has(row.scopeId) || row.childChannelId && retired.has(row.childChannelId) || row.readTarget && retired.has(row.readTarget.channelId)))
+ const retainedAttentionItems = [
+ ...attentionCandidates.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),
+ ...attentionCandidates.filter((item) => item.kind === "friend_request"),
+ ]
+ 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 = (rows("messages") as Array<CommunityCollectionRows["messages"] & Pick<Msg, "replyTo" | "thread" | "approval">>)
+ .filter((row) => !retired.has(row.channelId))
+ 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 retainedServerMemberships = rows("serverMemberships").filter((row) => row.viewer)
+ const channelMemberships = rows("channelMemberships")
+ 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 query of queries) if (query.queryKey[1] === "bots") {
+ for (const bot of (query.state.data as { bots: Array<{ id: string }> }).bots) referencedProfileIds.add(bot.id)
+ }
+ for (const server of rows("servers")) {
+ 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) {
+ for (const id of messageProfileIds(message)) referencedProfileIds.add(id)
+ }
+ for (const item of retainedAttentionItems) if (item.actorUserId) referencedProfileIds.add(item.actorUserId)
+
+ const windowed: Partial<Record<CommunityCollectionName, unknown[]>> = {
+ ...Object.fromEntries(canonical),
+ categories: rows("categories").filter(
+ (row) => retainedServerIds.has(row.serverId),
+ ),
+ channels: retainedChannels,
+ serverMemberships: retainedServerMemberships,
+ channelMemberships: retainedChannelMemberships,
+ messages: retainedMessages,
+ readStates: rows("readStates").filter((row) => !retired.has(row.channelId)),
+ notificationSettings: rows("notificationSettings").filter((row) => !row.channelId || !retired.has(row.channelId)),
+ attentionScopes,
+ attentionItems: retainedAttentionItems,
+ profiles: rows("profiles").filter(
+ (row) => referencedProfileIds.has(row.id),
+ ),
+ }
+ 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 } })
+ }
+ const retiredServerIds = new Set(rows("channels").filter(row => retired.has(row.id)).map(row => row.serverId))
+ for (const q of client.clientState.queries) {
+ if (!userId || !isForumSidebarWindowKey(q.queryKey)) continue
+ const data = readForumSidebarWindowResult(q.state.data)
+ if (!data || data.window.serverId !== q.queryKey[2] || retiredServerIds.has(data.window.serverId)
+ || data.window.parents.some(id => retired.has(id))
+ || [...data.window.base, ...(data.window.retained?.disposition === "eligible" ? [data.window.retained.reference] : [])].some(row => retired.has(row.id) || retired.has(row.parentChannelId))
+ || !forumSidebarWindowComplete(data.window, { servers: rows("servers"), channels: retainedChannels, channelMemberships: retainedChannelMemberships, messages: retainedMessages }, userId, data.window.serverId, null, Date.now() + data.serverClockOffsetMs)) continue
+ queries.push({ ...q, state: { ...q.state, data, status: "success", error: null, errorUpdatedAt: 0,
+ errorUpdateCount: 0, isInvalidated: true, fetchFailureCount: 0, fetchFailureReason: null, fetchStatus: "idle", fetchMeta: null } })
+ }
+ return {
+ ...client,
+ clientState: { ...client.clientState, queries },
+ }
+}
+
+/** IDB key namespace for a given user. `null` = pre-auth or logged out. */
+function namespaceFor(userId: string | null): string {
+ return `${IDB_PREFIX}:${userId ?? "anon"}`
+}
+
+/** Storage sub-key for the persister blob within a user's namespace. */
+type PersistDomain = "community" | "application"
+export const CACHE_INVALIDATION_STORAGE_KEY = "alook:qc:invalidation"
+export const cacheInvalidation = createNativeStore(0)
+function publishCacheInvalidation() {
+ cacheInvalidation.setState((version) => version + 1)
+ try { if (typeof localStorage !== "undefined") localStorage.setItem(CACHE_INVALIDATION_STORAGE_KEY, crypto.randomUUID()) } catch {}
+}
+export type QualifiedPersister = Persister & { isCurrent: () => Promise<boolean>; retireAccount: () => Promise<void>; retireChannels: (ids: Iterable<string>, deleted?: boolean) => Promise<void> }
+function blobKeyFor(userId: string | null, domain: PersistDomain = "community"): string {
+ return `${namespaceFor(userId)}${domain === "application" ? ":application" : ""}:client`
+}
+
+function isPersistedCacheBlobKey(key: IDBValidKey): key is string {
+ return typeof key === "string" && /^alook:qc:[^:]+:[^:]+(?::application)?:client$/.test(key)
+}
+
+export function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`
+ const units = ["KB", "MB", "GB"] as const
+ let value = bytes / 1024
+ let unitIndex = 0
+ while (value >= 1024 && unitIndex < units.length - 1) {
+ value /= 1024
+ unitIndex += 1
+ }
+ return `${Number(value.toFixed(1))} ${units[unitIndex]}`
+}
+
+// Reuse idb-keyval's existing database and native transaction serialization.
+// No document-local lock can fence a writer in another tab.
+const cacheStore = createStore("keyval-store", "keyval")
+const DEVICE_EPOCH_KEY = "alook:qc:device-epoch"
+const scopeEpochKey = (key: string) => `${key}:epoch`
+const accountEpochKey = (userId: string | null) => `${namespaceFor(userId)}:account-epoch`
+type ChannelDiskFence = { epoch: string; deleted: boolean }
+type PersistEligibility = { device: string; scope: string; account: string; channels: Map<string, ChannelDiskFence> }
+const channelFenceKey = (userId: string | null) => `${accountEpochKey(userId)}:channels`
+const isChannelFences = (value: unknown): value is Map<string, ChannelDiskFence> => (
+ value instanceof Map && [...value].every(([id, fence]) => typeof id === "string" && id.length > 0
+ && fence !== null && typeof fence === "object" && isEpoch(fence.epoch) && typeof fence.deleted === "boolean")
+)
+function changedChannelFences(current: Map<string, ChannelDiskFence>, expected: Map<string, ChannelDiskFence>) {
+ return new Map([...current].filter(([id, fence]) => fence.epoch !== expected.get(id)?.epoch))
+}
+function decodeDiskSnapshot(raw: unknown) {
+ try {
+ if (typeof raw !== "string") return undefined
+ const { version, channelFences, ...snapshot } = JSON.parse(raw) as PersistedClient & { version?: unknown; channelFences?: unknown }
+ if (version !== PERSIST_VERSION || snapshot.buster !== PERSIST_BUSTER || !Array.isArray(channelFences)
+ || !channelFences.every((entry) => Array.isArray(entry) && entry.length === 2)) return undefined
+ const fences = new Map(channelFences)
+ return isChannelFences(fences) ? { snapshot, fences } : undefined
+ } catch { return undefined }
+}
+
+const isEpoch = (value: unknown): value is string => (
+ typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)
+)
+
+function communityScopeEpoch(value: unknown): string | undefined {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined
+ const scope = value as Record<string, unknown>
+ return Object.keys(scope).length === 2 && scope.version === PERSIST_VERSION && isEpoch(scope.epoch)
+ ? scope.epoch : undefined
+}
+
+async function cacheTransaction<T>(
+ mode: IDBTransactionMode,
+ operation: (store: IDBObjectStore) => Promise<T>,
+): Promise<T> {
+ return cacheStore(mode, async (store) => {
+ const committed = promisifyRequest(store.transaction)
+ try {
+ const result = await operation(store)
+ await committed
+ return result
+ } catch (error) {
+ await committed.catch(() => undefined)
+ throw error
+ }
+ })
+}
+
+export function preparePersistedCache(): Promise<void> {
+ return cacheTransaction("readonly", async () => undefined)
+}
+
+async function readEligibility(store: IDBObjectStore, key: string, userId: string | null) {
+ const [device, scope, account, channels] = await Promise.all([
+ promisifyRequest<unknown>(store.get(DEVICE_EPOCH_KEY)),
+ promisifyRequest<unknown>(store.get(scopeEpochKey(key))),
+ promisifyRequest<unknown>(store.get(accountEpochKey(userId))),
+ promisifyRequest<unknown>(store.get(channelFenceKey(userId))),
+ ])
+ return { device, scope, account, channels }
+}
+
+// Qualification starts when the account owner is created, before restore or
+// any throttled persistence. Missing/corrupt eligibility never revives an old
+// writer or trusts its payload; generation tombstones survive payload removal.
+function qualifyPersister(key: string, userId: string | null, captureSnapshot: (raw: string, decoded: NonNullable<ReturnType<typeof decodeDiskSnapshot>>) => void): Promise<PersistEligibility> {
+ return cacheTransaction("readwrite", async (store) => {
+ await clearAccountRows(store, userId, true)
+ const raw = await promisifyRequest<unknown>(store.get(key))
+ const current = await readEligibility(store, key, userId)
+ const device = isEpoch(current.device) ? current.device : crypto.randomUUID()
+ const intact = isEpoch(current.account) && isChannelFences(current.channels)
+ const account = intact ? current.account as string : crypto.randomUUID()
+ const channels = intact ? current.channels as Map<string, ChannelDiskFence> : new Map<string, ChannelDiskFence>()
+ const currentScope = communityScopeEpoch(current.scope)
+ const decoded = decodeDiskSnapshot(raw)
+ const compatiblePayload = raw === undefined || Boolean(decoded)
+ let scope = currentScope && compatiblePayload ? currentScope : crypto.randomUUID()
+ if (!intact) {
+ for (const domain of ["community", "application"] as const) {
+ const payloadKey = blobKeyFor(userId, domain)
+ const epoch = crypto.randomUUID()
+ store.delete(payloadKey)
+ store.put(epoch, scopeEpochKey(payloadKey))
+ if (payloadKey === key) scope = epoch
+ }
+ store.put(account, accountEpochKey(userId))
+ store.put(channels, channelFenceKey(userId))
+ }
+ if (!isEpoch(current.device) || !currentScope || !compatiblePayload) store.delete(key)
+ if (!isEpoch(current.device)) store.put(device, DEVICE_EPOCH_KEY)
+ store.put({ version: PERSIST_VERSION, epoch: scope }, scopeEpochKey(key))
+ if (intact && isEpoch(current.device) && currentScope && decoded && typeof raw === "string") captureSnapshot(raw, decoded)
+ return { device, scope, account, channels }
+ })
+}
+
+async function withEligiblePersister<T>(
+ key: string,
+ userId: string | null,
+ eligibility: Promise<PersistEligibility>,
+ mode: IDBTransactionMode,
+ staleValue: T,
+ operation: (store: IDBObjectStore, current: Map<string, ChannelDiskFence>, expected: Map<string, ChannelDiskFence>) => Promise<T>,
+): Promise<T> {
+ const expected = await eligibility
+ return cacheTransaction(mode, async (store) => {
+ const current = await readEligibility(store, key, userId)
+ if (current.device !== expected.device || communityScopeEpoch(current.scope) !== expected.scope || current.account !== expected.account || !isChannelFences(current.channels)) return staleValue
+ return operation(store, current.channels, expected.channels)
+ })
+}
+
+/** Native TanStack persister, qualified against durable device/account epochs. */
+export function createIdbPersister(userId: string | null): QualifiedPersister {
+ const key = blobKeyFor(userId)
+ let initialSnapshot: { raw: string; decoded: NonNullable<ReturnType<typeof decodeDiskSnapshot>> } | undefined
+ let captureInitialSnapshot = true
+ const discardInitialSnapshot = () => { captureInitialSnapshot = false; initialSnapshot = undefined }
+ const eligibility = qualifyPersister(key, userId, (raw, decoded) => { if (captureInitialSnapshot) initialSnapshot = { raw, decoded } })
+ // An unavailable IDB must also fail restore through the provider's onError;
+ // attach a handler immediately so qualification cannot reject unobserved.
+ void eligibility.catch(() => undefined)
+ const writer = createAsyncStoragePersister({
+ storage: {
+ getItem: (get<string>).bind(undefined, key, cacheStore),
+ setItem: (_k: string, value: string) => withEligiblePersister(
+ key, userId, eligibility, "readwrite", undefined, async (store, current, expected) => {
+ const snapshot = scrubDehydratedClient(JSON.parse(value) as PersistedClient, userId, changedChannelFences(current, expected))
+ store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, channelFences: [...current] }), key)
+ },
+ ),
+ // Expiry/buster removal removes only this payload. It does not retire
+ // the owner, so its subsequent fresh network results can persist.
+ removeItem: () => withEligiblePersister(
+ key, userId, eligibility, "readwrite", undefined, async (store) => { store.delete(key) },
+ ),
+ },
+ key: "alook-query-cache",
+ serialize: (client) => JSON.stringify(scrubDehydratedClient(client, userId)),
+ })
+ const persister: Persister = {
+ persistClient: (client) => { discardInitialSnapshot(); return writer.persistClient(client) },
+ restoreClient: async () => {
+ try {
+ const input = await observeRestoreRead(() => withEligiblePersister(key, userId, eligibility, "readwrite", undefined, async (store, current) => {
+ const raw = await promisifyRequest<unknown>(store.get(key))
+ const decoded = initialSnapshot && initialSnapshot.raw === raw ? initialSnapshot.decoded : decodeDiskSnapshot(raw)
+ discardInitialSnapshot()
+ if (!decoded) { store.delete(key); return undefined }
+ return { ...decoded, retired: changedChannelFences(current, decoded.fences) }
+ }), persister)
+ return input && observeRestoreDecode(persister, () => scrubDehydratedClient(input.snapshot, userId, input.retired), PERSIST_BUSTER, PERSIST_MAX_AGE_MS)
+ } finally { discardInitialSnapshot() }
+ },
+ removeClient: () => { discardInitialSnapshot(); return writer.removeClient() },
+ }
+ return Object.assign(persister, {
+ isCurrent: () => withEligiblePersister(key, userId, eligibility, "readonly", false, async () => true),
+ retireChannels: (ids: Iterable<string>, deleted = false) => {
+ discardInitialSnapshot()
+ return withEligiblePersister(key, userId, eligibility, "readwrite", undefined, (store, current) => retireChannelRows(store, key, userId, current, ids, deleted))
+ },
+ retireAccount: async () => {
+ discardInitialSnapshot()
+ const retired = await withEligiblePersister(key, userId, eligibility, "readwrite", false, async (store) => { await clearAccountRows(store, userId); return true })
+ if (retired) publishCacheInvalidation()
+ },
+ })
+}
+
+async function clearAccountRows(store: IDBObjectStore, userId: string | null, legacyOnly = false): Promise<void> {
+ if (!legacyOnly) {
+ store.put(crypto.randomUUID(), accountEpochKey(userId))
+ store.put(new Map(), channelFenceKey(userId))
+ for (const domain of ["community", "application"] as const) {
+ const key = blobKeyFor(userId, domain)
+ store.put(crypto.randomUUID(), scopeEpochKey(key))
+ store.delete(key)
+ }
+ }
+ await new Promise<void>((resolve, reject) => {
+ const request = store.openKeyCursor()
+ request.onerror = () => reject(request.error)
+ request.onsuccess = () => {
+ const cursor = request.result
+ if (!cursor) { resolve(); return }
+ const match = typeof cursor.key === "string" && /^(alook:qc:[^:]+):([^:]+):((?:application:)?client(?::epoch)?|account-epoch(?::channels)?)$/.exec(cursor.key)
+ if (match && match[2] === (userId ?? "anon") && (!legacyOnly || match[1] !== IDB_PREFIX)) {
+ if (match[3] === "account-epoch:channels") store.put(new Map(), cursor.key)
+ else if (match[3]?.endsWith("epoch")) store.put(crypto.randomUUID(), cursor.key)
+ else store.delete(cursor.key)
+ }
+ cursor.continue()
+ }
+ })
+}
+
+async function retireChannelRows(store: IDBObjectStore, key: string, userId: string | null, current: Map<string, ChannelDiskFence>, ids: Iterable<string>, deleted: boolean) {
+ const scopes = [...ids]
+ if (!scopes.length) return
+ await clearAccountRows(store, userId, true)
+ const fences = new Map(current)
+ for (const id of scopes) fences.set(id, { epoch: crypto.randomUUID(), deleted: deleted || fences.get(id)?.deleted === true })
+ store.put(fences, channelFenceKey(userId))
+ const decoded = decodeDiskSnapshot(await promisifyRequest<unknown>(store.get(key)))
+ if (decoded) {
+ const snapshot = scrubDehydratedClient(decoded.snapshot, userId, changedChannelFences(fences, decoded.fences))
+ store.put(JSON.stringify({ ...snapshot, version: PERSIST_VERSION, channelFences: [...fences] }), key)
+ } else store.delete(key)
+}
+
+export async function clearPersistedCache(userId: string | null): Promise<void> {
+ await cacheTransaction("readwrite", (store) => clearAccountRows(store, userId))
+ publishCacheInvalidation()
+}
+
+export async function getPersistedCacheSizeBytes(signal?: AbortSignal): Promise<number> {
+ if (signal?.aborted) throw new DOMException("Cancelled cache size read", "AbortError")
+ const bytes = await cacheTransaction("readonly", (store) => new Promise<number>((resolve, reject) => {
+ let total = 0
+ const encoder = new TextEncoder()
+ const request = store.openCursor()
+ request.onerror = () => reject(request.error)
+ request.onsuccess = () => {
+ const cursor = request.result
+ if (!cursor) { resolve(total); return }
+ if (isPersistedCacheBlobKey(cursor.key) && typeof cursor.value === "string") {
+ total += encoder.encode(cursor.value).byteLength
+ }
+ cursor.continue()
+ }
+ }))
+ if (signal?.aborted) throw new DOMException("Cancelled cache size read", "AbortError")
+ const legacyBytes = await getLegacyChatCacheSizeBytes(signal)
+ const publicBytes = await getPublicWorkerCacheSizeBytes(signal)
+ if (signal?.aborted) throw new DOMException("Cancelled cache size read", "AbortError")
+ return bytes + legacyBytes + publicBytes
+}
+
+/** Clear this device, including qualified writers with no payload yet. */
+export async function clearAllPersistedCaches(): Promise<void> {
+ await cacheTransaction("readwrite", (store) => new Promise<void>((resolve, reject) => {
+ store.put(crypto.randomUUID(), DEVICE_EPOCH_KEY)
+ const request = store.openCursor()
+ request.onerror = () => reject(request.error)
+ request.onsuccess = () => {
+ const cursor = request.result
+ if (!cursor) { resolve(); return }
+ if (isPersistedCacheBlobKey(cursor.key)) cursor.delete()
+ cursor.continue()
+ }
+ }))
+ try {
+ const results = await Promise.allSettled([clearLegacyChatCaches(), clearPublicWorkerCaches()])
+ for (const result of results) if (result.status === "rejected") throw result.reason
+ } finally { publishCacheInvalidation() }
+}
diff --git a/src/web/src/lib/use-user-ws.session.dom.test.tsx b/src/web/src/lib/use-user-ws.session.dom.test.tsx
index 23d86d0ca..eb0452006 100644
--- a/src/web/src/lib/use-user-ws.session.dom.test.tsx
+++ b/src/web/src/lib/use-user-ws.session.dom.test.tsx
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -31,7 +32,7 @@ class SessionSocket {
}
open() { this.readyState = SessionSocket.OPEN; this.onopen?.() }
message(value: unknown) { this.onmessage?.({ data: JSON.stringify(value) }) }
- authenticate() { this.open(); this.message({ type: "auth.ok", communityContract: 2 }) }
+ authenticate() { this.open(); this.message({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION }) }
rejected() { this.readyState = SessionSocket.CLOSED; this.onclose?.({ code: 1008, reason: "Unauthorized", wasClean: false }) }
}
@@ -96,7 +97,7 @@ beforeEach(async () => {
function mount(onMessage = vi.fn()) {
return renderHook(({ viewerUserId }) => useUserWs(onMessage, {
- viewerUserId, communityContract: 2, requestDaemonStatusOnAuth: false,
+ viewerUserId, communityContract: BUSINESS_SCHEMA_VERSION, requestDaemonStatusOnAuth: false,
}), { initialProps: { viewerUserId: "account-a" } })
}
@@ -257,7 +258,7 @@ describe("real BetterAuth SDK WebSocket ownership", () => {
expect(old.readyState).toBe(SessionSocket.CLOSED)
selected = { userId: "account-a", id: "session-a-2", token: "fixture-sdk-a-2" }
await act(async () => { await authClient.$store.atoms.session.get().refetch() })
- act(() => { old.open(); old.message({ type: "auth.ok", communityContract: 2 }); old.message({ type: "task.updated", taskId: "after-unmount" }) })
+ act(() => { old.open(); old.message({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION }); old.message({ type: "task.updated", taskId: "after-unmount" }) })
expect(onMessage).not.toHaveBeenCalled()
expect(SessionSocket.instances).toHaveLength(1)
expect(tokenPaths).toEqual(["/api/ws/token"])
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index d882a911f..d9eb40ee2 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -1,11 +1,13 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
import {
+ BUSINESS_SCHEMA_VERSION,
+ communityBrowserEventBatchType,
+ encodeCommunityBrowserEvent,
COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES,
admitCommunityBrowserEventBatch,
decodeCommunityBrowserEvent,
decodeCommunityBrowserEventBatch,
deriveCommunityDeliveryOperationId,
- encodeCommunityBrowserEventBatch,
encodeCommunityBrowserEventBatchForContract,
prepareCommunityDeliveryEvents,
type CommunityWsEvent,
@@ -80,11 +82,11 @@ class MockWebSocket {
MockWebSocket.instances.push(this)
}
send(data: string) { this.sent.push(data) }
- close() {
+ close(code = 1000, reason = "local detail") {
if (this.readyState === MockWebSocket.CLOSING || this.readyState === MockWebSocket.CLOSED) return
this.closed = true
this.readyState = MockWebSocket.CLOSED
- this.onclose?.({ code: 1000, reason: "local detail", wasClean: true })
+ this.onclose?.({ code, reason, wasClean: true })
}
// Helpers for tests
@@ -314,19 +316,19 @@ describe("useUserWs", () => {
it("keeps bootstrap port discovery and authenticates a current SDK reconnect without another HTTP request", async () => {
mockSdkSession.set(sdkSession())
mockFetch.mockResolvedValue({ ok: true, json: async () => ({ userId: "user-1", token: "bootstrap-token", wsPort: 9123 }) })
- await mountHook(vi.fn(), { viewerUserId: "user-1", communityContract: 2, requestDaemonStatusOnAuth: false })
+ await mountHook(vi.fn(), { viewerUserId: "user-1", communityContract: BUSINESS_SCHEMA_VERSION, requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok", communityContract: 2 })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(mockFetch).toHaveBeenCalledOnce()
- expect(first.sent).toEqual([JSON.stringify({ type: "auth", token: "bootstrap-token", communityContract: 2 })])
+ expect(first.sent).toEqual([JSON.stringify({ type: "auth", token: "bootstrap-token", communityContract: BUSINESS_SCHEMA_VERSION })])
latestHookResult!.reconnectNow()
await flushPromises()
const replacement = MockWebSocket.instances[1]!
expect(replacement.url).toBe("ws://localhost:9123/api/ws/user?userId=user-1")
replacement.simulateOpen()
- expect(replacement.sent).toEqual([JSON.stringify({ type: "auth", token: "current-sdk-token", communityContract: 2 })])
- replacement.simulateMessage({ type: "auth.ok", communityContract: 2 })
+ expect(replacement.sent).toEqual([JSON.stringify({ type: "auth", token: "current-sdk-token", communityContract: BUSINESS_SCHEMA_VERSION })])
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(mockFetch).toHaveBeenCalledOnce()
})
@@ -336,7 +338,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const value = sdkSession()
if (state === "pending") value.isPending = true
if (state === "error") value.error = new Error("session unavailable")
@@ -405,7 +407,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
latestHookResult!.reconnectNow()
await flushPromises()
const sdk = MockWebSocket.instances[1]!
@@ -446,7 +448,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
latestHookResult!.reconnectNow()
await flushPromises()
mockFetch.mockRejectedValueOnce(new Error("fixture transport unavailable"))
@@ -463,7 +465,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
latestHookResult!.reconnectNow()
await flushPromises()
const sdk = MockWebSocket.instances[1]!
@@ -481,7 +483,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { viewerUserId: "user-1", requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
latestHookResult!.reconnectNow()
await flushPromises()
const sdk = MockWebSocket.instances[1]!
@@ -500,7 +502,7 @@ describe("useUserWs", () => {
await mountHook(callback)
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: undefined })
ws.simulateMessage({ type: "community:events.batch.v2", events: [] })
await flushPromises()
expect(callback).not.toHaveBeenCalled()
@@ -521,77 +523,49 @@ describe("useUserWs", () => {
userId: "user-1",
} as const
- async function legacyBatch(events: CommunityWsEvent[]) {
+ async function currentBatch(events: CommunityWsEvent[]) {
const prepared = await prepareCommunityDeliveryEvents(events)
- if (!prepared.ok) throw new Error("invalid regression events")
- const encoded = await encodeCommunityBrowserEventBatch({
- operationId: await deriveCommunityDeliveryOperationId("protocol-regression"),
- operationDigest: prepared.prepared.digest,
- events,
- })
- if (!encoded.ok) throw new Error("invalid regression batch")
- expect(decodeCommunityBrowserEventBatch(encoded.batch).ok).toBe(true)
+ if (!prepared.ok) throw new Error("Invalid current fixture events")
+ const encoded = await encodeCommunityBrowserEventBatchForContract({ operationId: await deriveCommunityDeliveryOperationId("current-protocol-regression"),
+ prepared: prepared.prepared, contract: BUSINESS_SCHEMA_VERSION })
+ if (!encoded.ok) throw new Error("Invalid current fixture batch")
+ expect((await admitCommunityBrowserEventBatch(encoded.batch)).ok).toBe(true)
return encoded.batch
}
- it.each([undefined, 1] as const)("rejects a new membership single without V2 confirmation (%s)", async (contract) => {
+ it.each([undefined, 1, 2, 3, 6, BUSINESS_SCHEMA_VERSION + 1])("retires missing or unsupported business confirmation %s before application admission", async contract => {
setupTokenFetch()
- const callback = vi.fn()
- await mountHook(callback)
+ const callback = vi.fn(), authenticated = vi.fn()
+ await mountHook(callback, { onAuthenticated: authenticated, requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
ws.simulateMessage({ type: "auth.ok", ...(contract === undefined ? {} : { communityContract: contract }) })
- expect(decodeCommunityBrowserEvent(explicitMembership).ok).toBe(true)
- ws.simulateMessage(explicitMembership)
+ ws.simulateMessage({ ...explicitMembership, schemaVersion: BUSINESS_SCHEMA_VERSION })
+ ws.simulateMessage(await currentBatch([explicitMembership]))
await flushPromises()
+ expect(ws.closed).toBe(true)
+ expect(authenticated).not.toHaveBeenCalled()
expect(callback).not.toHaveBeenCalled()
- ws.simulateMessage(legacyMembership)
- expect(callback).toHaveBeenCalledExactlyOnceWith(legacyMembership, undefined, 1)
})
- it.each([undefined, 1] as const)("rejects an entire legacy batch containing a new membership child without V2 confirmation (%s)", async (contract) => {
- const incompatibleBatch = await legacyBatch([legacyMembership, explicitMembership])
- const compatibleBatch = await legacyBatch([legacyMembership])
- setupTokenFetch()
- const callback = vi.fn()
- await mountHook(callback)
- const ws = MockWebSocket.instances[0]!
- ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok", ...(contract === undefined ? {} : { communityContract: contract }) })
- ws.simulateMessage(incompatibleBatch)
- await flushPromises()
- expect(callback).not.toHaveBeenCalled()
- ws.simulateMessage(compatibleBatch)
- expect(callback).toHaveBeenCalledExactlyOnceWith(compatibleBatch, undefined, 1)
- })
-
- it("admits new representations and older producer frames after V2 confirmation", async () => {
- const oldBatch = await legacyBatch([legacyMembership])
- const prepared = await prepareCommunityDeliveryEvents([explicitMembership])
- if (!prepared.ok) throw new Error("invalid regression events")
- const newBatch = await encodeCommunityBrowserEventBatchForContract({
- operationId: await deriveCommunityDeliveryOperationId("protocol-regression-v2"),
- prepared: prepared.prepared,
- contract: 2,
- })
- if (!newBatch.ok) throw new Error("invalid regression batch")
- expect(decodeCommunityBrowserEventBatch(newBatch.batch).ok).toBe(true)
+ it("admits only the current encoded membership single and batch after current confirmation", async () => {
+ const single = encodeCommunityBrowserEvent(explicitMembership)
+ if (!single.ok) throw new Error("Invalid current membership fixture")
+ const batch = await currentBatch([explicitMembership])
+ expect(decodeCommunityBrowserEvent(legacyMembership).ok).toBe(false)
setupTokenFetch()
const received: WsMessage[] = []
- await mountHook((message) => { received.push(message) })
+ await mountHook(message => { received.push(message) })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok", communityContract: 2 })
- ws.simulateMessage(explicitMembership)
- ws.simulateMessage(legacyMembership)
- ws.simulateMessage(oldBatch)
- ws.simulateMessage(newBatch.batch)
- await flushPromises()
- expect(received).toEqual([explicitMembership, legacyMembership, oldBatch, newBatch.batch])
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
+ ws.simulateMessage(single.envelope)
+ ws.simulateMessage(batch)
+ await vi.waitFor(() => expect(received).toEqual([single.envelope, batch]))
})
const resourceMessage = {
- type: "community:message.create", channelId: "channel-1", serverId: "server-1",
+ type: "community:message.create", profiles: [{ id: "user-1", name: "User", discriminator: "0042", avatar: null, avatarVersion: 4 }], channelId: "channel-1", serverId: "server-1",
message: {
id: "resource-message", channelId: "channel-1", seq: 1, type: "chat", authorId: "user-1", authorName: "User", authorAvatarVersion: 4,
createdAt: "2026-10-11T00:00:00Z", content: "actual body", replyToId: null, clientNonce: null,
@@ -600,114 +574,98 @@ describe("useUserWs", () => {
},
} as const
- async function resourceBatch() {
- const prepared = await prepareCommunityDeliveryEvents([resourceMessage], 3)
- if (!prepared.ok) throw new Error("invalid resource regression event")
- const encoded = await encodeCommunityBrowserEventBatchForContract({
- operationId: await deriveCommunityDeliveryOperationId("protocol-regression-v3"),
- prepared: prepared.prepared, contract: 3,
- })
- if (!encoded.ok) throw new Error("invalid resource regression batch")
- expect((await admitCommunityBrowserEventBatch(encoded.batch)).ok).toBe(true)
- return encoded.batch
- }
+ async function resourceBatch() { return currentBatch([resourceMessage]) }
async function mountResourceConnection() {
setupTokenFetch()
const received: CommunityWsEvent[] = []
const callback = vi.fn(async (message: WsMessage, assertCurrent?: () => void, contract?: CommunityContract) => {
- expect(contract).toBe(3)
- if (message.type === "community:events.batch.v3") {
+ expect(contract).toBe(BUSINESS_SCHEMA_VERSION)
+ if (message.type === communityBrowserEventBatchType()) {
const admitted = await admitCommunityBrowserEventBatch(message)
- if (!admitted.ok) throw new Error("invalid resource batch")
+ if (!admitted.ok) throw new Error("Invalid current resource batch")
assertCurrent?.()
- received.push(...admitted.batch.events)
+ for (const child of admitted.batch.events) {
+ const decoded = decodeCommunityBrowserEvent(child)
+ if (!decoded.ok) throw new Error("Invalid admitted current child")
+ received.push(decoded.event)
+ }
} else {
- const decoded = decodeCommunityBrowserEvent(message, 3)
- if (!decoded.ok) throw new Error("invalid resource event")
+ const decoded = decodeCommunityBrowserEvent(message)
+ if (!decoded.ok) return
assertCurrent?.()
received.push(decoded.event)
}
})
const onAuthenticated = vi.fn()
- await mountHook(callback, { communityContract: 3, requestDaemonStatusOnAuth: false, onAuthenticated })
+ await mountHook(callback, { communityContract: BUSINESS_SCHEMA_VERSION, requestDaemonStatusOnAuth: false, onAuthenticated })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- expect(JSON.parse(ws.sent[0]!)).toEqual({ type: "auth", token: "tok-123", communityContract: 3 })
+ expect(JSON.parse(ws.sent[0]!)).toEqual({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION })
return { ws, callback, received, onAuthenticated }
}
- it("requests and positively confirms explicit v3 before real resource admission", async () => {
+ it("requires current confirmation before actual current resource single and batch admission", async () => {
const batch = await resourceBatch()
+ const single = encodeCommunityBrowserEvent(resourceMessage)
+ if (!single.ok) throw new Error("Invalid current resource fixture")
const { ws, callback, received, onAuthenticated } = await mountResourceConnection()
ws.simulateMessage(batch)
await flushPromises()
expect(callback).not.toHaveBeenCalled()
- ws.simulateMessage({ type: "auth.ok", communityContract: 3 })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledOnce()
- ws.simulateMessage(resourceMessage)
+ ws.simulateMessage(single.envelope)
ws.simulateMessage(batch)
await vi.waitFor(() => expect(received).toEqual([resourceMessage, resourceMessage]))
- expect(callback).toHaveBeenLastCalledWith(batch, expect.any(Function), 3)
+ expect(callback).toHaveBeenLastCalledWith(batch, expect.any(Function), BUSINESS_SCHEMA_VERSION)
expect(ws.closed).toBe(false)
})
- it.each([undefined, 1, 2, 4] as const)("rejects mismatched or unknown explicit v3 confirmation %s", async confirmed => {
- const { ws, callback, received, onAuthenticated } = await mountResourceConnection()
- ws.simulateMessage({ type: "auth.ok", ...(confirmed === undefined ? {} : { communityContract: confirmed }) })
- expect(ws.closed).toBe(true)
- expect(onAuthenticated).not.toHaveBeenCalled()
- ws.simulateMessage(resourceMessage)
+ it.each([1, 2, 3, 6])("retires an obsolete version %s batch on a current connection", async contract => {
+ const { ws, callback } = await mountResourceConnection()
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
+ const batch = await resourceBatch()
+ ws.simulateMessage({ ...batch, type: `community:events.batch.v${contract}`, schemaVersion: contract })
await flushPromises()
expect(callback).not.toHaveBeenCalled()
- expect(received).toEqual([])
+ expect(ws.closed).toBe(true)
})
- it("rejects v2 representations on explicit v3 while retaining valid resource delivery", async () => {
- const prepared = await prepareCommunityDeliveryEvents([legacyMembership], 2)
- if (!prepared.ok) throw new Error("invalid legacy regression event")
- const oldBatch = await encodeCommunityBrowserEventBatchForContract({
- operationId: await deriveCommunityDeliveryOperationId("protocol-v2-on-v3"), prepared: prepared.prepared, contract: 2,
- })
- if (!oldBatch.ok) throw new Error("invalid legacy regression batch")
- const batch = await resourceBatch()
- const { ws, callback, received } = await mountResourceConnection()
- ws.simulateMessage({ type: "auth.ok", communityContract: 3 })
- ws.simulateMessage(oldBatch.batch)
- await flushPromises()
- expect(callback).not.toHaveBeenCalled()
- const { channelId: _channel, attachments: _attachments, replyToId: _reply, clientNonce: _nonce, ...legacyMessage } = resourceMessage.message
- const oldSingle = { ...resourceMessage, message: legacyMessage }
- expect(decodeCommunityBrowserEvent(oldSingle, 2).ok).toBe(true)
- expect(decodeCommunityBrowserEvent(oldSingle, 3).ok).toBe(false)
- ws.simulateMessage(oldSingle)
+ it("rejects a weak current resource in the actual decoder and retains current resource delivery", async () => {
+ const { ws, received } = await mountResourceConnection()
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
+ const { channelId: _channel, attachments: _attachments, replyToId: _reply, clientNonce: _nonce, ...weakMessage } = resourceMessage.message
+ const weak = { ...resourceMessage, message: weakMessage, schemaVersion: BUSINESS_SCHEMA_VERSION }
+ expect(decodeCommunityBrowserEvent(weak).ok).toBe(false)
+ ws.simulateMessage(weak)
await flushPromises()
expect(received).toEqual([])
- ws.simulateMessage(batch)
+ ws.simulateMessage(await resourceBatch())
await vi.waitFor(() => expect(received).toEqual([resourceMessage]))
expect(ws.closed).toBe(false)
})
- it("preserves frame order behind asynchronous v2 admission", async () => {
+ it("preserves frame order behind asynchronous current admission", async () => {
setupTokenFetch()
let release!: () => void
const gate = new Promise<void>((resolve) => { release = resolve })
const received: string[] = []
await mountHook(async (message, assertCurrent) => {
- if (message.type === "community:events.batch.v2") await gate
+ if (message.type === communityBrowserEventBatchType()) await gate
assertCurrent?.()
received.push(message.type)
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok", communityContract: 2 })
- ws.simulateMessage({ type: "community:events.batch.v2", events: [] })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
+ ws.simulateMessage(await resourceBatch())
ws.simulateMessage({ type: "runtime.status", status: "online" })
await flushPromises()
expect(received).toEqual([])
release()
await flushPromises()
- await vi.waitFor(() => expect(received).toEqual(["community:events.batch.v2", "runtime.status"]))
+ await vi.waitFor(() => expect(received).toEqual([communityBrowserEventBatchType(), "runtime.status"]))
})
it("retires an in-flight admission and queued frames with their original socket", async () => {
@@ -722,8 +680,8 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok", communityContract: 2 })
- ws.simulateMessage({ type: "community:events.batch.v2", events: [] })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
+ ws.simulateMessage(await resourceBatch())
ws.simulateMessage({ type: "runtime.status", status: "online" })
await flushPromises()
mockNavigator.onLine = false
@@ -776,10 +734,10 @@ describe("useUserWs", () => {
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(ws.sent).toEqual([
- JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }),
+ JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }),
JSON.stringify({ type: "check_daemon_status" }),
])
expect(onMsg).not.toHaveBeenCalled()
@@ -793,10 +751,10 @@ describe("useUserWs", () => {
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(ws.sent).toEqual([
- JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }),
+ JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }),
])
expect(onMsg).not.toHaveBeenCalled()
})
@@ -826,7 +784,7 @@ describe("useUserWs", () => {
expect(onAuthenticated).not.toHaveBeenCalled()
expect(onMessage).not.toHaveBeenCalled()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledTimes(1)
})
@@ -839,7 +797,7 @@ describe("useUserWs", () => {
ws.simulateOpen()
effectCleanup?.()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).not.toHaveBeenCalled()
})
@@ -862,9 +820,9 @@ describe("useUserWs", () => {
expect(secondConnect).toBe(firstConnect)
expect(MockWebSocket.instances).toEqual([ws])
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(ws.sent).toEqual([
- JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }),
+ JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }),
JSON.stringify({ type: "check_daemon_status" }),
])
expect(onMsg).not.toHaveBeenCalled()
@@ -903,11 +861,11 @@ describe("useUserWs", () => {
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
// Deliver a message — should go to cb1
ws.simulateMessage({ type: "test", data: "hello" })
- expect(cb1).toHaveBeenCalledWith({ type: "test", data: "hello" }, undefined, 1)
+ expect(cb1).toHaveBeenCalledWith({ type: "test", data: "hello" }, undefined, BUSINESS_SCHEMA_VERSION)
// Now simulate a re-render with a new callback by updating the ref directly
// In real React, the hook body runs `onMessageRef.current = onMessage` on each render
@@ -918,7 +876,7 @@ describe("useUserWs", () => {
if (onMessageRef) onMessageRef.current = cb2
ws.simulateMessage({ type: "test", data: "world" })
- expect(cb2).toHaveBeenCalledWith({ type: "test", data: "world" }, undefined, 1)
+ expect(cb2).toHaveBeenCalledWith({ type: "test", data: "world" }, undefined, BUSINESS_SCHEMA_VERSION)
expect(cb1).toHaveBeenCalledTimes(1) // cb1 not called again
})
@@ -956,7 +914,7 @@ describe("useUserWs", () => {
expect(onConnectionStateChange).toHaveBeenLastCalledWith("reconnecting")
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onConnectionStateChange).toHaveBeenLastCalledWith("authenticated")
mockDocument.visibilityState = "hidden"
@@ -973,18 +931,18 @@ describe("useUserWs", () => {
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
first.simulateClose()
setupTokenFetch()
await vi.advanceTimersByTimeAsync(2_000)
const replacement = MockWebSocket.instances.at(-1)!
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
onConnectionStateChange.mockClear()
first.simulateClose()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onConnectionStateChange).not.toHaveBeenCalled()
})
@@ -1053,7 +1011,7 @@ describe("useUserWs", () => {
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledOnce()
latestHookResult!.reconnectNow()
@@ -1062,11 +1020,11 @@ describe("useUserWs", () => {
expect(first.closed).toBe(true)
expect(MockWebSocket.instances).toHaveLength(2)
const replacement = MockWebSocket.instances[1]!
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledOnce()
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(5_000)
expect(MockWebSocket.instances).toHaveLength(2)
@@ -1078,7 +1036,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
mockNavigator.onLine = false
mockWindow.dispatch("offline")
@@ -1096,10 +1054,10 @@ describe("useUserWs", () => {
expect(MockWebSocket.instances).toHaveLength(3)
const manual = MockWebSocket.instances[2]!
automatic.simulateOpen()
- automatic.simulateMessage({ type: "auth.ok" })
+ automatic.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledOnce()
manual.simulateOpen()
- manual.simulateMessage({ type: "auth.ok" })
+ manual.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(5_000)
expect(mockFetch).toHaveBeenCalledTimes(3)
@@ -1112,7 +1070,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
latestHookResult!.reconnectNow()
await flushPromises()
@@ -1124,7 +1082,7 @@ describe("useUserWs", () => {
const replacement = MockWebSocket.instances[1]!
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
replacement.simulateClose(1006, "private remote detail", false)
replacement.simulateClose(1006, "duplicate private detail", false)
@@ -1144,7 +1102,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
ws.simulateClose(code, "private raw reason", false)
@@ -1215,7 +1173,7 @@ describe("useUserWs", () => {
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const fetchCount = mockFetch.mock.calls.length
mockDocument.visibilityState = "hidden"
@@ -1299,7 +1257,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
mockTrackCommunityWsLifecycleRecovery.mockImplementationOnce(() => {
mockNavigator.onLine = false
mockWindow.dispatch("offline")
@@ -1426,7 +1384,7 @@ describe("useUserWs", () => {
})
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(ws.closed).toBe(true)
expect(mockTrackCommunityWsLifecycleClose).toHaveBeenCalledWith(expect.objectContaining({
@@ -1480,7 +1438,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const fetchCount = mockFetch.mock.calls.length
mockNavigator.onLine = false
@@ -1514,7 +1472,7 @@ describe("useUserWs", () => {
await mountHook(onMessage, { onReconnect, requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
vi.setSystemTime(new Date("2026-09-12T00:00:00.000Z"))
mockNavigator.onLine = false
@@ -1546,7 +1504,7 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
vi.setSystemTime(new Date("2026-09-12T00:00:00.000Z"))
mockNavigator.onLine = false
@@ -1566,8 +1524,8 @@ describe("useUserWs", () => {
const replacement = MockWebSocket.instances.at(-1)!
expect(replacement).not.toBe(first)
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onReconnect).toHaveBeenCalledOnce()
expect(onReconnect).toHaveBeenCalledWith({
@@ -1584,7 +1542,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const authenticatedTimerCount = vi.getTimerCount()
const sentCount = ws.sent.length
@@ -1612,7 +1570,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const fetchCount = mockFetch.mock.calls.length
mockNavigator.onLine = false
@@ -1633,11 +1591,11 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }))
+ expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }))
mockNavigator.onLine = false
mockWindow.dispatch("offline")
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
first.simulateMessage({ type: "task.updated", taskId: "stale" })
await vi.advanceTimersByTimeAsync(60_000)
@@ -1680,7 +1638,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
@@ -1711,7 +1669,7 @@ describe("useUserWs", () => {
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
interval.mockClear()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(interval.mock.calls.filter(([, delay]) => delay === 25_000 || delay === 5_000)).toHaveLength(0)
await vi.advanceTimersByTimeAsync(60_000)
expect(ws.sent).not.toContain("ping")
@@ -1737,7 +1695,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
await vi.advanceTimersByTimeAsync(25_000)
expect(ws.sent.filter(frame => frame === "ping")).toHaveLength(1)
@@ -1766,7 +1724,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const fetchCount = mockFetch.mock.calls.length
dispatchPageShow(false)
@@ -1784,7 +1742,7 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const fetchCount = mockFetch.mock.calls.length
dispatchWindowFocus()
@@ -1848,7 +1806,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
ws.readyState = MockWebSocket.CLOSING
dispatchWindowFocus()
@@ -1874,7 +1832,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
ws.simulateClose()
mockDocument.visibilityState = "hidden"
@@ -1891,7 +1849,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
first.simulateClose()
dispatchWindowFocus()
@@ -1915,7 +1873,7 @@ describe("useUserWs", () => {
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
@@ -1966,7 +1924,7 @@ describe("useUserWs", () => {
expect(mockFetch).toHaveBeenCalledTimes(replacementFetchCount)
expect(MockWebSocket.instances).toEqual([first, replacement])
expect(replacement.closed).toBe(false)
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onReconnect).toHaveBeenCalledOnce()
})
@@ -1981,7 +1939,7 @@ describe("useUserWs", () => {
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchWindowFocus()
const [{ nonce }] = connectionPings(first)
@@ -2001,11 +1959,11 @@ describe("useUserWs", () => {
const replacement = MockWebSocket.instances[1]!
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onReconnect).toHaveBeenCalledOnce()
first.simulateMessage({ type: "connection.pong", nonce })
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
first.simulateClose()
expect(onDisconnect).toHaveBeenCalledOnce()
expect(MockWebSocket.instances).toHaveLength(2)
@@ -2017,7 +1975,7 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const fetchCount = mockFetch.mock.calls.length
await vi.advanceTimersByTimeAsync(mod.WS_FOREGROUND_SENTINEL_INTERVAL_MS)
@@ -2047,7 +2005,7 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
@@ -2111,13 +2069,13 @@ describe("useUserWs", () => {
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123", communityContract: 2 }))
+ expect(first.sent).toContain(JSON.stringify({ type: "auth", token: "tok-123", communityContract: BUSINESS_SCHEMA_VERSION }))
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
expect(first.closed).toBe(true)
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).not.toHaveBeenCalled()
mockDocument.visibilityState = "visible"
@@ -2166,7 +2124,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const fetchCount = mockFetch.mock.calls.length
onConnectionStateChange.mockClear()
@@ -2199,7 +2157,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onForeground, onReconnect, requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchHiddenToVisible()
expect(onForeground).toHaveBeenCalledOnce()
@@ -2253,7 +2211,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onForeground, requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
dispatchWindowFocus()
@@ -2276,7 +2234,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchHiddenToVisible()
expect(connectionPings(ws)).toHaveLength(1)
@@ -2293,7 +2251,7 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const timerSpy = vi.spyOn(globalThis, "setTimeout")
dispatchHiddenToVisible()
@@ -2324,7 +2282,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchHiddenToVisible()
const [{ nonce }] = connectionPings(ws)
@@ -2352,7 +2310,7 @@ describe("useUserWs", () => {
send(data)
})
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchHiddenToVisible()
await vi.advanceTimersByTimeAsync(1_000)
@@ -2375,7 +2333,7 @@ describe("useUserWs", () => {
})
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
onConnectionStateChange.mockClear()
dispatchHiddenToVisible()
@@ -2403,7 +2361,7 @@ describe("useUserWs", () => {
.toHaveLength(1)
first.simulateMessage({ type: "connection.pong", nonce })
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onDisconnect).toHaveBeenCalledTimes(1)
expect(MockWebSocket.instances).toHaveLength(2)
})
@@ -2417,7 +2375,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchHiddenToVisible()
const firstNonce = connectionPings(ws).at(-1)!.nonce
@@ -2448,7 +2406,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
mockDocument.visibilityState = "hidden"
mockDocument.dispatch("visibilitychange")
@@ -2475,7 +2433,7 @@ describe("useUserWs", () => {
const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchHiddenToVisible()
const [{ nonce }] = connectionPings(ws)
@@ -2497,7 +2455,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchHiddenToVisible()
const [{ nonce }] = connectionPings(ws)
@@ -2526,7 +2484,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
dispatchWindowFocus()
expect(connectionPings(ws)).toHaveLength(1)
@@ -2556,7 +2514,7 @@ describe("useUserWs", () => {
})
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
onConnectionStateChange.mockClear()
dispatchHiddenToVisible()
@@ -2607,7 +2565,7 @@ describe("useUserWs", () => {
await flushPromises()
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
ws.simulateClose()
expect(mockTrackCommunityWsRetryScheduled).toHaveBeenLastCalledWith({
@@ -2781,9 +2739,9 @@ describe("useUserWs", () => {
ws.simulateMessage({ type: "task.updated", taskId: "before" })
expect(onMessage).not.toHaveBeenCalled()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
ws.simulateMessage({ type: "task.updated", taskId: "after" })
- expect(onMessage).toHaveBeenCalledWith({ type: "task.updated", taskId: "after" }, undefined, 1)
+ expect(onMessage).toHaveBeenCalledWith({ type: "task.updated", taskId: "after" }, undefined, BUSINESS_SCHEMA_VERSION)
})
it("does not report an access disconnect for a socket that never authenticated", async () => {
@@ -2809,7 +2767,7 @@ describe("useUserWs", () => {
await vi.advanceTimersByTimeAsync(2_000)
const replacement = MockWebSocket.instances.at(-1)!
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onReconnect).not.toHaveBeenCalled()
})
@@ -2831,10 +2789,10 @@ describe("useUserWs", () => {
expect(JSON.stringify(warn.mock.calls)).not.toContain("sentinel-token")
expect(JSON.stringify(warn.mock.calls)).not.toContain("private")
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const valid = { type: "email.received", agentId: "agent-1" }
ws.simulateMessage(valid)
- expect(onMessage).toHaveBeenCalledWith(valid, undefined, 1)
+ expect(onMessage).toHaveBeenCalledWith(valid, undefined, BUSINESS_SCHEMA_VERSION)
})
it("consumes the raw pong liveness response without reporting a dropped frame", async () => {
@@ -2858,7 +2816,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
warn.mockClear()
await vi.advanceTimersByTimeAsync(29_000)
@@ -2879,8 +2837,8 @@ describe("useUserWs", () => {
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onAuthenticated).toHaveBeenCalledTimes(1)
})
@@ -2891,7 +2849,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: false })
const first = MockWebSocket.instances[0]
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onReconnect).not.toHaveBeenCalled()
vi.setSystemTime(new Date("2026-08-11T08:00:00.000Z"))
@@ -2902,7 +2860,7 @@ describe("useUserWs", () => {
replacement.simulateOpen()
expect(onReconnect).not.toHaveBeenCalled()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
expect(onReconnect).toHaveBeenCalledTimes(1)
expect(onReconnect).toHaveBeenCalledWith({ reconnectDurationMs: 2_000 })
})
@@ -2916,7 +2874,7 @@ describe("useUserWs", () => {
await mountHook(onMessage, { onAuthenticated, onReconnect })
const first = MockWebSocket.instances[0]
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
trace.length = 0
first.simulateClose()
setupTokenFetch()
@@ -2928,7 +2886,7 @@ describe("useUserWs", () => {
if (data === JSON.stringify({ type: "check_daemon_status" })) trace.push("status")
}
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
replacement.simulateMessage({ type: "task.updated", taskId: "after-auth" })
expect(trace).toEqual(["authenticated", "reconnect", "status", "message"])
@@ -2945,7 +2903,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: true })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
await flushPromises()
expect(first.closed).toBe(true)
@@ -2961,13 +2919,13 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onReconnect, requestDaemonStatusOnAuth: true })
const first = MockWebSocket.instances[0]!
first.simulateOpen()
- first.simulateMessage({ type: "auth.ok" })
+ first.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
first.simulateClose()
await vi.advanceTimersByTimeAsync(2_000)
const replacement = MockWebSocket.instances.at(-1)!
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
await flushPromises()
expect(replacement.closed).toBe(true)
@@ -2990,14 +2948,14 @@ describe("useUserWs", () => {
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- expect(() => ws.simulateMessage({ type: "auth.ok" })).not.toThrow()
+ expect(() => ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })).not.toThrow()
expect(ws.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))
expect(() => ws.simulateClose()).not.toThrow()
setupTokenFetch()
await vi.advanceTimersByTimeAsync(2_000)
const replacement = MockWebSocket.instances.at(-1)!
replacement.simulateOpen()
- expect(() => replacement.simulateMessage({ type: "auth.ok" })).not.toThrow()
+ expect(() => replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })).not.toThrow()
expect(replacement.sent).toContain(JSON.stringify({ type: "check_daemon_status" }))
await flushPromises()
expect(warn.mock.calls.flat()).not.toContain("secret sync error")
@@ -3011,7 +2969,7 @@ describe("useUserWs", () => {
await mountHook(onMessage, { requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const oversizedCommunity = JSON.stringify({
type: "community:message.create",
@@ -3020,23 +2978,23 @@ describe("useUserWs", () => {
ws.simulateRawMessage(oversizedCommunity)
expect(onMessage).not.toHaveBeenCalled()
- const legalLargeBatch = {
- type: "community:events.batch",
- payload: "x".repeat(70_000),
- }
+ const legalLargeBatch = await currentBatch([0, 1].map(index => ({ ...resourceMessage,
+ message: { ...resourceMessage.message, id: `large-${index}`, content: "x".repeat(40_000) } })))
+ expect(new TextEncoder().encode(JSON.stringify(legalLargeBatch)).byteLength).toBeGreaterThan(65_536)
ws.simulateMessage(legalLargeBatch)
- expect(onMessage).toHaveBeenCalledWith(legalLargeBatch, undefined, 1)
+ await vi.waitFor(() => expect(onMessage).toHaveBeenCalledWith(legalLargeBatch, expect.any(Function), BUSINESS_SCHEMA_VERSION))
onMessage.mockClear()
ws.simulateRawMessage(JSON.stringify({
- type: "community:events.batch",
+ type: communityBrowserEventBatchType(), schemaVersion: BUSINESS_SCHEMA_VERSION,
payload: "x".repeat(COMMUNITY_BROWSER_EVENT_BATCH_MAX_BYTES),
}))
+ await flushPromises()
expect(onMessage).not.toHaveBeenCalled()
const generic = { type: "task.updated", payload: "x".repeat(65_536) }
ws.simulateMessage(generic)
- expect(onMessage).toHaveBeenCalledWith(generic, undefined, 1)
+ expect(onMessage).toHaveBeenCalledWith(generic, undefined, BUSINESS_SCHEMA_VERSION)
})
it.each(["token", "authentication", "heartbeat"] as const)("keeps one retry deadline when a timed-out %s attempt later fails", async (kind) => {
const random = vi.spyOn(Math, "random").mockReturnValue(0.75)
@@ -3049,7 +3007,7 @@ describe("useUserWs", () => {
if (old) {
old.close = vi.fn(() => { old.readyState = MockWebSocket.CLOSING })
old.simulateOpen()
- if (kind === "heartbeat") old.simulateMessage({ type: "auth.ok" })
+ if (kind === "heartbeat") old.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
}
const count = MockWebSocket.instances.length
await vi.advanceTimersByTimeAsync(kind === "heartbeat" ? 35_000 : mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
@@ -3058,7 +3016,7 @@ describe("useUserWs", () => {
else {
old!.simulateClose()
old!.simulateError()
- old!.simulateMessage({ type: "auth.ok" })
+ old!.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
}
await flushPromises()
expect(mockTrackCommunityWsRetryScheduled).toHaveBeenCalledOnce()
@@ -3080,7 +3038,7 @@ describe("useUserWs", () => {
const old = MockWebSocket.instances[0]!
old.close = vi.fn(() => { old.readyState = MockWebSocket.CLOSING })
old.simulateOpen()
- if (kind === "heartbeat") old.simulateMessage({ type: "auth.ok" })
+ if (kind === "heartbeat") old.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const deadline = kind === "authentication" ? mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS : 35_000
await vi.advanceTimersByTimeAsync(deadline - 1)
expect(old.close).not.toHaveBeenCalled()
@@ -3092,9 +3050,9 @@ describe("useUserWs", () => {
expect(MockWebSocket.instances).toHaveLength(2)
const replacement = MockWebSocket.instances[1]!
replacement.simulateOpen()
- replacement.simulateMessage({ type: "auth.ok" })
+ replacement.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
old.simulateOpen()
- old.simulateMessage({ type: "auth.ok" })
+ old.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
old.simulateMessage({ type: "task.updated" })
old.simulateClose()
old.simulateError()
@@ -3117,7 +3075,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onForeground, onConnectionStateChange, requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
const sent = ws.sent.length
listeners.get("tauri://suspended")!()
dispatchWindowFocus()
@@ -3157,7 +3115,7 @@ describe("useUserWs", () => {
await mountHook(vi.fn(), { onForeground, onConnectionStateChange, requestDaemonStatusOnAuth: false })
const ws = MockWebSocket.instances[0]!
ws.simulateOpen()
- ws.simulateMessage({ type: "auth.ok" })
+ ws.simulateMessage({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION })
callbacks.get("tauri://suspended")!()
resumed.reject(new Error("permission denied"))
await flushPromises()
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index c9ba084d7..8ed44d072 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -1,4 +1,5 @@
"use client"
+import { requestBusinessSchemaUpdate } from "@/lib/business-schema-lifecycle"
import { currentPageObservation, startPageOperation, finishPageOperation, pageOperationAttributes, runPageOperation, type PageOperation } from "@/lib/observability/context"
import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "@/lib/observability/telemetry"
import { useEffect, useRef, useCallback } from "react"
@@ -711,7 +712,7 @@ export function useUserWs(
trackCommunityWsAuthFailure({ failureClass })
}
- let communityContract: CommunityContract = 1
+ let communityContract: CommunityContract = COMMUNITY_CONTRACT_VERSION
const requestedCommunityContract = requestedCommunityContractRef.current
let communityAdmission = Promise.resolve()
let pendingAdmissions = 0
@@ -783,7 +784,7 @@ export function useUserWs(
return
}
const msg = parsed as Record<string, unknown>
- if (msg.type === "auth.error") protocolRejected = true
+ if (msg.type === "auth.error") { protocolRejected = true; requestBusinessSchemaUpdate(Number(msg.communityContract)); ws.close(1008, "Community contract mismatch"); return }
if (typeof msg.type !== "string" || msg.type.length === 0) {
reportDroppedFrame("missing-type", msg)
return
@@ -821,10 +822,10 @@ export function useUserWs(
reportDroppedFrame("duplicate-auth-ok", msg)
return
}
- const confirmed = msg.communityContract ?? 1
- if ((confirmed !== 1 && confirmed !== 2 && confirmed !== 3)
- || (confirmed !== requestedCommunityContract && !(confirmed === 1 && requestedCommunityContract === 2))) {
+ const confirmed = msg.communityContract
+ if (confirmed !== COMMUNITY_CONTRACT_VERSION || confirmed !== requestedCommunityContract) {
protocolRejected = true
+ requestBusinessSchemaUpdate(Number(confirmed))
reportDroppedFrame("invalid-payload", msg)
ws.close(1008, "Community contract confirmation mismatch")
return
@@ -883,12 +884,12 @@ export function useUserWs(
return
}
}
- if ((isCommunityBatch && msg.type !== communityBrowserEventBatchType(communityContract)
- && !(communityContract === 2 && msg.type === communityBrowserEventBatchType(1)))
- || (communityContract === 1 && (msg.type === "community:channel.membership.change"
- || (isCommunityBatch && Array.isArray(msg.events) && msg.events.some((event: unknown) =>
- isCommunityEventCandidate(event) && event.type === "community:channel.membership.change"))))) {
+ if ((isCommunityBatch && msg.type !== communityBrowserEventBatchType(communityContract))
+ || (isCommunityEventCandidate(msg) && !isCommunityBatch && msg.schemaVersion !== communityContract)) {
+ protocolRejected = true
+ requestBusinessSchemaUpdate()
reportDroppedFrame("invalid-payload", msg)
+ ws.close(1008, "Community contract mismatch")
return
}
@@ -896,7 +897,7 @@ export function useUserWs(
const assertAdmissionCurrent = () => {
if (!ownsAuthenticatedConnection(ws, generation) || isOffline() || callback !== onMessageRef.current) throw new DOMException("Retired WebSocket admission", "AbortError")
}
- if ((isCommunityBatch && msg.type !== communityBrowserEventBatchType(1)) || pendingAdmissions > 0) {
+ if (isCommunityBatch || pendingAdmissions > 0) {
if (pendingAdmissions >= 32) { ws.close(1011, "Community admission overloaded"); return }
pendingAdmissions++
communityAdmission = communityAdmission.then(async () => {
@@ -962,6 +963,7 @@ export function useUserWs(
isBackground() || frozenRef.current ? "suspended" : "reconnecting",
)
if (generation !== connectionGenerationRef.current) return
+ if (protocolRejected) { credentialRetryRef.current.stopped = true; return }
if (failedValidation && !isBackground() && !isOffline() && !frozenRef.current) {
void connectRef.current?.()
} else {
@@ -1276,7 +1278,7 @@ export function useUserWs(
const send = useCallback((msg: object) => {
const ws = wsRef.current
if (!isOffline() && isCurrentWsAccount(viewerUserId) && ws?.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify(msg))
+ ws.send(JSON.stringify(isCommunityEventCandidate(msg) ? { ...msg, schemaVersion: COMMUNITY_CONTRACT_VERSION } : msg))
}
}, [isOffline, viewerUserId])
diff --git a/src/web/src/stores/community/ws-store.ts b/src/web/src/stores/community/ws-store.ts
index f5925ec38..624bb90af 100644
--- a/src/web/src/stores/community/ws-store.ts
+++ b/src/web/src/stores/community/ws-store.ts
@@ -1,5 +1,6 @@
import type { Presence as CommunityPresence } from "@/lib/community/models/people"
import { createStore } from "@tanstack/store"
+import type { CommunityApiError } from "@/lib/errors"
// Cap the seen-message set to bound memory. Mirrors the current dedup logic
// in `hooks/community/use-community-ws.ts` (grow to 500, trim to the newest
@@ -29,6 +30,7 @@ type ChannelAccessScope = {
parentChannelId?: string | null
generation: number
revoked: boolean
+ denialCode?: CommunityApiError["code"]
}
type CommunityWsStoreState = {
@@ -38,7 +40,7 @@ type CommunityWsStoreState = {
beginChannelMembershipChange: (serverId: string | null, channelId: string, options?: { preserveRevocation: boolean }) => number
observeChannelScope: (serverId: string, channelId: string, parentChannelId?: string | null) => void
rememberChannelAccess: (serverId: string | null, channelId: string, parentChannelId?: string | null) => void
- revokeChannelAccess: (serverId: string | null, channelId: string) => string[]
+ revokeChannelAccess: (serverId: string | null, channelId: string, denialCode?: CommunityApiError["code"]) => string[]
revokeServerAccess: (serverId: string) => void
grantServerAccess: (serverId: string) => void
isChannelAccessRevoked: (channelId: string, serverId?: string | null, parentChannelId?: string) => boolean
@@ -231,7 +233,9 @@ export function createCommunityWsStore(viewerId: string | null) {
const scopes = new Map(get().channelAccessScopes)
const previous = scopes.get(channelId)
const generation = (previous?.generation ?? 0) + 1
- scopes.set(channelId, { ...previous, serverId, revoked: !!options?.preserveRevocation && !!previous?.revoked, generation })
+ const { denialCode, ...prior } = previous ?? {}
+ scopes.set(channelId, { ...prior, serverId, revoked: !!options?.preserveRevocation && !!previous?.revoked, generation,
+ ...(options?.preserveRevocation && previous?.revoked && denialCode ? { denialCode } : {}) })
setState((state) => ({ ...state, ...{ channelAccessScopes: scopes } }))
return generation
},
@@ -250,12 +254,12 @@ export function createCommunityWsStore(viewerId: string | null) {
scopes.set(channelId, { serverId, parentChannelId, generation: previous?.generation ?? 0, revoked: false })
if (parentChannelId && scopes.get(parentChannelId)?.revoked) {
const parent = scopes.get(parentChannelId)!
- scopes.set(parentChannelId, { ...parent, revoked: false })
+ scopes.set(parentChannelId, { serverId: parent.serverId, parentChannelId: parent.parentChannelId, generation: parent.generation, revoked: false })
}
setState((state) => ({ ...state, ...{ channelAccessScopes: scopes } }))
},
- revokeChannelAccess: (serverId, channelId) => {
+ revokeChannelAccess: (serverId, channelId, denialCode) => {
const scopes = new Map(get().channelAccessScopes)
const affected = new Set([channelId])
for (const [id, scope] of scopes) {
@@ -263,7 +267,8 @@ export function createCommunityWsStore(viewerId: string | null) {
}
for (const id of affected) {
const previous = scopes.get(id)
- scopes.set(id, { serverId, ...previous, generation: (previous?.generation ?? 0) + (previous?.revoked ? 0 : 1), revoked: true })
+ scopes.set(id, { serverId, ...previous, generation: (previous?.generation ?? 0) + (previous?.revoked ? 0 : 1), revoked: true,
+ ...(denialCode ? { denialCode } : {}) })
}
setState((state) => ({ ...state, ...{ channelAccessScopes: scopes } }))
return [...affected]
diff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.ts
index 8fa82af6a..7344d08d3 100644
--- a/src/web/src/stores/community/ws.test.ts
+++ b/src/web/src/stores/community/ws.test.ts
@@ -120,3 +120,38 @@ describe("useCommunityWsStore", () => {
it("keeps audit facts outside the transient owner", () => {
expect(nativeStore.get()).not.toHaveProperty("botAuditEvents")
})})
+
+describe("current scoped denial facts",()=>{
+ it("keeps a classified denial through same-generation cleanup and replaces it only with a current classified cause",()=>{
+ activate()
+ nativeStore.actions.revokeChannelAccess(null,"dm-a","blocked")
+ const generation=nativeStore.get().channelAccessScopes.get("dm-a")!.generation
+ nativeStore.actions.revokeChannelAccess(null,"dm-a")
+ expect(nativeStore.get().channelAccessScopes.get("dm-a")).toMatchObject({generation,revoked:true,denialCode:"blocked"})
+ expect(nativeStore.get().channelAccessScopes.has("dm-b")).toBe(false)
+ nativeStore.actions.revokeChannelAccess(null,"dm-a","not_found")
+ expect(nativeStore.get().channelAccessScopes.get("dm-a")).toMatchObject({generation,denialCode:"not_found"})
+ })
+ it("clears the reason on a new membership generation, authoritative grant and account retirement",()=>{
+ activate()
+ nativeStore.actions.revokeChannelAccess(null,"dm-a","blocked")
+ const generation=nativeStore.actions.beginChannelMembershipChange(null,"dm-a")
+ expect(nativeStore.get().channelAccessScopes.get("dm-a")).toMatchObject({generation,revoked:false})
+ expect(nativeStore.get().channelAccessScopes.get("dm-a")).not.toHaveProperty("denialCode")
+ nativeStore.actions.revokeChannelAccess(null,"dm-a","blocked")
+ nativeStore.actions.rememberChannelAccess(null,"dm-a")
+ expect(nativeStore.get().channelAccessScopes.get("dm-a")).not.toHaveProperty("denialCode")
+ nativeStore.actions.revokeChannelAccess(null,"dm-a","blocked")
+ nativeStore.actions.activateProfileAccount("next-viewer")
+ expect(nativeStore.get().channelAccessScopes.size).toBe(0)
+ })
+ it("preserves only explicitly retained revocation and clears a granted parent cause",()=>{
+ activate()
+ nativeStore.actions.revokeChannelAccess("server","parent","not_allowed")
+ nativeStore.actions.beginChannelMembershipChange("server","parent",{preserveRevocation:true})
+ expect(nativeStore.get().channelAccessScopes.get("parent")).toMatchObject({revoked:true,denialCode:"not_allowed"})
+ nativeStore.actions.rememberChannelAccess("server","child","parent")
+ expect(nativeStore.get().channelAccessScopes.get("parent")).toMatchObject({revoked:false})
+ expect(nativeStore.get().channelAccessScopes.get("parent")).not.toHaveProperty("denialCode")
+ })
+})
diff --git a/src/web/src/test/community-query-owner.ts b/src/web/src/test/community-query-owner.ts
index a6b01f420..0aa66fec3 100644
--- a/src/web/src/test/community-query-owner.ts
+++ b/src/web/src/test/community-query-owner.ts
@@ -1,3 +1,4 @@
+import { messageSeedFixture, resourceBundleFixture } from "./community-resource-fixtures"
import { AttentionScopeSchema, AttentionItemSchema } from "@alook/shared"
import { beforeEach } from "vitest"
import { act } from "react"
@@ -31,7 +32,7 @@ export async function createCommunityQueryOwner(accountId = "viewer", config?: Q
export function seedCommunityMessageWindow(client: QueryClient, key: QueryKey, window: InfiniteData<MessagesPage>, options?: SetDataOptions) {
const registry = getCommunityDbRegistry(client)
if (!registry || key.at(-1) !== "messages") throw new Error("Message fixture requires its original owner and window key")
- ingestMessages(registry, String(key.at(-2)), window.pages.flatMap((page) => page.messages))
+ ingestMessages(registry, String(key.at(-2)), messageSeedFixture(String(key.at(-2)), window.pages.flatMap((page) => page.messages)))
return client.setQueryData(key, {
...window,
pages: window.pages.map((page) => ({ ...page, hasMoreNewer: page.hasMoreNewer ?? false, messages: page.messages.map(({ id }) => ({ id })) })),
@@ -57,5 +58,5 @@ beforeEach(() => async () => {
export function seedCommunityAttentionScope(client: QueryClient, input: { channelId: string; serverId?: string | null; parentChannelId?: string | null; seq?: number; ordinaryUnread?: boolean; attentionCount?: number }) {
const registry = getCommunityDbRegistry(client)!
const scope = { scopeId: input.channelId, channelId: input.channelId, serverId: input.serverId ?? null, parentChannelId: input.parentChannelId ?? null, lastUnreadSeq: input.seq ?? 1, ordinaryUnread: input.ordinaryUnread ?? true, attentionCount: input.attentionCount ?? 0, lastAttentionSeq: input.attentionCount ? input.seq ?? 1 : null }
- ingestAttentionSnapshot(registry, { scopes: [...[...registry.collections.attentionScopes.values()].filter(row => row.channelId !== input.channelId).map(row => AttentionScopeSchema.strip().parse(row)), scope], items: [...registry.collections.attentionItems.values()].map(row => AttentionItemSchema.strip().parse(row)), limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } })
+ ingestAttentionSnapshot(registry, { resources: resourceBundleFixture({ viewerId: registry.accountId! }), scopes: [...[...registry.collections.attentionScopes.values()].filter(row => row.channelId !== input.channelId).map(row => AttentionScopeSchema.strip().parse(row)), scope], items: [...registry.collections.attentionItems.values()].map(row => AttentionItemSchema.strip().parse(row)), limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } })
}
diff --git a/src/web/src/test/community-registry-snapshot.ts b/src/web/src/test/community-registry-snapshot.ts
new file mode 100644
index 000000000..c323aaf18
--- /dev/null
+++ b/src/web/src/test/community-registry-snapshot.ts
@@ -0,0 +1,9 @@
+import type { CommunityDbRegistry } from "@/lib/community-db/collections"
+import { beginCommunityProfileSeed } from "@/lib/community/profile-seed"
+
+export function communityRegistrySnapshot(registry: CommunityDbRegistry) {
+ return {
+ collections: Object.fromEntries(Object.entries(registry.collections).map(([name, collection]) => [name, structuredClone([...collection.base.values()])])),
+ profileRevision: beginCommunityProfileSeed(registry).revision,
+ }
+}
diff --git a/src/web/src/test/community-resource-fixtures.ts b/src/web/src/test/community-resource-fixtures.ts
new file mode 100644
index 000000000..c2a61cfa3
--- /dev/null
+++ b/src/web/src/test/community-resource-fixtures.ts
@@ -0,0 +1,203 @@
+import { parseCommunityServerMembersRead, CommunityResourceProfileSchema, CommunityInvitesReadSchema, type CommunityInviteListItem, type CommunityResourceProfile } from "@alook/shared"
+import { CommunityAcceptedFriendsReadSchema, CommunityBlockedFriendsReadSchema, CommunityPendingFriendsReadSchema, AccountAttentionSnapshotSchema, CommunityThreadsReadSchema, encodeCommunityBrowserEvent, BUSINESS_SCHEMA_VERSION, CommunityMachineSummarySchema, CommunityChannelResourceSchema, CommunityMessageResourceSchema, CommunityServerResourceSchema, CommunityCategoryResourceSchema, CommunityResourceBundleSchema,
+ type CommunityChannelResource, type CommunityMessageResource, type CommunityResourceBundle } from "@alook/shared"
+
+export function channelResourceFixture(fields: Partial<CommunityChannelResource> = {}): CommunityChannelResource {
+ return CommunityChannelResourceSchema.parse({ id: "c1", type: "text", serverId: "s1", categoryId: null,
+ name: "Channel", topic: "", parentChannelId: null, parentMessageId: null, creatorId: "viewer", position: 0,
+ archived: false, createdAt: "2026-10-01T00:00:00.000Z", lastMessageAt: null, messageCount: 0, ...fields })
+}
+
+export function messageResourceFixture(fields: Partial<CommunityMessageResource> = {}): CommunityMessageResource {
+ return CommunityMessageResourceSchema.parse({ id: "m1", channelId: "c1", seq: 1, authorId: "viewer", type: "chat",
+ createdAt: "2026-10-01T00:00:01.000Z", content: "Body", replyToId: null, clientNonce: null, attachments: [], ...fields })
+}
+
+export function messageProfilesFixture(messages: readonly CommunityMessageResource[]): CommunityResourceProfile[] {
+ const profiles = new Map<string, CommunityResourceProfile>()
+ for (const message of messages) {
+ profiles.set(message.authorId, profileResourceFixture({ id: message.authorId, name: message.authorName ?? message.authorId, avatar: message.authorAvatar ?? null, avatarVersion: message.authorAvatarVersion ?? 0 }))
+ if (message.replyTo?.authorId && message.replyTo.deleted !== true && !profiles.has(message.replyTo.authorId)) profiles.set(message.replyTo.authorId, profileResourceFixture({ id: message.replyTo.authorId, name: message.replyTo.authorName }))
+ }
+ return [...profiles.values()]
+}
+
+export function messageReadPageFixture<T extends { messages: CommunityMessageResource[] }>(page: T) {
+ return { ...page, profiles: messageProfilesFixture(page.messages) }
+}
+
+export function singleMessageReadFixture(message: CommunityMessageResource) {
+ return { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: message.channelId, message, profiles: messageProfilesFixture([message]) }
+}
+
+export function serverResourceFixture(fields: Partial<ReturnType<typeof CommunityServerResourceSchema.parse>> = {}) {
+ return CommunityServerResourceSchema.parse({ id: "s1", position: 0, name: "Server", discriminator: "1234", description: "", ownerId: "viewer", icon: null, official: false, isOwner: true, ...fields })
+}
+
+export function categoryResourceFixture(fields: Partial<ReturnType<typeof CommunityCategoryResourceSchema.parse>> = {}) {
+ return CommunityCategoryResourceSchema.parse({ id: "cat1", serverId: "s1", name: "Category", position: 0, private: false, creatorId: "viewer", ...fields })
+}
+
+export function profileResourceFixture(fields: Partial<CommunityResourceProfile> = {}): CommunityResourceProfile {
+ return CommunityResourceProfileSchema.parse({ id: "viewer", name: "Viewer", discriminator: "0042", avatar: null, avatarVersion: 0, ...fields })
+}
+
+export function resourceBundleFixture(fields: Partial<CommunityResourceBundle> = {}): CommunityResourceBundle {
+ return CommunityResourceBundleSchema.parse({ viewerId: "viewer", servers: [], serverMemberships: [], channels: [], memberships: [], profiles: [], messages: [], ...fields })
+}
+
+type ChannelScenario = Partial<CommunityChannelResource> & { id: string; [field: string]: unknown }
+type CategoryScenario = Partial<ReturnType<typeof CommunityCategoryResourceSchema.parse>> & { id: string; channels?: ChannelScenario[]; [field: string]: unknown }
+type DirectoryScenario = Partial<ReturnType<typeof CommunityServerResourceSchema.parse>> & { id: string; categories?: CategoryScenario[]; channels?: ChannelScenario[]; [field: string]: unknown }
+
+export function serverDirectoryFixture(scenario: DirectoryScenario) {
+ const { categories = [], channels = [], ...serverFields } = scenario
+ const server = serverResourceFixture(Object.fromEntries(Object.entries(serverFields).filter(([key]) => key in CommunityServerResourceSchema.shape)))
+ return { server,
+ categories: categories.map(({ channels: _channels, ...category }, position) => categoryResourceFixture(Object.fromEntries(Object.entries({ ...category, position: category.position ?? position, serverId: server.id }).filter(([key]) => key in CommunityCategoryResourceSchema.shape)))),
+ channels: [...channels.map(channel => channelResourceFixture(Object.fromEntries(Object.entries({ ...channel, serverId: server.id }).filter(([key]) => key in CommunityChannelResourceSchema.shape)))),
+ ...categories.flatMap(category => (category.channels ?? []).map((channel, position) => channelResourceFixture(Object.fromEntries(Object.entries({ ...channel, position: channel.position ?? position, serverId: server.id, categoryId: category.id }).filter(([key]) => key in CommunityChannelResourceSchema.shape)))))],
+ }
+}
+
+export function fullResourceBundleFixture(viewerId: string, servers: CommunityResourceBundle["servers"], channels: CommunityResourceBundle["channels"], messages: CommunityResourceBundle["messages"] = [], profiles: CommunityResourceBundle["profiles"] = [profileResourceFixture({ id: viewerId }), ...messageProfilesFixture(messages).filter(profile => profile.id !== viewerId)]) {
+ return resourceBundleFixture({ viewerId, servers, channels, messages, profiles,
+ serverMemberships: servers.map(server => ({ serverId: server.id, userId: viewerId, memberId: `member-${server.id}`, role: server.ownerId === viewerId ? "owner" : "member" })),
+ memberships: channels.flatMap(channel => [{ channelId: channel.id, userId: viewerId, relation: "access" as const, source: "explicit" },
+ ...(channel.type === "thread" ? [{ channelId: channel.id, userId: viewerId, relation: "notify" as const, source: "spoke" as const }] : [])]),
+ })
+}
+
+export function forumSidebarEnvelopeFixture(serverId: string, ids = ["post_1"], viewerId = "viewer", content?: string) {
+ const now = new Date().toISOString()
+ const server = serverResourceFixture({ id: serverId, ownerId: viewerId })
+ const parent = channelResourceFixture({ id: "forum_1", serverId, type: "forum" })
+ const children = ids.map(id => channelResourceFixture({ id, serverId, type: "thread", name: `fallback-${id}`, parentChannelId: parent.id, parentMessageId: `opener-${id}`, lastMessageAt: now }))
+ const summaries = children.map(channel => ({ id: channel.id, name: channel.name, serverId, parentChannelId: parent.id, parentMessageId: channel.parentMessageId!, activityAt: now, expiresAt: new Date(Date.now() + 72 * 3600_000).toISOString(), unread: false }))
+ return { schemaVersion: BUSINESS_SCHEMA_VERSION, serverId, channels: summaries, canonicalChannels: summaries,
+ retainedChannel: null, retainedDisposition: null, serverNow: now,
+ resources: fullResourceBundleFixture(viewerId, [server], [parent, ...children], children.map(channel => messageResourceFixture({ id: channel.parentMessageId!, channelId: parent.id, content: content ?? `title-${channel.id}` })), [profileResourceFixture()]),
+ }
+}
+
+export function dmListRowFixture(fields: Partial<import("@/lib/community/models/people").DM> & { id: string; userId: string }, viewerId = "viewer") {
+ const profile = { id: fields.userId, name: fields.name ?? "Peer", discriminator: fields.discriminator ?? "1234", avatar: null, avatarVersion: fields.avatarVersion ?? 0 }
+ const channel = channelResourceFixture({ id: fields.id, type: "dm", serverId: null, name: null })
+ return { id: fields.id, userId: fields.userId, preview: fields.preview ?? "", profile, channel,
+ activityAt: fields.activityAt ?? channel.lastMessageAt ?? channel.createdAt,
+ unread: fields.unread ?? false,
+ ...(fields.lastUnreadSeq === undefined ? {} : { lastUnreadSeq: fields.lastUnreadSeq }),
+ memberships: [viewerId, fields.userId].map(userId => ({ channelId: fields.id, userId, relation: "access" as const, source: "added" as const, isCreator: false, role: null, memberId: null })),
+ }
+}
+
+
+export function machineResourceFixture(fields: Partial<ReturnType<typeof CommunityMachineSummarySchema.parse>> = {}) {
+ return CommunityMachineSummarySchema.parse({ id: "m1", hostname: "host", displayName: "Host", platform: "darwin", arch: "arm64", osRelease: "26", daemonVersion: "0.1.53", lastSeenAt: null, status: "online", availableRuntimes: [], createdAt: "2026-10-01T00:00:00Z", updatedAt: "2026-10-01T00:00:00Z", ...fields })
+}
+
+
+export function serverRailResponseFixture(scenario: { servers: Array<{ id: string; [field: string]: unknown }> }, viewerId: string | null = "viewer"): import("@/hooks/community/use-servers").ServersResponse {
+ return { servers: scenario.servers.map((row, position) => {
+ const fields = Object.fromEntries(Object.entries(row).filter(([key]) => key in CommunityServerResourceSchema.shape))
+ const server = serverResourceFixture({ ...fields, id: row.id, position, isOwner: row.isOwner === undefined ? row.ownerId === viewerId : row.isOwner as boolean })
+ const role = row.role === undefined ? server.isOwner ? "owner" : "member" : row.role
+ if (role !== "owner" && role !== "admin" && role !== "member") throw new Error("Invalid declared fixture role")
+ return { ...server, initial: server.name[0] ?? "", active: false, unread: row.unread === true, mentions: typeof row.mentions === "number" ? row.mentions : 0,
+ memberId: typeof row.memberId === "string" ? row.memberId : `member-${server.id}`, role }
+ }) }
+}
+
+
+export function messageSeedFixture(channelId: string, scenario: ReadonlyArray<{ id: string; [field: string]: unknown }>) {
+ return scenario.map(row => messageResourceFixture({ channelId, ...Object.fromEntries(Object.entries(row).filter(([key]) => key in CommunityMessageResourceSchema.shape)) }))
+}
+
+export function currentCommunityEventFixture(value: unknown) {
+ const encoded = encodeCommunityBrowserEvent(value)
+ if (!encoded.ok) throw new Error(`Invalid current event fixture: ${encoded.reason}`)
+ return encoded.envelope
+}
+
+type ForumMessageScenario = Partial<CommunityMessageResource> & { id: string; authorImage?: string | null }
+type ForumFeedScenario = {
+ serverId: string
+ parentType: "forum" | "text"
+ threads: Array<Partial<CommunityChannelResource> & { id: string }>
+ included: {
+ parentMessages?: ForumMessageScenario[]
+ firstMessages?: Array<Partial<CommunityMessageResource> & { channelId: string; content: string }>
+ participants?: Array<{ channelId: string; userId: string; userName?: string | null; userImage?: string | null; userAvatarVersion?: number; participantCount?: number }>
+ tags?: Array<{ messageId: string; tag: string }>
+ }
+ hasMore: boolean
+ nextCursor?: string | null
+}
+
+export function forumFeedScenarioFixture(channelId: string, scenario: ForumFeedScenario) {
+ const channel = channelResourceFixture({ id: channelId, serverId: scenario.serverId, type: scenario.parentType })
+ const threads = scenario.threads.map(row => channelResourceFixture({ ...Object.fromEntries(Object.entries(row).filter(([key]) => key in CommunityChannelResourceSchema.shape)),
+ id: row.id, serverId: scenario.serverId, type: "thread", parentChannelId: channelId }))
+ const openers = (scenario.included.parentMessages ?? []).map(({ authorImage, ...row }) => messageResourceFixture({ channelId, ...row,
+ ...(authorImage === undefined ? {} : { authorAvatar: authorImage }) }))
+ const first = (scenario.included.firstMessages ?? []).map(row => messageResourceFixture({ id: `first-${row.channelId}`, ...row }))
+ const profiles = new Map<string, CommunityResourceProfile>()
+ for (const row of [...openers, ...first]) {
+ profiles.set(row.authorId, profileResourceFixture({ id: row.authorId, name: row.authorName ?? "Author", avatar: row.authorAvatar ?? null, avatarVersion: row.authorAvatarVersion ?? 0 }))
+ if (row.replyTo?.authorId && row.replyTo.deleted !== true) profiles.set(row.replyTo.authorId, profileResourceFixture({ id: row.replyTo.authorId, name: row.replyTo.authorName }))
+ }
+ for (const row of scenario.included.participants ?? []) profiles.set(row.userId, profileResourceFixture({ id: row.userId, name: row.userName ?? "Participant", avatar: row.userImage ?? null, avatarVersion: row.userAvatarVersion ?? 0 }))
+ return CommunityThreadsReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, channelId, channel, threads,
+ included: { messages: [...openers, ...first], profiles: [...profiles.values()], tags: scenario.included.tags ?? [],
+ members: (scenario.included.participants ?? []).map(row => ({ channelId: row.channelId, userId: row.userId, relation: "notify", source: "spoke", isCreator: false, role: null, memberId: null })),
+ participantCounts: threads.map(thread => ({ channelId: thread.id, count: scenario.included.participants?.find(row => row.channelId === thread.id)?.participantCount ?? (scenario.included.participants ?? []).filter(row => row.channelId === thread.id).length })),
+ }, page: { hasMore: scenario.hasMore, nextCursor: scenario.nextCursor ?? null },
+ })
+}
+
+export function attentionSnapshotScenarioFixture(scenario: Omit<import("@alook/shared").AccountAttentionSnapshot, "resources">, viewerId = "viewer") {
+ const { included } = scenario
+ const servers = included.servers.map(row => serverResourceFixture({ ...row, ownerId: viewerId }))
+ const channels = [
+ ...included.channels.map(row => channelResourceFixture(Object.fromEntries(Object.entries(row).filter(([key]) => key in CommunityChannelResourceSchema.shape)))),
+ ...included.dms.map(row => channelResourceFixture({ id: row.id, serverId: null, type: "dm", name: null, lastMessageAt: row.lastMessageAt })),
+ ]
+ const profiles = included.profiles.map(({ userId, ...profile }) => ({ id: userId, ...profile }))
+ const messages = included.messages.map(row => messageResourceFixture({ ...row, authorId: row.authorId ?? "viewer" }))
+ const resources = fullResourceBundleFixture(viewerId, servers, channels, messages, [...new Map([...messageProfilesFixture(messages), ...profiles].map(profile => [profile.id, profile])).values()])
+ resources.memberships = resources.memberships.filter(row => row.relation === "access")
+ return AccountAttentionSnapshotSchema.parse({ ...scenario, resources })
+}
+
+
+export function friendBucketScenarioFixture<K extends "friends" | "blocked" | "pending", R extends { id: string; userId: string; name: string; avatar: string; avatarVersion: number; discriminator: string; sub?: string; kind?: string; needsOwnerApproval?: string | null }>(bucket: K, rows: R[], viewerId = "viewer") {
+ const resources = resourceBundleFixture({ viewerId, profiles: rows.map(row => ({ id: row.userId, name: row.name, discriminator: row.discriminator, avatar: row.avatar, avatarVersion: row.avatarVersion })) })
+ const descriptors = rows.map(row => ({ id: row.id, userId: row.userId,
+ ...(bucket === "friends" && row.sub !== undefined ? { sub: row.sub } : {}),
+ ...(bucket === "pending" ? { kind: row.kind, ...(row.needsOwnerApproval === undefined ? {} : { needsOwnerApproval: row.needsOwnerApproval }) } : {}),
+ }))
+ const schema = bucket === "friends" ? CommunityAcceptedFriendsReadSchema : bucket === "blocked" ? CommunityBlockedFriendsReadSchema : CommunityPendingFriendsReadSchema
+ return schema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, [bucket]: descriptors, resources }) as Record<K, Array<{ id: string; userId: string; kind?: string }>> & { resources: CommunityResourceBundle }
+}
+
+export function staleFriendBucketFixture(bucket: "friends" | "blocked" | "pending") {
+ const schema = bucket === "friends" ? CommunityAcceptedFriendsReadSchema : bucket === "blocked" ? CommunityBlockedFriendsReadSchema : CommunityPendingFriendsReadSchema
+ return schema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, [bucket]: [], stale: true })
+}
+
+export function invitesReadFixture(serverId: string, invites: CommunityInviteListItem[] = [], profiles: CommunityResourceProfile[] = [], viewerId = "viewer") {
+ return CommunityInvitesReadSchema.parse({ contractVersion: BUSINESS_SCHEMA_VERSION, serverId, invites,
+ resources: fullResourceBundleFixture(viewerId, [serverResourceFixture({ id: serverId, ownerId: viewerId, isOwner: true })], [], [], profiles),
+ })
+}
+
+export function serverMembersReadFixture(serverId: string, members: Array<{ id: string; userId: string; [field: string]: unknown }>, options: { viewerId?: string; search?: boolean; hasMore?: boolean; cursor?: string; limit?: number; total?: number } = {}) {
+ const viewerId = options.viewerId ?? "viewer"
+ const rows = members.map(row => ({ id: row.id, userId: row.userId, name: row.name, discriminator: row.discriminator, avatar: row.avatar, avatarVersion: row.avatarVersion,
+ role: row.role, status: row.status ?? (row.userId === viewerId ? "online" : "offline"), sub: row.sub ?? "",
+ statusEmoji: row.statusEmoji === undefined ? null : row.statusEmoji, statusText: row.statusText === undefined ? null : row.statusText,
+ }))
+ return parseCommunityServerMembersRead({ viewerId, serverId, members: rows, hasMore: options.hasMore ?? false, limit: options.limit ?? 100,
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor }), ...(options.search ? {} : { total: options.total ?? rows.length }),
+ }, serverId, viewerId, options.search ?? false)
+}
diff --git a/src/web/src/test/community-sqlite-db.test.ts b/src/web/src/test/community-sqlite-db.test.ts
new file mode 100644
index 000000000..70c377451
--- /dev/null
+++ b/src/web/src/test/community-sqlite-db.test.ts
@@ -0,0 +1,61 @@
+import { readFileSync } from "node:fs"
+import { afterEach, expect, it } from "vitest"
+import { createRequire } from "node:module"
+import { queries } from "@alook/shared"
+import { user } from "../../../shared/src/db/schema"
+import { createCommunitySqliteDb } from "./community-sqlite-db"
+
+const { eq } = createRequire(import.meta.resolve("@alook/shared"))("drizzle-orm") as { eq: (column: typeof user.id, value: string) => ReturnType<typeof user.id.getSQL> }
+const stores: ReturnType<typeof createCommunitySqliteDb>[] = []
+afterEach(() => { for (const store of stores) store.sqlite.close(); stores.length = 0 })
+function fixture() {
+ const store = createCommunitySqliteDb(); stores.push(store)
+ store.sqlite.exec("INSERT INTO user (id,name,email,discriminator,\"avatarVersion\",\"isBot\",\"ownerUserId\") VALUES ('viewer','Viewer','[email protected]','0042',0,0,null),('bot','Bot','[email protected]','0043',0,1,'viewer')")
+ store.sqlite.exec("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES ('server','Server','0044','','viewer','2026-10-29T00:00:00Z')")
+ store.sqlite.exec("INSERT INTO community_server_member (id,server_id,user_id,role) VALUES ('viewer-member','server','viewer','owner'),('bot-member','server','bot','member')")
+ store.sqlite.exec("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at) VALUES ('channel','server','Channel','text','',0,0,0,'2026-10-29T00:00:00Z')")
+ return store
+}
+it("retains the actual migration's two notification partial unique constraints", () => {
+ const { sqlite } = fixture()
+ const migration = readFileSync(new URL("../../migrations/0068_dm_to_channel.sql", import.meta.url), "utf8")
+ const statements = migration.split("\n").filter(line => line.startsWith("CREATE UNIQUE INDEX idx_notification_setting_user_"))
+ expect(statements).toHaveLength(2)
+ for (const sql of statements) {
+ const name = /^CREATE UNIQUE INDEX (\S+)/.exec(sql)![1]
+ expect(sqlite.prepare("SELECT sql FROM sqlite_master WHERE type='index' AND name=?").get(name)).toMatchObject({ sql: sql.replace(/;$/, "") })
+ }
+})
+it("implements the public unmapped D1 all contract with actual ORM SQL, named columns and parameter binding", async () => {
+ const { db, record } = fixture()
+ const selected = (id: string) => db.select({ id: user.id, name: user.name }).from(user).where(eq(user.id, id)).getSQL()
+ expect(await db.all(selected("viewer"))).toEqual([{ id: "viewer", name: "Viewer" }])
+ expect(await db.all(selected("absent"))).toEqual([])
+ expect(record.statements.map(row => row.bindings)).toEqual([["viewer"], ["absent"]])
+ expect(record.invocations).toBe(2)
+})
+it("persists a real bot notification upsert and update without a human read-state revision", async () => {
+ const { db, sqlite, record } = fixture()
+ const first = await queries.communityNotificationSetting.setChannelLevel(db, { userId: "bot", channelId: "channel", level: "mentions", actorKind: "bot" })
+ const second = await queries.communityNotificationSetting.setChannelLevel(db, { userId: "bot", channelId: "channel", level: "nothing", actorKind: "bot" })
+ expect(first).toMatchObject({ setting: { userId: "bot", channelId: "channel", level: "mentions" }, readStateRevision: null })
+ expect(second).toMatchObject({ setting: { id: first.setting.id, level: "nothing" }, readStateRevision: null })
+ expect(await queries.communityNotificationSetting.getChannelSetting(db, "bot", "channel")).toMatchObject({ id: first.setting.id, level: "nothing" })
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting").get()).toMatchObject({ count: 1 })
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_read_state_revision").get()).toMatchObject({ count: 0 })
+ expect(record.batches).toEqual([])
+})
+it("rolls back a real human policy batch after the first write and accepts the same input after storage recovers", async () => {
+ const { db, sqlite, record } = fixture()
+ sqlite.exec("CREATE TRIGGER reject_setting BEFORE INSERT ON community_notification_setting BEGIN SELECT RAISE(ABORT,'test setting storage rejection'); END")
+ const before = (sqlite.prepare("SELECT total_changes() AS count").get() as { count: number }).count
+ await expect(queries.communityNotificationSetting.setChannelLevel(db, { userId: "viewer", channelId: "channel", level: "nothing", actorKind: "human" })).rejects.toThrow()
+ expect((sqlite.prepare("SELECT total_changes() AS count").get() as { count: number }).count).toBeGreaterThan(before)
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_read_state_revision").get()).toMatchObject({ count: 0 })
+ expect(await queries.communityNotificationSetting.getChannelSetting(db, "viewer", "channel")).toBeNull()
+ expect(record.batches).toEqual([3])
+ sqlite.exec("DROP TRIGGER reject_setting")
+ const accepted = await queries.communityNotificationSetting.setChannelLevel(db, { userId: "viewer", channelId: "channel", level: "nothing", actorKind: "human" })
+ expect(accepted).toMatchObject({ setting: { level: "nothing" }, readStateRevision: 1 })
+ expect(sqlite.prepare("SELECT revision FROM community_read_state_revision WHERE user_id='viewer'").get()).toMatchObject({ revision: 1 })
+})
diff --git a/src/web/src/test/community-sqlite-db.ts b/src/web/src/test/community-sqlite-db.ts
new file mode 100644
index 000000000..98a483b71
--- /dev/null
+++ b/src/web/src/test/community-sqlite-db.ts
@@ -0,0 +1,72 @@
+import type { SQLInputValue } from "node:sqlite"
+import { createRequire } from "node:module"
+import { createDb } from "@alook/shared"
+import * as machineTables from "../../../shared/src/db/community-machine-schema"
+import * as tables from "../../../shared/src/db/community-schema"
+import { user } from "../../../shared/src/db/schema"
+
+const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite") as typeof import("node:sqlite")
+const requireShared = createRequire(import.meta.resolve("@alook/shared"))
+const { is } = requireShared("drizzle-orm") as { is: (value: unknown, kind: unknown) => boolean }
+const { SQLiteTable, getTableConfig, SQLiteSyncDialect } = requireShared("drizzle-orm/sqlite-core") as {
+ SQLiteTable: unknown
+ SQLiteSyncDialect: new () => { sqlToQuery: (value: unknown) => { sql: string; params: unknown[] } }
+ getTableConfig: (table: unknown) => { name: string; columns: Array<{ name: string; primary: boolean; isUnique: boolean; default?: unknown; getSQLType: () => string }>; primaryKeys: Array<{ columns: Array<{ name: string }> }>; uniqueConstraints: Array<{ columns: Array<{ name: string }> }>; indexes: Array<{ config: { name: string; unique: boolean; columns: Array<{ name?: string }>; where?: unknown } }> }
+}
+
+export function createCommunitySqliteDb() {
+ const sqlite = new DatabaseSync(":memory:")
+ const dialect = new SQLiteSyncDialect()
+ for (const table of [user, ...Object.values({ ...tables, ...machineTables }).filter(value => is(value, SQLiteTable))]) {
+ const config = getTableConfig(table)
+ sqlite.exec(`CREATE TABLE "${config.name}" (${config.columns.map(column => {
+ const value = column.default
+ const initial = typeof value === "string" ? " DEFAULT '" + value.replaceAll("'", "''") + "'" : typeof value === "number" ? ` DEFAULT ${value}` : typeof value === "boolean" ? ` DEFAULT ${Number(value)}` : ""
+ return `"${column.name}" ${column.getSQLType()}${column.primary ? " PRIMARY KEY" : column.isUnique ? " UNIQUE" : ""}${initial}`
+ }).concat(config.primaryKeys.map(key => `PRIMARY KEY (${key.columns.map(column => `"${column.name}"`).join(", ")})`), config.uniqueConstraints.map(key => `UNIQUE (${key.columns.map(column => `"${column.name}"`).join(", ")})`)).join(", ")})`)
+ for (const index of config.indexes) if (index.config.unique) {
+ const columns = index.config.columns.map(column => column.name ? `"${column.name}"` : dialect.sqlToQuery(column).sql).join(", ")
+ const where = index.config.where ? dialect.sqlToQuery(index.config.where) : undefined
+ if (where?.params.length) throw new Error("Test schema index requires literal metadata")
+ sqlite.exec(`CREATE UNIQUE INDEX "${index.config.name}" ON "${config.name}" (${columns})${where ? ` WHERE ${where.sql}` : ""}`)
+ }
+ }
+ sqlite.exec("CREATE UNIQUE INDEX idx_read_state_user_channel ON community_read_state(user_id, channel_id)")
+ sqlite.exec("CREATE UNIQUE INDEX idx_notification_setting_user_server ON community_notification_setting(user_id, server_id) WHERE server_id IS NOT NULL;")
+ sqlite.exec("CREATE UNIQUE INDEX idx_notification_setting_user_channel ON community_notification_setting(user_id, channel_id) WHERE channel_id IS NOT NULL;")
+ const record = { invocations: 0, batches: [] as number[], statements: [] as Array<{ sql: string; bindings: SQLInputValue[] }> }
+ const binding = {
+ prepare(sql: string) {
+ let values: SQLInputValue[] = []
+ const execute = (arrays: boolean, batched = false) => {
+ if (!batched) record.invocations++
+ record.statements.push({ sql, bindings: [...values] })
+ if (values.length > 100) throw new Error("Existing D1 binding limit exceeded")
+ let statement
+ try { statement = sqlite.prepare(sql) } catch (error) { throw new Error(`Test SQL preparation failed: ${sql}`, { cause: error }) }
+ statement.setReturnArrays(arrays)
+ return statement.all(...values)
+ }
+ const prepared = {
+ bind(...bindings: SQLInputValue[]) { values = bindings; return prepared },
+ async raw() { return execute(true) },
+ async all() { return { success: true, results: execute(false) } },
+ async run() { record.invocations++; record.statements.push({ sql, bindings: [...values] }); return { success: true, meta: sqlite.prepare(sql).run(...values) } },
+ async batchResult() { return { success: true, results: execute(false, true) } },
+ }
+ return prepared
+ },
+ async batch(statements: Array<{ batchResult: () => Promise<unknown> }>) {
+ record.invocations++
+ record.batches.push(statements.length)
+ sqlite.exec("BEGIN")
+ try {
+ const results = []
+ for (const statement of statements) results.push(await statement.batchResult())
+ sqlite.exec("COMMIT")
+ return results
+ } catch (error) { sqlite.exec("ROLLBACK"); throw error }
+ },
+ }
+ return { sqlite, db: createDb(binding as unknown as D1Database), record }
+}
diff --git a/src/web/src/test/conversation-entry-fixtures.ts b/src/web/src/test/conversation-entry-fixtures.ts
index e583613ff..68f4729b9 100644
--- a/src/web/src/test/conversation-entry-fixtures.ts
+++ b/src/web/src/test/conversation-entry-fixtures.ts
@@ -1,10 +1,12 @@
-import { normalizeCommunityChannelResource, type CommunityChannelIdentity } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, type CommunityChannelIdentity } from "@alook/shared"
+import { channelResourceFixture, profileResourceFixture } from "./community-resource-fixtures"
import type { CommunityConversationEntryRead } from "@alook/shared"
export function conversationEntryFixture(): CommunityConversationEntryRead {
const at = "2026-10-01T00:00:01.000Z"
return {
- contractVersion: 3, channelId: "c1", viewerId: "viewer", peer: null,
+ contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "c1", viewerId: "viewer", peer: null,
+ profiles: [profileResourceFixture({ id: "peer", name: "Peer", discriminator: "0042", avatarVersion: 5 })],
channel: { id: "c1", type: "text", serverId: "s1", categoryId: null, name: "Channel", topic: "", parentChannelId: null, parentMessageId: null, creatorId: "viewer", position: 0, archived: false, createdAt: at, lastMessageAt: at, messageCount: 1 },
access: { channelId: "c1", canRead: true, canSend: true, canCreateDiscussion: true },
readState: { channelId: "c1", lastReadMessageId: "m1", lastReadAt: at, lastReadSeq: 1 }, readStateRevision: 4,
@@ -19,13 +21,13 @@ export const conversationEntryTarget = { channelId: "c1", serverId: "s1" }
export function forumConversationEntryFixture(channelId = "c1", serverId = "s1", empty = false): CommunityConversationEntryRead {
const base = conversationEntryFixture()
const channel = { ...base.channel, id: channelId, serverId, type: "forum" as const, name: "Forum" }
- return { ...base, channelId, channel, messages: [],
+ return { ...base, channelId, channel, messages: [], profiles: [],
access: { ...base.access, channelId }, readState: { ...base.readState, channelId },
selection: { reason: "tail", anchorMessageId: null }, surfaceReceipt: { channelId, surfaceKind: "forum" },
page: { ...base.page, hasMoreOlder: false, olderCursor: null },
- forumFeed: { contractVersion: 3, channelId, channel,
+ forumFeed: { contractVersion: BUSINESS_SCHEMA_VERSION, channelId, channel,
threads: empty ? [] : [{ ...channel, id: "t1", type: "thread", parentChannelId: channelId, parentMessageId: "m1", name: "Post" }],
- included: { messages: empty ? [] : [{ ...base.messages[0], channelId }], members: [], profiles: [], tags: [], participantCounts: [] },
+ included: { messages: empty ? [] : [{ ...base.messages[0], channelId }], members: [], profiles: empty ? [] : base.profiles, tags: [], participantCounts: [] },
page: { hasMore: false, nextCursor: null },
},
}
@@ -39,13 +41,13 @@ export function dmConversationEntryFixture(): CommunityConversationEntryRead {
}
export function conversationEntryFromChannel(value: CommunityChannelIdentity, viewerId = "viewer"): CommunityConversationEntryRead {
- const channel = normalizeCommunityChannelResource(value)
- return { contractVersion: 3, channelId: channel.id, viewerId, channel,
+ const channel = channelResourceFixture(value)
+ return { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: channel.id, viewerId, channel,
peer: channel.type === "dm" ? { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0 } : null,
access: { channelId: channel.id, canRead: true, canSend: true, canCreateDiscussion: channel.type === "text" || channel.type === "forum" },
readState: { channelId: channel.id, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }, readStateRevision: 0,
selection: { reason: "tail", anchorMessageId: null }, surfaceReceipt: { channelId: channel.id, surfaceKind: channel.type === "text" ? "channel" : channel.type },
- messages: [], page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 } }
+ messages: [], profiles: [], page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 } }
}
export async function seedConversationEntry(client: import("@tanstack/react-query").QueryClient, entry: CommunityConversationEntryRead, target: import("@/lib/community/conversation-entry").ConversationEntryTarget = { channelId: entry.channelId, serverId: entry.channel.serverId }) {
diff --git a/src/web/src/test/e2e-business-contract.test.ts b/src/web/src/test/e2e-business-contract.test.ts
new file mode 100644
index 000000000..036ca6368
--- /dev/null
+++ b/src/web/src/test/e2e-business-contract.test.ts
@@ -0,0 +1,159 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { protectCommunityJsonResponse, rejectUnknownCommunityContract } from "@/lib/middleware/response-cache"
+import { communityFixtureFetch } from "./e2e-ui/_fixtures/business-contract"
+import { createSeed } from "./e2e-ui/_fixtures/seed"
+import { WEB_URL } from "./e2e-ui/_setup/paths"
+
+vi.mock("./e2e-ui/_fixtures/community-fixture", () => ({ sessionCookie: vi.fn(), userId: vi.fn() }))
+vi.mock("./e2e-ui/_fixtures/manifest", () => ({ manifest: () => ({ users: {} }) }))
+afterEach(() => vi.unstubAllGlobals())
+
+function transport(handler: (request: Request) => Promise<Response> | Response) {
+ const accepted: Request[] = []
+ const fetchMock = vi.fn(async (url: string | URL, options?: RequestInit) => {
+ const request = new Request(url, options)
+ const refused = rejectUnknownCommunityContract(request)
+ if (!refused) accepted.push(request)
+ return protectCommunityJsonResponse(request, refused ?? await handler(request))
+ })
+ vi.stubGlobal("fetch", fetchMock)
+ return { accepted, fetchMock }
+}
+
+describe("owned fixture current protocol", () => {
+ it("connects an explicit current fixture request through actual guard and confirmation", async () => {
+ const h = transport(() => Response.json({ id: "receipt" }))
+ expect(await (await communityFixtureFetch(`${WEB_URL}/api/community/operation`, { method: "POST", headers: { Cookie: "fixture", Origin: WEB_URL } })).json()).toEqual({ id: "receipt" })
+ expect(h.accepted).toHaveLength(1)
+ expect(h.accepted[0].headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ expect(h.accepted[0].headers.get("Cookie")).toBe("fixture")
+ for (const version of [null, BUSINESS_SCHEMA_VERSION - 1]) {
+ const response = await fetch(`${WEB_URL}/api/community/operation`, { headers: version === null ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(version) } })
+ expect(response.status).toBe(400)
+ }
+ expect(h.accepted).toHaveLength(1)
+ })
+ it.each([null, BUSINESS_SCHEMA_VERSION - 1, BUSINESS_SCHEMA_VERSION + 1])("rejects an unconfirmed successful fixture response (%s)", async version => {
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ id: "receipt" }, { headers: version === null ? {} : { [COMMUNITY_CONTRACT_HEADER]: String(version) } })))
+ await expect(communityFixtureFetch(`${WEB_URL}/api/community/operation`)).rejects.toThrow("did not confirm current business version")
+ })
+ it("preserves original failed status and body for the caller's error evidence", async () => {
+ const response = new Response("original failure", { status: 500 })
+ vi.stubGlobal("fetch", vi.fn(async () => response))
+ expect(await communityFixtureFetch(`${WEB_URL}/api/community/operation`)).toBe(response)
+ expect(response.bodyUsed).toBe(false)
+ })
+ it("runs actual server/join/retirement preconditions without accepting a generic400 join", async () => {
+ let joinError = "Already a member"
+ const h = transport(request => {
+ const path = new URL(request.url).pathname
+ if (path.endsWith("/join")) return Response.json({ error: joinError }, { status: 400 })
+ if (path.endsWith("/invites")) return Response.json({ invite: { token: "token" } })
+ if (request.method === "DELETE") return new Response(null, { status: 204 })
+ return Response.json({ server: { id: "server" } }, { status: 201 })
+ })
+ const seed = createSeed({ sessionCookie: () => "fixture-cookie", userId: key => key, users: () => ({ alice: { userId: "alice" }, bob: { userId: "bob" } }) })
+ expect(await seed.seedServer("alice", "current")).toBe("server")
+ await seed.seedJoinServer("alice", "bob", "server")
+ joinError = "Invalid or expired invite"
+ await expect(seed.seedJoinServer("alice", "bob", "server")).rejects.toThrow("Invalid or expired invite")
+ await seed.retireSeedServers("alice", ["server"])
+ expect(h.accepted.map(request => request.method)).toEqual(["POST", "POST", "POST", "POST", "POST", "DELETE"])
+ expect(h.accepted.every(request => request.headers.get(COMMUNITY_CONTRACT_HEADER) === String(BUSINESS_SCHEMA_VERSION))).toBe(true)
+ })
+})
+
+describe("stock caller isolated serialized execution", () => {
+ async function evaluateCallback(file: string, fragment: string) {
+ const { readFileSync } = await import("node:fs")
+ const ts = await import("typescript")
+ const { runInNewContext } = await import("node:vm")
+ const source = readFileSync(new URL(`./e2e-ui/${file}`, import.meta.url), "utf8")
+ const ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true)
+ let callback = ""
+ function visit(node: import("typescript").Node) {
+ if (ts.isCallExpression(node) && /\.evaluate$/.test(node.expression.getText(ast)) && node.arguments[0]?.getText(ast).includes(fragment)) {
+ callback = node.arguments[0].getText(ast)
+ expect(node.arguments[1]?.getText(ast)).toContain("businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS")
+ }
+ ts.forEachChild(node, visit)
+ }
+ visit(ast)
+ expect(callback).not.toBe("")
+ return (fetchImpl: typeof fetch) => runInNewContext(ts.transpileModule(`(${callback})`, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText, { fetch: fetchImpl, Headers }) as (arg: unknown) => Promise<number>
+ }
+ it.each([
+ { file: "29-multi-device-read-state.spec.ts", fragment: "/channels/${channelId}/messages", arg: { channelId: "channel", content: "test" }, method: "POST" },
+ { file: "29-multi-device-read-state.spec.ts", fragment: "/notifications/channel/${channelId}", arg: { value: "channel" }, method: "PUT" },
+ { file: "27-canonical-forum-post-delete.spec.ts", fragment: "/messages/${openerId}", arg: { value: "message" }, method: "DELETE" },
+ ])("executes the actual $method callback in $file without module-scope globals", async ({ file, fragment, arg, method }) => {
+ const { CURRENT_COMMUNITY_FIXTURE_HEADERS } = await import("./e2e-ui/_fixtures/business-contract")
+ const factory = await evaluateCallback(file, fragment)
+ let version = BUSINESS_SCHEMA_VERSION as number
+ const fetchImpl = vi.fn(async (_path: string | URL | Request, _options?: RequestInit) => Response.json({ ok: true }, { status: 201, headers: { [COMMUNITY_CONTRACT_HEADER]: String(version) } }))
+ const callback = factory(fetchImpl)
+ expect(await callback({ ...arg, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })).toBe(201)
+ expect(fetchImpl.mock.calls[0][1]?.method).toBe(method)
+ expect(new Headers(fetchImpl.mock.calls[0][1]?.headers).get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ version--
+ await expect(callback({ ...arg, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })).rejects.toThrow("did not confirm current business version")
+ })
+ it("qualifies current Playwright responses and preserves original failed status", async () => {
+ const { confirmCommunityFixtureApiResponse, CURRENT_COMMUNITY_FIXTURE_HEADERS } = await import("./e2e-ui/_fixtures/business-contract")
+ const good = { ok: () => true, headers: () => CURRENT_COMMUNITY_FIXTURE_HEADERS }
+ expect(await confirmCommunityFixtureApiResponse(Promise.resolve(good))).toBe(good)
+ await expect(confirmCommunityFixtureApiResponse(Promise.resolve({ ok: () => true, headers: () => ({}) }))).rejects.toThrow("did not confirm current business version")
+ const failed = { ok: () => false, headers: () => ({}) }
+ expect(await confirmCommunityFixtureApiResponse(Promise.resolve(failed))).toBe(failed)
+ })
+ it("confirms only the case-insensitive contract header when Playwright merges response cookies", async () => {
+ const { confirmCommunityFixtureApiResponse } = await import("./e2e-ui/_fixtures/business-contract")
+ const good = { ok: () => true, headers: () => ({
+ [COMMUNITY_CONTRACT_HEADER.toUpperCase()]: String(BUSINESS_SCHEMA_VERSION),
+ "set-cookie": "fixture-a=value-a; Path=/\nfixture-b=value-b; Path=/",
+ }) }
+ expect(await confirmCommunityFixtureApiResponse(Promise.resolve(good))).toBe(good)
+ for (const version of [String(BUSINESS_SCHEMA_VERSION - 1), String(BUSINESS_SCHEMA_VERSION + 1)]) {
+ await expect(confirmCommunityFixtureApiResponse(Promise.resolve({ ...good, headers: () => ({ [COMMUNITY_CONTRACT_HEADER.toLowerCase()]: version }) })))
+ .rejects.toThrow("did not confirm current business version")
+ }
+ })
+ it("admits current notification frames in wire order while retaining exact rejected raw frames", async () => {
+ const { EventEmitter } = await import("node:events")
+ const { captureNotificationRequests } = await import("./e2e-ui/_fixtures/community-notification-requests")
+ const { encodeCommunityBrowserEvent, encodeCommunityBrowserEventBatch, prepareCommunityDeliveryEvents } = await import("@alook/shared")
+ const { communityWsEventFixtures } = await import("../../../shared/test/community-ws-events.fixtures")
+ const page = new EventEmitter()
+ const socket = new EventEmitter()
+ const trace = captureNotificationRequests(page as unknown as Parameters<typeof captureNotificationRequests>[0])
+ page.emit("websocket", socket)
+ const before = communityWsEventFixtures["community:presence.update"]
+ const children = [communityWsEventFixtures["community:reaction.remove"], communityWsEventFixtures["community:channel.delete"]]
+ const after = communityWsEventFixtures["community:identity.update"]
+ const first = encodeCommunityBrowserEvent(before), last = encodeCommunityBrowserEvent(after)
+ const prepared = await prepareCommunityDeliveryEvents(children)
+ if (!first.ok || !last.ok || !prepared.ok) throw new Error("Current notification fixtures did not encode")
+ const batch = await encodeCommunityBrowserEventBatch({ events: children, operationId: `message:${"a".repeat(43)}`, operationDigest: prepared.prepared.digest })
+ if (!batch.ok) throw new Error("Current notification batch did not encode")
+ const raw = [first.body, batch.body, last.body, JSON.stringify(before),
+ JSON.stringify({ ...batch.batch, type: "community:events.batch.v2" }),
+ JSON.stringify({ ...batch.batch, wireDigest: "0".repeat(64) }), "{"]
+ trace.phase("wire")
+ for (const payload of raw) socket.emit("framereceived", { payload })
+ trace.phase("after-wire")
+ await trace.framesSettled()
+ expect(trace.rawFrames).toEqual(raw)
+ expect(trace.events).toEqual([before, ...children, after])
+ expect(trace.timeline.filter(item => item.kind === "event").every(item => item.phase === "wire")).toBe(true)
+ expect(trace.timeline.filter(item => item.kind === "event").map(item => item.type)).toEqual([before, ...children, after].map(event => event.type))
+ })
+
+ it("uses an actual current error body for stock retry faults", async () => {
+ const { currentCommunityFixtureError } = await import("./e2e-ui/_fixtures/business-contract")
+ const { apiFetch } = await import("@/lib/api/client")
+ const fault = currentCommunityFixtureError("forced controlled retry", 400)
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(fault.body, { status: fault.status, headers: { ...fault.headers, "Content-Type": fault.contentType } })))
+ await expect(apiFetch("/api/community/billing")).rejects.toMatchObject({ name: "ApiError", status: 400, message: "forced controlled retry" })
+ })
+})
diff --git a/src/web/src/test/e2e-fixture-isolation.test.ts b/src/web/src/test/e2e-fixture-isolation.test.ts
index 31efa4123..1612807af 100644
--- a/src/web/src/test/e2e-fixture-isolation.test.ts
+++ b/src/web/src/test/e2e-fixture-isolation.test.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./e2e-ui/_fixtures/business-contract"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import type { APIResponse, Browser, BrowserContext, Page, Response as PlaywrightResponse, TestFixture, TestInfo } from "@playwright/test"
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs"
@@ -7,6 +8,12 @@ import { cleanupGeometryServers, seedGeometryRoutes } from "./e2e-ui/_fixtures/c
import { seedChannel, seedDm, seedForumThread, seedMessage, seedServer, seedThread } from "./e2e-ui/_fixtures/seed"
import * as legacySeed from "./e2e-ui/_fixtures/seed"
+function communityJsonReply(body: unknown, init?: ResponseInit) {
+ const headers = new Headers(init?.headers)
+ for (const [name, value] of Object.entries(CURRENT_COMMUNITY_FIXTURE_HEADERS)) headers.set(name, value)
+ return Response.json(body, { ...init, headers })
+}
+
type CaseFactory = (roles: readonly ("alice" | "bob" | "carol" | "logout")[]) => Promise<CaseActors>
type ExitOwner = { allocate: CaseFactory; resources: CaseResources }
type Registration = {
@@ -72,7 +79,7 @@ describe("geometry fixture backend resource isolation", () => {
const owned: string[] = []
let nextId = 0
vi.mocked(seedServer).mockImplementation(async () => `owned-${++nextId}`)
- const request = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))
+ const request = vi.fn().mockResolvedValue(new Response(null, { status: 204, headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
vi.stubGlobal("fetch", request)
const routes = await seedGeometryRoutes(owned, legacySeed, (key) => `user-${key}`)
@@ -84,7 +91,7 @@ describe("geometry fixture backend resource isolation", () => {
owned.map((id) => `/api/community/servers/${id}`),
)
expect(request.mock.calls.every(([, options]) => options.method === "DELETE"
- && options.headers.Cookie === "fixture-user=dave")).toBe(true)
+ && new Headers(options.headers).get("Cookie") === "fixture-user=dave")).toBe(true)
})
it("keeps successful IDs available for teardown when later seeding fails", async () => {
@@ -93,7 +100,7 @@ describe("geometry fixture backend resource isolation", () => {
.mockResolvedValueOnce("owned-first")
.mockResolvedValueOnce("owned-second")
.mockRejectedValueOnce(new Error("seed failed"))
- const request = vi.fn().mockResolvedValue(new Response(null, { status: 204 }))
+ const request = vi.fn().mockResolvedValue(new Response(null, { status: 204, headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
vi.stubGlobal("fetch", request)
await expect(seedGeometryRoutes(owned, legacySeed, (key) => `user-${key}`)).rejects.toThrow("seed failed")
@@ -111,7 +118,7 @@ describe("geometry fixture backend resource isolation", () => {
.mockResolvedValueOnce(new Response(null, { status: 400 }))
.mockRejectedValueOnce(new Error("connection failed"))
.mockResolvedValueOnce(new Response(null, { status: 404 }))
- .mockResolvedValueOnce(new Response(null, { status: 204 }))
+ .mockResolvedValueOnce(new Response(null, { status: 204, headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
vi.stubGlobal("fetch", request)
const error = await cleanupGeometryServers(["failed", "disconnected", "already-gone", "remaining"], legacySeed)
@@ -245,7 +252,7 @@ describe("test-scoped case actors and cleanup", () => {
vi.stubGlobal("fetch", vi.fn(async (input: string, options?: RequestInit) => {
const path = new URL(input).pathname
if (path === "/api/ws/token") return emptySessionResponse ?? new Response("Unauthorized", { status: 401 })
- const cookie = (options?.headers as Record<string, string>).Cookie
+ const cookie = new Headers(options?.headers).get("Cookie")!
const actor = actors.get(cookie.split("=")[1])!
if (options?.method === "DELETE") {
const id = path.split("/").at(-1)!
@@ -253,39 +260,39 @@ describe("test-scoped case actors and cleanup", () => {
const found = servers.get(id)
if (found && found.ownerId !== actor.userId) return new Response("{}", { status: 403 })
servers.delete(id)
- return new Response(null, { status: found ? 204 : missingDeleteStatus })
+ return new Response(null, { status: found ? 204 : missingDeleteStatus, headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })
}
if (options?.method === "POST") {
if (path === "/api/community/servers") {
const server = { id: `owned-${++nextServer}`, ownerId: actor.userId }
servers.set(server.id, server)
- if (loseServerResponse) return new Response("invalid server JSON")
- return Response.json({ server })
+ if (loseServerResponse) return new Response("invalid server JSON", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })
+ return communityJsonReply({ server })
}
if (path === "/api/community/channels") {
dmCreated = true
- return Response.json({ conversation: { id: "case-dm" } })
+ return communityJsonReply({ conversation: { id: "case-dm" } })
}
- if (path.endsWith("/friends/request")) return Response.json({ id: "case-friendship" })
- return Response.json({})
+ if (path.endsWith("/friends/request")) return communityJsonReply({ id: "case-friendship" })
+ return communityJsonReply({})
}
- if (path.endsWith("/profile")) return Response.json({ id: actor.userId, name: actor.name, aboutMe: baselineFault === "profile" ? "old account profile" : "", avatarVersion: 0, bannerColor: null, statusEmoji: null, statusText: "" })
+ if (path.endsWith("/profile")) return communityJsonReply({ id: actor.userId, name: actor.name, discriminator: "0042", avatar: null, aboutMe: baselineFault === "profile" ? "old account profile" : "", avatarVersion: 0, bannerColor: null, statusEmoji: null, statusText: null })
if (path === "/api/community/servers") {
- if (serverListFault === "error") return Response.json({ error: "Unavailable" }, { status: 503 })
- if (serverListFault === "missing") return Response.json({})
- if (serverListFault === "stale" || serverListFault === "truncated") return Response.json({ servers: [], [serverListFault]: true })
- if (serverListFault === "malformed") return Response.json({ servers: [{ id: "incomplete-server" }] })
- if (serverListFault === "empty-id") return Response.json({ servers: [{ id: "", ownerId: actor.userId }] })
- return Response.json({ servers: [...servers.values()].filter((server) => server.ownerId === actor.userId) })
+ if (serverListFault === "error") return communityJsonReply({ error: "Unavailable" }, { status: 503 })
+ if (serverListFault === "missing") return communityJsonReply({})
+ if (serverListFault === "stale" || serverListFault === "truncated") return communityJsonReply({ servers: [], [serverListFault]: true })
+ if (serverListFault === "malformed") return communityJsonReply({ servers: [{ id: "incomplete-server" }] })
+ if (serverListFault === "empty-id") return communityJsonReply({ servers: [{ id: "", ownerId: actor.userId }] })
+ return communityJsonReply({ servers: [...servers.values()].filter((server) => server.ownerId === actor.userId) })
}
- if (path.endsWith("/read-state")) return Response.json({ readStates: dmCreated ? [{ channelId: "case-dm", lastReadSeq: dmCursor }] : [] })
+ if (path.endsWith("/read-state")) return communityJsonReply({ readStates: dmCreated ? [{ channelId: "case-dm", lastReadSeq: dmCursor }] : [] })
if (path.endsWith("/attention")) {
- if (baselineFault === "error") return Response.json({ error: "Unavailable" }, { status: 503 })
- if (baselineFault === "malformed") return Response.json({ scopes: null, items: [] })
- return Response.json({ scopes: [], items: [], stale: baselineFault === "stale", truncated: baselineFault === "truncated" })
+ if (baselineFault === "error") return communityJsonReply({ error: "Unavailable" }, { status: 503 })
+ if (baselineFault === "malformed") return communityJsonReply({ scopes: null, items: [] })
+ return communityJsonReply({ scopes: [], items: [], stale: baselineFault === "stale", truncated: baselineFault === "truncated" })
}
const field = path.endsWith("/dms") ? "conversations" : path.endsWith("/server-folders") ? "folders" : path.endsWith("/marks") ? "marked" : path.endsWith("/accepted") ? "friends" : path.endsWith("/pending") ? "pending" : "blocked"
- return Response.json({ [field]: [] })
+ return communityJsonReply({ [field]: [] })
}))
})
@@ -558,9 +565,9 @@ describe("test-scoped case actors and cleanup", () => {
})
it.each([
- ["SDK JSON 401", () => Response.json({ code: "UNAUTHORIZED", message: "SDK failure" }, { status: 401 })],
+ ["SDK JSON 401", () => communityJsonReply({ code: "UNAUTHORIZED", message: "SDK failure" }, { status: 401 })],
["server failure", () => new Response("Unavailable", { status: 503 })],
- ["live session", () => Response.json({ userId: "still-live", token: "test-token" })],
+ ["live session", () => communityJsonReply({ userId: "still-live", token: "test-token" })],
] as const)("does not retire a session after %s", async (_label, response) => {
emptySessionResponse = response()
await expect(run(info("unproved-session"), async (create) => {
diff --git a/src/web/src/test/e2e-public-static-qa.test.ts b/src/web/src/test/e2e-public-static-qa.test.ts
index 57d92ff62..ccce83441 100644
--- a/src/web/src/test/e2e-public-static-qa.test.ts
+++ b/src/web/src/test/e2e-public-static-qa.test.ts
@@ -106,6 +106,45 @@ describe("public static QA immutable input and phase controls", () => {
expect((globalThis as Record<symbol, unknown>)[sentinel]).toBeUndefined()
})
+ it.each([
+ 'var q=p??[];new W({precacheEntries:q})',
+ 'var urls=p.map(e=>typeof e==="string"?e:e.url);new W({precacheEntries:p})',
+ 'var q=p??[];var shells=q.map(e=>typeof e==="string"?e:e.url).filter(u=>shellHash(u));if(shells.length!==1)throw new Error("shell required");var shell=shells[0];new W({precacheEntries:q})',
+ ])("extracts immutable catalogues through emitted shell reads: %s", body => {
+ expect(builtPrecacheEntries(`(()=>{var p=[{url:"/community-shell/actual",revision:"hash"}];${body}})()`)).toEqual([{ url: "/community-shell/actual", revision: "hash" }])
+ })
+
+ it("keeps shell reads primitive and rejects escaping or mutated catalogue/guard inputs", () => {
+ const prefix = 'var p=[{url:"/shell",revision:null}];'
+ const suffix = 'new W({precacheEntries:p})'
+ const invalid = [
+ 'var q=p??other;',
+ 'var q=p??[{}];',
+ 'p.map(e=>e);',
+ 'p.map(e=>({url:e.url}));',
+ 'p.map(e=>mutate(e));',
+ 'p.map(e=>{e.url="bad";return e.url});',
+ 'p.map((e=escape(p))=>e.url);',
+ 'p.map(async e=>e.url);',
+ 'p.map(e=>typeof e==="string"?e:escape(e));',
+ 'p.map(e=>e.url,escape);',
+ 'var q=p??[];q.push({url:"/bad",revision:null});',
+ 'var shells=p.map(e=>e.url).filter(Boolean);if(shells.length!==1){sideEffect();throw new Error("bad")}',
+ 'var shells=p.map(e=>e.url).filter(Boolean);if(shells.length!==1)throw new Error("bad");else sideEffect();',
+ 'var shells=["/fake"];if(shells.length!==1)throw new Error("bad");',
+ 'var shells=p.map(e=>e.url).filter(Boolean);shells=[];if(shells.length!==1)throw new Error("bad");',
+ 'var shells=p.map(e=>e.url).filter(Boolean);shells[0]="bad";if(shells.length!==1)throw new Error("bad");',
+ 'var shells=p.map(e=>e.url).filter(Boolean);escape(shells);if(shells.length!==1)throw new Error("bad");',
+ 'Array.prototype.map=function(){return this};p.map(e=>e.url);',
+ 'var prototype=Array.prototype;prototype.map=escape;p.map(e=>e.url);',
+ 'if(other)throw new Error("bad");',
+ ]
+ for (const body of invalid) expect(() => builtPrecacheEntries(`(()=>{${prefix}${body}${suffix}})()`), body).toThrow("unambiguous")
+ for (const map of ['e=>e.url', 'e=>typeof e!="string"?e.url:e']) {
+ expect(builtPrecacheEntries(`(()=>{${prefix}var shells=p.map(${map}).filter(Boolean);if(1!=shells.length){throw new Error("shell")};var url=shells[0];${suffix}})()`)).toEqual([{url:"/shell",revision:null}])
+ }
+ })
+
it("resolves the real memoized bundler initializer only after its unchanged factory is called directly", () => {
const factory = '(e,t,s)=>()=>{if(s)throw s[0];try{return e&&(t=e(e=0)),t}catch(r){throw s=[r],r}}'
const array = '[{url:"/real",revision:"revision"}]'
@@ -438,7 +477,7 @@ describe("original-path forensic evidence", () => {
const actors = { sessionCookie: () => "unit-private-cookie" } as unknown as Parameters<typeof qaApi>[0]
await expect(qaApi(actors, observed.resources, "alice", "/api/community/machines")).rejects.toThrow("QA GET /api/community/machines returned 500")
expect(fetchMock).toHaveBeenCalledTimes(1)
- expect(fetchMock.mock.calls[0]![1]).toMatchObject({ headers: { Cookie: "unit-private-cookie" } })
+ expect(new Headers(fetchMock.mock.calls[0]![1]?.headers).get("Cookie")).toBe("unit-private-cookie")
expect(json).not.toHaveBeenCalled()
await observed.flush()
const snapshot = JSON.parse(observed.attachments[0]!.body)
@@ -528,3 +567,42 @@ describe("original-path forensic evidence", () => {
expect(order).toEqual(["terminate", "terminate"])
})
})
+
+describe("current persistence fixture byte ownership", () => {
+ async function disk() {
+ const { IDBFactory } = await import("fake-indexeddb")
+ vi.stubGlobal("indexedDB", new IDBFactory())
+ const { createStore, set, get } = await import("idb-keyval")
+ const store = createStore("keyval-store", "keyval")
+ const page = { evaluate: <T, A>(fn: (arg: A) => Promise<T>, argument: A) => fn(argument) } as unknown as import("@playwright/test").Page
+ return { page, put: (key: string, value: unknown) => set(key, value, store), read: (key: string) => get(key, store) }
+ }
+ it("captures current both-domain payloads and inserts only explicitly artificial retirement negatives", async () => {
+ const { BUSINESS_SCHEMA_VERSION } = await import("@alook/shared")
+ const { deviceSnapshot, insertArtificialRetiredResidual } = await import("./e2e-ui/_fixtures/public-static-qa")
+ const h = await disk(), userId = "fixture", device = crypto.randomUUID(), account = crypto.randomUUID()
+ const key = `alook:business:v${BUSINESS_SCHEMA_VERSION}:${userId}:client`
+ const payload = JSON.stringify({ version: BUSINESS_SCHEMA_VERSION, buster: String(BUSINESS_SCHEMA_VERSION), timestamp: 123, clientState: { queries: [], mutations: [] }, channelFences: [], ownerEpochs: { device, account } })
+ await h.put("alook:qc:device-epoch", device); await h.put(`alook:qc:cache:${userId}:account-epoch`, account)
+ await h.put(`alook:qc:cache:${userId}:account-epoch:channels`, new Map())
+ await h.put(key, payload); await h.put(`alook:business:v${BUSINESS_SCHEMA_VERSION}:${userId}:application:client`, payload)
+ const captured = await deviceSnapshot(h.page)
+ expect(captured.payloadKeys).toHaveLength(2)
+ const result = await insertArtificialRetiredResidual(h.page, userId, captured)
+ expect(result.preparation).toContain("artificial")
+ for (const written of result.keys) expect(await h.read(written)).toBe(payload)
+ const map = await h.read(`alook:qc:cache:${userId}:account-epoch:channels`) as Map<string, unknown>
+ expect(map.get(result.channelFixture.channelId)).toEqual({ epoch: result.channelFixture.epoch, deleted: true })
+ expect(result.sha256).toBe(createHash("sha256").update(payload).digest("hex"))
+ })
+ it("refuses an unbound or old captured envelope before writing residual bytes", async () => {
+ const { BUSINESS_SCHEMA_VERSION } = await import("@alook/shared")
+ const { insertArtificialRetiredResidual } = await import("./e2e-ui/_fixtures/public-static-qa")
+ const h = await disk(), userId = "fixture", epoch = crypto.randomUUID()
+ for (const body of [{ version: BUSINESS_SCHEMA_VERSION - 1, buster: String(BUSINESS_SCHEMA_VERSION - 1), ownerEpochs: { device: epoch, account: "account" } }, { version: BUSINESS_SCHEMA_VERSION, buster: String(BUSINESS_SCHEMA_VERSION) }]) {
+ const captured = { epoch, payloadKeys: [], records: [{ key: `alook:business:v${BUSINESS_SCHEMA_VERSION}:${userId}:client`, encoded: JSON.stringify(JSON.stringify({ ...body, clientState: {}, channelFences: [] })) }, { key: `alook:qc:cache:${userId}:account-epoch`, encoded: JSON.stringify("account") }] }
+ await expect(insertArtificialRetiredResidual(h.page, userId, captured)).rejects.toThrow("not bound to the current business owner")
+ expect(await h.read(`alook:business:v${BUSINESS_SCHEMA_VERSION}:${userId}:client`)).toBeUndefined()
+ }
+ })
+})
diff --git a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
index 0af62c6b1..13d8d7821 100644
--- a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
+++ b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts
@@ -1,3 +1,4 @@
+import { currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Request } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -234,11 +235,7 @@ test("server → channel → message", async ({ caseActors, caseResources }) =>
sendBodies.push(route.request().postDataJSON())
pendingSendIntercepted = true
await pendingSendGate
- await route.fulfill({
- status: 500,
- contentType: "application/json",
- body: JSON.stringify({ error: "forced staging rejection probe" }),
- })
+ await route.fulfill(currentCommunityFixtureError("forced staging rejection probe", 500))
pendingSendCompleted = true
})
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 b352657d4..c2c4092f0 100644
--- a/src/web/src/test/e2e-ui/04-dm.spec.ts
+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { currentCommunityFixtureError, CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import type { Frame } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -152,7 +154,7 @@ test.describe("direct messages", () => {
await entrySettled
const permission = await entryResponse
expect(permission.status()).toBe(200)
- expect(permission.headers()["x-alook-community-contract"]).toBe("3")
+ expect(permission.headers()[COMMUNITY_CONTRACT_HEADER.toLowerCase()]).toBe(String(BUSINESS_SCHEMA_VERSION))
const resource = await permission.json()
expect(resource.channel.id).toBe(dmId)
expect(resource.access).toMatchObject({ channelId: dmId, canRead: true, canSend: true })
@@ -192,12 +194,11 @@ test.describe("direct messages", () => {
const entryPattern = (url: URL) => url.pathname === `/api/community/channels/${missingDmId}/messages` && url.searchParams.get("entry") === "1"
await alice.page.route(dmsPattern, async (route) => {
canonicalDmsGets += 1
- await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ conversations: [] }) })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, contentType: "application/json", body: JSON.stringify({ conversations: [] }) })
})
await alice.page.route(entryPattern, async (route) => {
entryGets += 1
- await route.fulfill({ status: entryGets === 1 ? 503 : 404,
- contentType: "application/json", body: JSON.stringify({ error: entryGets === 1 ? "temporary" : "missing" }) })
+ await route.fulfill(currentCommunityFixtureError(entryGets === 1 ? "temporary" : "missing", entryGets === 1 ? 503 : 404))
})
try {
diff --git a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts
index 36881b342..4b6c248ad 100644
--- a/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts
+++ b/src/web/src/test/e2e-ui/06-channel-member-admin.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -162,7 +163,7 @@ test.describe("channel & member admin", () => {
await toggle.click()
await expect(row).toBeVisible()
expect(responses).toEqual([200])
- const messages = await page.request.get(`/api/community/channels/${privateId}/messages`)
+ const messages = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${privateId}/messages`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(messages.status()).toBe(403)
await page.getByTestId(tid.settingsTab("members")).click()
await expectFiniteMembersFrame()
@@ -182,7 +183,7 @@ test.describe("channel & member admin", () => {
await page.getByTestId(tid.serverSettingsOpen).click()
await expect(page.getByTestId(tid.settingsShell)).toHaveCount(0)
await expect(page.getByTestId(tid.settingsTab("channels"))).toHaveCount(0)
- const result = await page.request.get(`/api/community/servers/${serverId}/channels/admin`)
+ const result = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/servers/${serverId}/channels/admin`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(result.status()).toBe(403)
})
})
diff --git a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts
index a40b7602c..40b19c4a3 100644
--- a/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts
+++ b/src/web/src/test/e2e-ui/10-eject-nav-auth.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"
import { test, expect } from "./_fixtures/case-fixture"
@@ -55,7 +56,7 @@ test.describe("eject, navigation & logout", () => {
const publicDocumentResponse = await page.request.get("/c", { maxRedirects: 0 })
expect(publicDocumentResponse.status()).toBe(200)
expectPublicCommunityDocument(await publicDocumentResponse.text())
- const protectedResponse = await page.request.get("/api/community/servers", { maxRedirects: 0 })
+ const protectedResponse = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/servers", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, maxRedirects: 0 }))
expect(protectedResponse.status()).toBe(401)
await page.goto("/c")
await expect(page).toHaveURL(/\/sign-in\?redirect=%2Fc$/)
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 4426806fc..6253e12a7 100644
--- a/src/web/src/test/e2e-ui/13-mentions.spec.ts
+++ b/src/web/src/test/e2e-ui/13-mentions.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, communityFixtureFetch, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
import { composerEditable } from "./_fixtures/actions"
@@ -75,14 +76,14 @@ test.describe("mentions — mandatory discriminator", () => {
const sent: Array<{ id: string; content: string; mentionType?: string }> = []
async function participants(): Promise<string[]> {
- const response = await page.request.get(`/api/community/channels/${threadId}/members`)
+ const response = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${threadId}/members?relation=notify`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.status()).toBe(200)
const payload = await response.json() as { members: Array<{ userId: string }> }
return payload.members.map((member) => member.userId).sort()
}
async function attention(role: "bob" | "carol") {
- const response = await fetch(new URL("/api/community/users/me/attention?limit=200", page.url()), {
+ const response = await communityFixtureFetch(new URL("/api/community/users/me/attention?limit=200", page.url()), {
headers: { Cookie: actors.sessionCookie(role) },
})
expect(response.status).toBe(200)
@@ -144,9 +145,9 @@ test.describe("mentions — mandatory discriminator", () => {
expect(outgoing.mentionType).toBe(mentionType)
const created = await response.json() as { message: { id: string; content: string } }
expect(created.message.content).toBe(content)
- const persisted = await page.request.get(`/api/community/messages/${created.message.id}`)
+ const persisted = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/messages/${created.message.id}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(persisted.status()).toBe(200)
- expect(await persisted.json()).toMatchObject({ id: created.message.id, content, channelId: threadId })
+ expect((await persisted.json()).message).toMatchObject({ id: created.message.id, content, channelId: threadId })
const body = threadSurface.getByTestId(tid.message(created.message.id)).locator("[data-community-message-body]")
await expect(body).toBeVisible()
await expect(editable).toHaveText("")
@@ -185,9 +186,9 @@ test.describe("mentions — mandatory discriminator", () => {
expect(await attention("carol")).toEqual([broadcast.id])
expect(await participants()).toEqual([actors.userId("alice"), actors.userId("bob")].sort())
- const explicit = await page.request.post(`/api/community/channels/${threadId}/messages`, {
+ const explicit = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${threadId}/messages`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
data: { content: "explicit API broadcast without body token", mentionType: "everyone" },
- })
+ }))
expect(explicit.status()).toBe(201)
const explicitBody = await explicit.json() as { message: { id: string } }
expect(await attention("carol")).toEqual(expect.arrayContaining([broadcast.id, explicitBody.message.id]))
@@ -357,17 +358,17 @@ test.describe("mentions — mandatory discriminator", () => {
const { page } = await asUser("alice")
for (const bad of ["Ann#1234", "bad@name", "line\nbreak"]) {
- const res = await page.request.patch("/api/community/users/me/profile", {
- headers: { "Content-Type": "application/json" },
+ const res = await confirmCommunityFixtureApiResponse(page.request.patch("/api/community/users/me/profile", {
+ headers: { "Content-Type": "application/json", ...CURRENT_COMMUNITY_FIXTURE_HEADERS },
data: { name: bad },
- })
+ }))
expect(res.status()).toBe(400)
}
// A valid spaced name still saves.
- const ok = await page.request.patch("/api/community/users/me/profile", {
- headers: { "Content-Type": "application/json" },
+ const ok = await confirmCommunityFixtureApiResponse(page.request.patch("/api/community/users/me/profile", {
+ headers: { "Content-Type": "application/json", ...CURRENT_COMMUNITY_FIXTURE_HEADERS },
data: { name: "Jane Roe" },
- })
+ }))
expect(ok.status()).toBe(200)
})
})
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 64c6d9c4e..c0121014d 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
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -135,7 +136,7 @@ test.describe("DM presence stability on refresh", () => {
const bob = await asUser("bob")
await expect.poll(async () => {
- const response = await bob.page.request.get(`/api/community/servers/${serverId}/presence`)
+ const response = await confirmCommunityFixtureApiResponse(bob.page.request.get(`/api/community/servers/${serverId}/presence`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
if (!response.ok()) return false
const body = await response.json() as { online?: string[] }
return body.online?.includes(userId("alice")) ?? false
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 22067bd44..4a5fc8217 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
@@ -1,3 +1,4 @@
+import { currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Locator, Page } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -171,7 +172,7 @@ test.describe("mentions — candidate scope", () => {
await page.route(`**/api/community/channels/${privateChannelId}/members?*`, async (route) => {
if (new URL(route.request().url()).searchParams.get("relation") !== "access") return route.continue()
accessReads += 1
- if (failAccess) return route.fulfill({ status: 500, json: { error: "controlled access read failure" } })
+ if (failAccess) return route.fulfill(currentCommunityFixtureError("controlled access read failure", 500))
return route.continue()
})
await page.goto(`/c/channels/${serverId}/${privateChannelId}`)
diff --git a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
index 17404bfa6..3563c6e1a 100644
--- a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
+++ b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -19,7 +20,7 @@ test("anchored channel jumps to the newest tail with one request", async ({ case
for (let index = 1; index <= 36; index++) {
latestId = await seedMessage(index % 2 === 0 ? "bob" : "carol", channelId, `newer message ${index}`)
}
- const readResponse = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ const readResponse = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
method: "PUT",
headers: {
Cookie: sessionCookie("alice"),
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 6739ad616..a1a09de01 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
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import type { Page } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { holdRoute } from "./_fixtures/held-route"
@@ -8,7 +10,7 @@ import type { CaseActors } from "./_fixtures/case-fixture"
async function prepareCase(_actors: CaseActors) {
async function participantUserIds(page: Page, channelId: string): Promise<string[]> {
- const response = await page.request.get(`/api/community/channels/${channelId}/members`)
+ const response = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${channelId}/members?relation=notify`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.status()).toBe(200)
const payload = await response.json() as {
members: Array<{
@@ -83,9 +85,9 @@ async function strictSidebar(page: Page, serverId: string, retainId?: string) {
include: "parentMessage",
})
if (retainId) params.set("retainId", retainId)
- const response = await page.request.get(
- `/api/community/servers/${serverId}/channels?${params.toString()}`,
- )
+ const response = await confirmCommunityFixtureApiResponse(page.request.get(
+ `/api/community/servers/${serverId}/channels?${params.toString()}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))
expect(response.status()).toBe(200)
return await response.json() as {
canonicalChannels: Array<{ id: string }>
@@ -430,7 +432,7 @@ test.describe("forum sidebar Stage B request shape", () => {
warmVisibleMs = Date.now() - clickStartedAt
expect(requests.filter((url) => isConversationEntryRequest(url, threadId))).toHaveLength(1)
const entryResponse = await firstChildEntry
- expect(entryResponse.headers()["x-alook-community-contract"]).toBe("3")
+ expect(entryResponse.headers()[COMMUNITY_CONTRACT_HEADER.toLowerCase()]).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(await entryResponse.json()).toMatchObject({
channelId: threadId, channel: { id: threadId, serverId, archived: false },
access: { channelId: threadId, canRead: true },
@@ -545,9 +547,9 @@ test.describe("forum sidebar archived opener projection", () => {
expect(archivedProjection.canonicalChannels.map(({ id }) => id)).toEqual(
initialIds.filter((id) => id !== archivedId).concat(refillId),
)
- const exact = await viewer.page.request.get(`/api/community/channels/${archivedId}`)
+ const exact = await confirmCommunityFixtureApiResponse(viewer.page.request.get(`/api/community/channels/${archivedId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(exact.status()).toBe(200)
- expect((await exact.json() as { archived: boolean | number }).archived).toBeFalsy()
+ expect((await exact.json() as { channel: { archived: boolean } }).channel.archived).toBeFalsy()
await viewer.page.goto(`/c/channels/${serverId}/${archivedId}`)
await expect(childPanel(viewer.page).getByRole("heading", { name: titles.get(archivedId)! })).toBeVisible({
diff --git a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
index efb53637e..ff85ab0cd 100644
--- a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
+++ b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"
import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
@@ -31,7 +32,7 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",
)
}
- const readResponse = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ const readResponse = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
method: "PUT",
headers: {
Cookie: sessionCookie("alice"),
@@ -153,7 +154,7 @@ test("New reading near the tail survives peer and remote-self messages until the
await seedJoinServer("alice", "carol", serverId)
let readThroughId = ""
for (let index = 0; index < 18; index++) readThroughId = await seedMessage("alice", channelId, `read ${index}`)
- const read = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ const read = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
method: "PUT",
headers: { Cookie: sessionCookie("alice"), "Content-Type": "application/json", Origin: WEB_URL },
body: JSON.stringify({ lastReadMessageId: readThroughId }),
diff --git a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
index 5d13c1ee8..8ffd5c1d5 100644
--- a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
+++ b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
@@ -1,7 +1,8 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { composerEditable, expectMessageVisible, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"
import type { Frame, Page, Request, Response as PlaywrightResponse } from "@playwright/test"
-import { COMMUNITY_CONTRACT_VERSION, CommunityMessageResourceSchema, requestedCommunityContract } from "@alook/shared"
+import { COMMUNITY_CONTRACT_VERSION, communityBrowserEventBatchType, CommunityMessageResourceSchema, requestedCommunityContract } from "@alook/shared"
import { decodeCommunityReadResponse } from "@/lib/community/read-response"
import type { MessagesPage } from "@/lib/community/models/message"
@@ -72,9 +73,9 @@ test.describe("committed message delivery QA", () => {
const carolProxy = await proxyCommunityWebSockets(carol.context)
await gotoAfterUserWsAuth(carol.page, `/c/channels/${serverId}/${forumId}`)
await expect(carol.page.getByTestId(tid.forumThreadCard(threadId))).toBeVisible({ timeout: 20_000 })
- const membersBefore = await carol.page.request.get(`/api/community/channels/${threadId}/members`)
+ const membersBefore = await confirmCommunityFixtureApiResponse(carol.page.request.get(`/api/community/channels/${threadId}/members?relation=notify`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(membersBefore.status()).toBe(200)
- expect((await membersBefore.json() as { members: Array<{ id: string }> }).members.map((member) => member.id)).not.toContain(userId("carol"))
+ expect((await membersBefore.json() as { members: Array<{ userId: string }> }).members.map((member) => member.userId)).not.toContain(userId("carol"))
const frameStart = carolProxy.frames.length
const bob = await asUser("bob")
@@ -94,9 +95,9 @@ test.describe("committed message delivery QA", () => {
expect(carolProxy.frames.slice(frameStart).flatMap(communityFrameEvents).filter((event) =>
event.channelId === threadId && event.userId === userId("carol")
&& (event.type === "community:unread.bump" || event.type === "community:mention.create" || event.type === "community:channel.member_add"))).toEqual([])
- const membersAfter = await carol.page.request.get(`/api/community/channels/${threadId}/members`)
+ const membersAfter = await confirmCommunityFixtureApiResponse(carol.page.request.get(`/api/community/channels/${threadId}/members?relation=notify`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(membersAfter.status()).toBe(200)
- expect((await membersAfter.json() as { members: Array<{ id: string }> }).members.map((member) => member.id)).not.toContain(userId("carol"))
+ expect((await membersAfter.json() as { members: Array<{ userId: string }> }).members.map((member) => member.userId)).not.toContain(userId("carol"))
await expect(carol.page.getByText(body, { exact: false })).toHaveCount(0)
})
@@ -148,7 +149,7 @@ test.describe("committed message delivery QA", () => {
const repaired = await expectRepairedMessage(repairResponses, channelId, missing)
expect(proxy.heldCount()).toBe(1)
const heldBatch = proxy.frames.find((frame) => messageFrame(frame, channelId, missing))
- expect(heldBatch?.type).toBe("community:events.batch.v2")
+ expect(heldBatch?.type).toBe(communityBrowserEventBatchType())
expect(communityFrameEvents(heldBatch!).some((event) =>
event.type === "community:mention.create")).toBe(true)
expect(communityFrameEvents(heldBatch!).find((event) => event.type === "community:message.create")?.message)
@@ -160,7 +161,7 @@ test.describe("committed message delivery QA", () => {
await expect(bob.page.getByText(missing, { exact: false })).toHaveCount(1)
expect(proxy.frames.filter((frame) => messageFrame(frame, channelId, missing))).toHaveLength(1)
await expect.poll(async () => {
- const response = await bob.page.request.get("/api/community/servers")
+ const response = await confirmCommunityFixtureApiResponse(bob.page.request.get("/api/community/servers", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
const data = await response.json() as { servers: Array<{ id: string; mentions: number }> }
const authoritative = data.servers.find((server) => server.id === serverId)?.mentions ?? 0
const badge = bob.page.getByTestId(tid.railUnreadBadge(serverId))
@@ -280,7 +281,7 @@ test.describe("committed message delivery QA", () => {
isCommunityBatchFrame(frame) && messageFrame(frame, channelId, body))
expect(batches).toHaveLength(1)
const batch = batches[0]!
- expect(batch.type).toBe("community:events.batch.v2")
+ expect(batch.type).toBe(communityBrowserEventBatchType())
expect(batch.operationId).toMatch(/^message:[A-Za-z0-9_-]{43}$/)
expect(batch.operationDigest).toMatch(/^[0-9a-f]{64}$/)
expect(batch.wireDigest).toMatch(/^[0-9a-f]{64}$/)
diff --git a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
index e480e4ecd..bbd7de942 100644
--- a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
+++ b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./_fixtures/business-contract"
import type { Locator, Page, TestInfo } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -9,7 +10,7 @@ import type { CaseActors } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors) {
const { sessionCookie } = actors
async function seedTags(forumId: string, threadId: string, tags: string[]): Promise<void> {
- const listResponse = await fetch(`${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: { Cookie: sessionCookie("bob"), Origin: WEB_URL } })
+ const listResponse = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: { Cookie: sessionCookie("bob"), Origin: WEB_URL } })
expect(listResponse.ok).toBe(true)
const page = await listResponse.json() as {
threads: Array<{
@@ -19,7 +20,7 @@ async function prepareCase(actors: CaseActors) {
}
const openerMessageId = page.threads.find((thread) => thread.id === threadId)?.parentMessageId
expect(openerMessageId).toBeTruthy()
- const tagResponse = await fetch(`${WEB_URL}/api/community/messages/${openerMessageId}/tags`, {
+ const tagResponse = await communityFixtureFetch(`${WEB_URL}/api/community/messages/${openerMessageId}/tags`, {
method: "PUT",
headers: {
Cookie: sessionCookie("bob"),
diff --git a/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts b/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts
index e62c6f9f8..6c0f1f9c8 100644
--- a/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts
+++ b/src/web/src/test/e2e-ui/27-canonical-forum-post-delete.spec.ts
@@ -1,3 +1,5 @@
+import { decodeCommunityBrowserEvent, type CommunityWsEvent } from "@alook/shared"
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, communityFixtureFetch } from "./_fixtures/business-contract"
import type { Page, WebSocket } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -9,7 +11,7 @@ import type { CaseActors } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors) {
const { sessionCookie } = actors
async function resolveOpener(forumId: string, childId: string): Promise<string> {
- const response = await fetch(`${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })
expect(response.status).toBe(200)
const body = await response.json() as {
threads: Array<{
@@ -24,13 +26,7 @@ async function prepareCase(actors: CaseActors) {
return { resolveOpener }
}
-type ChannelDeleteFrame = {
- type: "community:channel.delete"
- serverId: string
- channelId: string
- parentChannelId?: string
- parentMessageId?: string
-}
+type ChannelDeleteFrame = Extract<CommunityWsEvent, { type: "community:channel.delete" }>
function captureChannelDeletes(page: Page) {
const frames: ChannelDeleteFrame[] = []
@@ -39,8 +35,8 @@ function captureChannelDeletes(page: Page) {
sockets.add(socket)
socket.on("framereceived", ({ payload }) => {
try {
- const frame = JSON.parse(payload.toString()) as ChannelDeleteFrame
- if (frame.type === "community:channel.delete") frames.push(frame)
+ const admitted = decodeCommunityBrowserEvent(JSON.parse(payload.toString()))
+ if (admitted.ok && admitted.event.type === "community:channel.delete") frames.push(admitted.event)
} catch {}
})
})
@@ -97,16 +93,16 @@ test("canonical forum-post delete converges author, manager, private WS, and act
await gotoAfterUserWsAuth(carol.page, "/c")
await expect(bob.page.getByTestId(tid.forumThreadCard(authorChildId))).toBeVisible({ timeout: 20_000 })
- const unauthorizedStatus = await carol.page.evaluate(async (openerId) => {
- const response = await fetch(`/api/community/messages/${openerId}`, { method: "DELETE" })
+ const unauthorizedStatus = await carol.page.evaluate(async ({ value: openerId, businessHeaders }) => {
+ const response = await fetch(`/api/community/messages/${openerId}`, { headers: businessHeaders, method: "DELETE" }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, authorOpenerId)
+ }, { value: authorOpenerId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(unauthorizedStatus).toBe(403)
- const legacyStatus = await bob.page.evaluate(async (childId) => {
- const response = await fetch(`/api/community/channels/${childId}`, { method: "DELETE" })
+ const legacyStatus = await bob.page.evaluate(async ({ value: childId, businessHeaders }) => {
+ const response = await fetch(`/api/community/channels/${childId}`, { headers: businessHeaders, method: "DELETE" }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, authorChildId)
+ }, { value: authorChildId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(legacyStatus).toBe(409)
await expect(bob.page.getByTestId(tid.forumThreadCard(authorChildId))).toBeVisible()
@@ -129,10 +125,10 @@ test("canonical forum-post delete converges author, manager, private WS, and act
await bob.page.reload()
await expect(bob.page.getByTestId(tid.forumThreadCard(authorChildId))).toHaveCount(0)
- const deletedChildStatus = await bob.page.evaluate(async (childId) => {
- const response = await fetch(`/api/community/channels/${childId}`)
+ const deletedChildStatus = await bob.page.evaluate(async ({ value: childId, businessHeaders }) => {
+ const response = await fetch(`/api/community/channels/${childId}`, { headers: businessHeaders }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, authorChildId)
+ }, { value: authorChildId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(deletedChildStatus).toBe(404)
await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${managerChildId}`)
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 0440bcf88..b63c53ead 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
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, communityFixtureFetch, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { COMMUNITY_CONTRACT_VERSION, WS_EVENTS } from "@alook/shared"
import { test, expect } from "./_fixtures/case-fixture"
import { captureNotificationRequests, gotoAfterNotificationStartup } from "./_fixtures/community-notification-requests"
@@ -9,7 +10,7 @@ import type { CaseActors } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors) {
const { sessionCookie } = actors
async function mutate(path: string, method: string, body?: unknown) {
- return fetch(`${WEB_URL}${path}`, {
+ return communityFixtureFetch(`${WEB_URL}${path}`, {
method,
headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL, "Content-Type": "application/json" },
...(body ? { body: JSON.stringify(body) } : {}),
@@ -61,10 +62,10 @@ for (const parentType of ["text", "forum"] as const) {
}).toBe(true)
const added = await mutate(`/api/community/channels/${childId}/participants`, "POST", { userId: userId("bob") })
expect(added.status).toBe(201)
- await expect.poll(() => trace.events.some((event) => event.type === WS_EVENTS.CHANNEL_MEMBER_ADD && event.serverId === serverId && event.channelId === childId && event.userId === userId("bob"))).toBe(true)
- const removed = await bob.page.request.delete(`/api/community/channels/${childId}/participants/${userId("bob")}`)
+ await expect.poll(() => trace.events.some((event) => event.type === WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE && event.relation === "notify" && event.present === true && event.serverId === serverId && event.channelId === childId && event.userId === userId("bob"))).toBe(true)
+ const removed = await confirmCommunityFixtureApiResponse(bob.page.request.delete(`/api/community/channels/${childId}/participants/${userId("bob")}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(removed.status()).toBe(204)
- await expect.poll(() => trace.events.some((event) => event.type === WS_EVENTS.CHANNEL_MEMBER_REMOVE && event.serverId === serverId && event.channelId === childId && event.userId === userId("bob"))).toBe(true)
+ await expect.poll(() => trace.events.some((event) => event.type === WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE && event.relation === "notify" && event.present === false && event.serverId === serverId && event.channelId === childId && event.userId === userId("bob"))).toBe(true)
await expect(bob.page.getByTestId(tid.message(firstId))).toBeVisible()
const secondId = await seedMessage("alice", childId, "Still readable after leaving participation")
await expect(bob.page.getByTestId(tid.message(secondId))).toBeVisible()
@@ -73,7 +74,7 @@ for (const parentType of ["text", "forum"] as const) {
const revoked = await mutate(`/api/community/channels/${parentId}/members/${userId("bob")}`, "DELETE")
expect(revoked.status).toBe(204)
await expect(bob.page.getByTestId(tid.message(secondId))).toHaveCount(0)
- const denied = await bob.page.request.get(`/api/community/channels/${childId}`)
+ const denied = await confirmCommunityFixtureApiResponse(bob.page.request.get(`/api/community/channels/${childId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect([403, 404]).toContain(denied.status())
const lastId = await seedMessage("alice", childId, "Revoked reader cannot receive this")
await bob.page.waitForTimeout(750)
diff --git a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
index e648bafea..e52840af5 100644
--- a/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
+++ b/src/web/src/test/e2e-ui/29-community-bot-avatar-cleanup.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, communityFixtureFetch } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { WEB_URL } from "./_setup/paths"
@@ -14,7 +15,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
}
}
async function pairMachine(): Promise<string> {
- const pair = await fetch(`${WEB_URL}/api/community/machines/pair`, {
+ const pair = await communityFixtureFetch(`${WEB_URL}/api/community/machines/pair`, {
method: "POST",
headers: aliceHeaders(),
})
@@ -47,7 +48,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
}
const machineId = body.machineId
caseResources.own(machineId, async (id) => {
- const response = await fetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", headers: aliceHeaders() })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", headers: aliceHeaders() })
expect([204, 404]).toContain(response.status)
})
activationProof.response = activate
@@ -57,7 +58,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
return machineId
}
async function createBot(machineId: string, name: string): Promise<string> {
- const response = await fetch(`${WEB_URL}/api/community/bots`, {
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/bots`, {
method: "POST",
headers: aliceHeaders({ "Content-Type": "application/json" }),
body: JSON.stringify({ name, machineId, runtime: "codex" }),
@@ -70,7 +71,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
}
const botId = body.bot.id
caseResources.own(botId, async (id) => {
- const response = await fetch(`${WEB_URL}/api/community/bots/${id}`, { method: "DELETE", headers: aliceHeaders() })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/bots/${id}`, { method: "DELETE", headers: aliceHeaders() })
expect([204, 404]).toContain(response.status)
})
return botId
@@ -86,21 +87,21 @@ async function uploadAvatar(
botId: string,
): Promise<{ status: number; url: string; avatarVersion: number }> {
return page.evaluate(async (
- { id, base64 }: { id: string; base64: string },
+ { businessHeaders, id, base64 }: ({ id: string; base64: string }) & { businessHeaders: Record<string, string> },
) => {
const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0))
const form = new FormData()
form.append("file", new File([bytes], "avatar.png", { type: "image/png" }))
- const response = await fetch(`/api/community/bots/${id}/avatar`, {
+ const response = await fetch(`/api/community/bots/${id}/avatar`, { headers: businessHeaders,
method: "POST",
body: form,
credentials: "include",
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return {
status: response.status,
...await response.json() as { url: string; avatarVersion: number },
}
- }, { id: botId, base64: ONE_PIXEL_PNG_BASE64 })
+ }, { id: botId, base64: ONE_PIXEL_PNG_BASE64, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
}
test("real bot avatars become unreadable after single delete and authenticated machine cascade", async ({ caseActors, caseResources }) => {
@@ -168,12 +169,12 @@ test("real bot avatars become unreadable after single delete and authenticated m
await fetch(`${path}?before=${crypto.randomUUID()}`, { cache: "no-store" })
).status, avatarPath)).toBe(200)
- const deleteStatus = await alice.page.evaluate(async (id) => (
- await fetch(`/api/community/bots/${id}`, {
+ const deleteStatus = await alice.page.evaluate(async ({ value: id, businessHeaders }) => (
+ await fetch(`/api/community/bots/${id}`, { headers: businessHeaders,
method: "DELETE",
credentials: "include",
- })
- ).status, botId)
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
+ ).status, { value: botId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(deleteStatus).toBe(204)
expect(await alice.page.evaluate(async (path) => (
@@ -187,7 +188,7 @@ test("real bot avatars become unreadable after single delete and authenticated m
await fetch(`${path}?reload=${crypto.randomUUID()}`, { cache: "no-store" })
).status, avatarPath)).toBe(404)
- const machineDelete = await fetch(`${WEB_URL}/api/community/machines/${machineId}`, {
+ const machineDelete = await communityFixtureFetch(`${WEB_URL}/api/community/machines/${machineId}`, {
method: "DELETE",
headers: aliceHeaders(),
})
@@ -206,36 +207,36 @@ test("real bot avatars become unreadable after single delete and authenticated m
await fetch(`${path}?before-cascade=${crypto.randomUUID()}`, { cache: "no-store" })
).status, cascadeAvatarPath)).toBe(200)
- const preflightStatus = await alice.page.evaluate(async (id) => (
- await fetch(`/api/community/machines/${id}`, {
+ const preflightStatus = await alice.page.evaluate(async ({ value: id, businessHeaders }) => (
+ await fetch(`/api/community/machines/${id}`, { headers: businessHeaders,
method: "DELETE",
credentials: "include",
- })
- ).status, cascadeMachineId)
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
+ ).status, { value: cascadeMachineId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(preflightStatus).toBe(409)
- const cascadeStatus = await alice.page.evaluate(async (id) => (
+ const cascadeStatus = await alice.page.evaluate(async ({ value: id, businessHeaders }) => (
await fetch(`/api/community/machines/${id}`, {
method: "DELETE",
credentials: "include",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", ...businessHeaders },
body: JSON.stringify({ cascade: true }),
- })
- ).status, cascadeMachineId)
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
+ ).status, { value: cascadeMachineId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(cascadeStatus).toBe(204)
expect(await alice.page.evaluate(async (path) => (
await fetch(`${path}?after-cascade=${crypto.randomUUID()}`, { cache: "no-store" })
).status, cascadeAvatarPath)).toBe(404)
- const listedBotIds = await alice.page.evaluate(async () => {
- const response = await fetch("/api/community/bots", {
+ const listedBotIds = await alice.page.evaluate(async ({ businessHeaders }) => {
+ const response = await fetch("/api/community/bots", { headers: businessHeaders,
credentials: "include",
cache: "no-store",
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
if (!response.ok) throw new Error(`bot list failed: ${response.status}`)
const body = await response.json() as { bots: Array<{ id: string }> }
return body.bots.map((bot) => bot.id)
- })
+ }, { businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(listedBotIds).not.toContain(cascadeBotId)
await alice.page.reload()
await expect(alice.page.getByText(cascadeBotName, { exact: true })).toHaveCount(0)
diff --git a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
index 8acec2c27..69082055c 100644
--- a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
+++ b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
import type { Route } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
@@ -113,9 +114,9 @@ test("one human account converges read state across two browser profiles", async
await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toHaveCount(0)
}
- const accountSnapshot = async () => await (await deviceB.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const accountSnapshot = async () => await (await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -319,9 +320,9 @@ test("one human account converges read state across two browser profiles", async
expect(events.every((event) => event.inboxChanged && !("readStates" in event))).toBe(true)
}
- const snapshot = await (await deviceB.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const snapshot = await (await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -412,9 +413,9 @@ test("hidden eager channel and DM mounts defer cross-device reads until visible"
await expect.poll(() => deviceA.page.evaluate(() => document.visibilityState))
.toBe(state)
}
- const accountSnapshot = async () => await (await deviceB.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const accountSnapshot = async () => await (await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -565,9 +566,9 @@ test("a visible live tail clears both devices while an unseen tail stays unread"
await expect.poll(() => deviceA.page.evaluate(() => document.visibilityState))
.toBe(state)
}
- const beforeHidden = await (await deviceA.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const beforeHidden = await (await confirmCommunityFixtureApiResponse(deviceA.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -596,9 +597,9 @@ test("a visible live tail clears both devices while an unseen tail stays unread"
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
await deviceA.page.waitForTimeout(1_000) // hidden active-profile read exclusion window
expect(hiddenReadResponses).toEqual([])
- const afterHidden = await (await deviceA.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const afterHidden = await (await confirmCommunityFixtureApiResponse(deviceA.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -615,9 +616,9 @@ test("a visible live tail clears both devices while an unseen tail stays unread"
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
deviceA.page.off("response", trackHiddenReads)
- const beforeUnseen = await (await deviceA.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const beforeUnseen = await (await confirmCommunityFixtureApiResponse(deviceA.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -648,9 +649,9 @@ test("a visible live tail clears both devices while an unseen tail stays unread"
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
await deviceA.page.waitForTimeout(1_000) // unseen-tail read exclusion window
expect(unseenReadResponses).toEqual([])
- const afterUnseen = await (await deviceA.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const afterUnseen = await (await confirmCommunityFixtureApiResponse(deviceA.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -682,10 +683,10 @@ test("forum cards use the ordinary parent cursor while child cursors stay indepe
const alice = await asUser("alice")
const createEmptyPost = async (label: string) => {
- const response = await alice.page.request.post(
+ const response = await confirmCommunityFixtureApiResponse(alice.page.request.post(
`/api/community/channels/${forumId}/messages`,
- { data: { content: label, nonce: `e2e:${crypto.randomUUID()}:opener` } },
- )
+ { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, data: { content: label, nonce: `e2e:${crypto.randomUUID()}:opener` } },
+ ))
expect(response.status()).toBe(201)
return await response.json() as { threadId: string }
}
@@ -698,9 +699,9 @@ test("forum cards use the ordinary parent cursor while child cursors stay indepe
const proxyB = await proxyCommunityWebSockets(deviceB.context)
await gotoAfterUserWsAuth(deviceB.page, "/c/me")
- const threadsResponse = await deviceA.page.request.get(
- `/api/community/channels/${forumId}/threads?order=createdAt&limit=50`,
- )
+ const threadsResponse = await confirmCommunityFixtureApiResponse(deviceA.page.request.get(
+ `/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))
expect(threadsResponse.status()).toBe(200)
const threads = await threadsResponse.json() as {
threads: Array<{ id: string; parentMessageId: string | null }>
@@ -710,9 +711,9 @@ test("forum cards use the ordinary parent cursor while child cursors stay indepe
expect(firstOpener).toBeTruthy()
expect(secondOpener).toBeTruthy()
- const accountSnapshot = async () => await (await deviceA.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const accountSnapshot = async () => await (await confirmCommunityFixtureApiResponse(deviceA.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadSeq: number }>
}
@@ -782,10 +783,10 @@ test("forum cards use the ordinary parent cursor while child cursors stay indepe
expect(forumResponses).toHaveLength(beforeNavigationWrites)
expect((await accountSnapshot()).revision).toBe(afterVisible.revision)
- const directForumRead = await deviceA.page.request.put(
+ const directForumRead = await confirmCommunityFixtureApiResponse(deviceA.page.request.put(
`/api/community/channels/${forumId}/read`,
- { data: { lastReadMessageId: firstOpener } },
- )
+ { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, data: { lastReadMessageId: firstOpener } },
+ ))
expect(directForumRead.status()).toBe(200)
expect(await directForumRead.json()).toMatchObject({ changed: false, revision: afterVisible.revision })
@@ -844,14 +845,14 @@ test("human author-send replaces both profiles while notification policy preserv
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()
const authorStarts = [proxyA.frames.length, proxyB.frames.length]
- const authorStatus = await deviceA.page.evaluate(async ({ channelId, content }) => {
+ const authorStatus = await deviceA.page.evaluate(async ({ businessHeaders, channelId, content }) => {
const response = await fetch(`/api/community/channels/${channelId}/messages`, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", ...businessHeaders },
body: JSON.stringify({ content }),
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, { channelId: authorChannelId, content: `bob author send ${stamp}` })
+ }, { ...{ channelId: authorChannelId, content: `bob author send ${stamp}` }, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(authorStatus).toBe(201)
for (const [proxy, start] of [[proxyA, authorStarts[0]], [proxyB, authorStarts[1]]] as const) {
@@ -870,14 +871,14 @@ test("human author-send replaces both profiles while notification policy preserv
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()
const notificationStarts = [proxyA.frames.length, proxyB.frames.length]
- const notificationStatus = await deviceA.page.evaluate(async (channelId) => {
+ const notificationStatus = await deviceA.page.evaluate(async ({ value: channelId, businessHeaders }) => {
const response = await fetch(`/api/community/users/me/notifications/channel/${channelId}`, {
method: "PUT",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", ...businessHeaders },
body: JSON.stringify({ level: "mentions" }),
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, notificationChannelId)
+ }, { value: notificationChannelId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(notificationStatus).toBe(200)
for (const [proxy, start] of [[proxyA, notificationStarts[0]], [proxyB, notificationStarts[1]]] as const) {
@@ -905,23 +906,23 @@ test("human author-send replaces both profiles while notification policy preserv
expect(notificationEvents[0].revision).toBe(notificationEvents[1].revision)
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toHaveCount(0)
- const writerSnapshot = await (await deviceB.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const writerSnapshot = await (await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
expect(writerSnapshot.readStates.find((state) => state.channelId === authorChannelId)?.lastReadSeq)
.toBeGreaterThan(0)
expect(writerSnapshot.readStates.find((state) => state.channelId === notificationChannelId)?.lastReadSeq ?? 0)
.toBe(0)
const restoreStarts = [proxyA.frames.length, proxyB.frames.length]
- const restoreStatus = await deviceA.page.evaluate(async (channelId) => {
+ const restoreStatus = await deviceA.page.evaluate(async ({ value: channelId, businessHeaders }) => {
const response = await fetch(`/api/community/users/me/notifications/channel/${channelId}`, {
method: "PUT",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", ...businessHeaders },
body: JSON.stringify({ level: "all" }),
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, notificationChannelId)
+ }, { value: notificationChannelId, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(restoreStatus).toBe(200)
for (const [proxy, start] of [[proxyA, restoreStarts[0]], [proxyB, restoreStarts[1]]] as const) {
@@ -948,9 +949,9 @@ test("human author-send replaces both profiles while notification policy preserv
]
expect(restoreEvents[0].revision).toBe(restoreEvents[1].revision)
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()
- const restoredSnapshot = await (await deviceB.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const restoredSnapshot = await (await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
expect(restoredSnapshot.readStates.find((state) => state.channelId === notificationChannelId)?.lastReadSeq ?? 0)
.toBe(0)
})
@@ -977,9 +978,9 @@ test("forum delete broadcasts replacement and removal to both active profiles",
await gotoAfterUserWsAuth(deviceB.page, `/c/channels/${serverId}/${forumId}`)
await expect(deviceB.page.getByTestId(tid.forumThreadCard(deletedChildId))).toBeVisible()
- const threadsResponse = await deviceB.page.request.get(
- `/api/community/channels/${forumId}/threads?order=createdAt&limit=50`,
- )
+ const threadsResponse = await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ `/api/community/channels/${forumId}/threads?order=createdAt&limit=50`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))
expect(threadsResponse.status()).toBe(200)
const threads = (await threadsResponse.json()) as {
threads: Array<{ id: string; parentMessageId: string | null }>
@@ -989,15 +990,15 @@ test("forum delete broadcasts replacement and removal to both active profiles",
expect(priorOpenerId).toBeTruthy()
expect(deletedOpenerId).toBeTruthy()
- const beforeDeleteSnapshot = await (await deviceB.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as { revision: number }
+ const beforeDeleteSnapshot = await (await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { revision: number }
const starts = [proxyA.frames.length, proxyB.frames.length]
- const deleteStatus = await deviceA.page.evaluate(async (messageId) => {
- const response = await fetch(`/api/community/messages/${messageId}`, { method: "DELETE" })
+ const deleteStatus = await deviceA.page.evaluate(async ({ value: messageId, businessHeaders }) => {
+ const response = await fetch(`/api/community/messages/${messageId}`, { headers: businessHeaders, method: "DELETE" }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, deletedOpenerId!)
+ }, { value: deletedOpenerId!, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(deleteStatus).toBe(204)
for (const [proxy, start] of [[proxyA, starts[0]], [proxyB, starts[1]]] as const) {
@@ -1015,9 +1016,9 @@ test("forum delete broadcasts replacement and removal to both active profiles",
expect(eventsByProfile.flat().every((event) => !("readStates" in event))).toBe(true)
const profileBRevisions = new Set(eventsByProfile[1].map((event) => event.revision))
expect(eventsByProfile[0].some((event) => profileBRevisions.has(event.revision))).toBe(true)
- const deletedSnapshot = await (await deviceB.page.request.get(
- "/api/community/users/me/read-state",
- )).json() as {
+ const deletedSnapshot = await (await confirmCommunityFixtureApiResponse(deviceB.page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as {
revision: number
readStates: Array<{ channelId: string; lastReadMessageId: string | null }>
}
diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
index 86e2cfca9..da38f35a6 100644
--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
@@ -1,3 +1,4 @@
+import { communityFixtureFetch, currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Locator, Page, Route, TestInfo, WebSocket as BrowserSocket } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -32,7 +33,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
}
}
async function jsonRequest<T>(key: UserKey, path: string, init?: RequestInit): Promise<T> {
- const response = await fetch(`${WEB_URL}${path}`, {
+ const response = await communityFixtureFetch(`${WEB_URL}${path}`, {
...init,
headers: headersFor(key, {
...(init?.body ? { "Content-Type": "application/json" } : {}),
@@ -75,7 +76,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
machineId: string
}
createdMachineIds.set(data.machineId, caseResources.own(data.machineId, async (machineId) => {
- const response = await fetch(`${WEB_URL}/api/community/machines/${machineId}`, { method: "DELETE", headers: headersFor("alice") })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/machines/${machineId}`, { method: "DELETE", headers: headersFor("alice") })
expect(response.status, `delete test machine ${machineId}`).toBe(204)
createdMachineIds.delete(machineId)
}))
@@ -94,7 +95,7 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {
body: JSON.stringify({ name, machineId, runtime: "codex" }),
})
createdBotIds.set(data.bot.id, caseResources.own(data.bot.id, async (botId) => {
- const response = await fetch(`${WEB_URL}/api/community/bots/${botId}`, { method: "DELETE", headers: headersFor("alice") })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/bots/${botId}`, { method: "DELETE", headers: headersFor("alice") })
expect(response.status, `delete test bot ${botId}`).toBe(204)
createdBotIds.delete(botId)
}))
@@ -521,7 +522,7 @@ let caseJourneyFailure1Present = false
}))
await expect.poll(async () => {
- const response = await fetch(
+ const response = await communityFixtureFetch(
`${WEB_URL}/api/community/bots/${botId}/audit-log?limit=10`,
{ headers: headersFor("alice") },
)
@@ -619,13 +620,13 @@ test("owned bot profile preview stays root-bounded from its first visible frame"
const forumRef = `/${server!.name}#${server!.discriminator}/${forumName}`
const forumEnvelope = await jsonRequest<{
threads: Array<{ id: string; parentMessageId: string | null }>
- included: { parentMessages: Array<{ id: string; seq: number }> }
+ included: { messages: Array<{ id: string; seq: number }> }
}>(
"alice",
`/api/community/channels/${forumId}/threads?order=createdAt&limit=50&include=parentMessage`,
)
const forumThread = forumEnvelope.threads.find((thread) => thread.id === forumThreadId)
- const forumOpener = forumEnvelope.included.parentMessages.find(
+ const forumOpener = forumEnvelope.included.messages.find(
(message) => message.id === forumThread?.parentMessageId,
)
expect(forumOpener?.seq).toBeGreaterThan(0)
@@ -754,7 +755,7 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned aud
}>("alice", `/api/community/servers/${staleServerId}/members`)
const staleBotMember = staleMembers.members.find((member) => member.userId === botId)
expect(staleBotMember).toBeTruthy()
- const removeStaleBot = await fetch(
+ const removeStaleBot = await communityFixtureFetch(
`${WEB_URL}/api/community/servers/${staleServerId}/members/${staleBotMember!.id}`,
{ method: "DELETE", headers: headersFor("alice") },
)
@@ -776,7 +777,7 @@ let caseJourneyFailure2Present = false
}
await expect.poll(async () => {
- const response = await fetch(
+ const response = await communityFixtureFetch(
`${WEB_URL}/api/community/bots/${botId}/audit-log?limit=10`,
{ headers: headersFor("alice") },
)
@@ -990,7 +991,7 @@ let caseJourneyFailure2Present = false
await expect(alice.page).toHaveURL(`/c/me/bots?machineId=${machineId}`)
const bob = await asUser("bob")
- const bobDirectMarks = await fetch(`${WEB_URL}/api/community/bots/${botId}/marks`, {
+ const bobDirectMarks = await communityFixtureFetch(`${WEB_URL}/api/community/bots/${botId}/marks`, {
headers: headersFor("bob"),
})
expect(bobDirectMarks.status).toBe(404)
@@ -1165,7 +1166,7 @@ async function gateOlderActivityPages(page: Page, botId: string, caseResources:
const status = await ready
if (page.isClosed()) return
if (closing) await route.abort("failed")
- else if (status) await route.fulfill({ status, contentType: "application/json", body: JSON.stringify({ error: "Injected Activity older-page failure" }) })
+ else if (status) await route.fulfill(currentCommunityFixtureError("Injected Activity older-page failure", status))
else await route.continue()
})()
entries.push({ url: url.toString(), release })
diff --git a/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts
index 7607a9c88..72d4b30d5 100644
--- a/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts
+++ b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts
@@ -1,18 +1,12 @@
+import type { z } from "zod"
+import { CommunityServerMemberReadSchema, CommunityServerMembersReadSchema, CommunityServerMemberSearchReadSchema } from "@alook/shared"
+import { currentCommunityFixtureError, CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import { test, expect } from "./_fixtures/case-fixture"
import { composerEditable } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
-type Candidate = {
- id: string
- userId: string
- name: string
- discriminator: string
- avatar: string
- status: "offline"
- sub: string
- role: "member"
-}
+type Candidate = z.infer<typeof CommunityServerMemberReadSchema>
function candidate(prefix: string, index: number): Candidate {
const tag = String(index).padStart(4, "0")
@@ -21,7 +15,10 @@ function candidate(prefix: string, index: number): Candidate {
userId: `${prefix}-user-${tag}`,
name: `${prefix}${tag}`,
discriminator: tag,
- avatar: prefix[0] ?? "M",
+ avatar: null,
+ avatarVersion: 0,
+ statusEmoji: null,
+ statusText: null,
status: "offline",
sub: "",
role: "member",
@@ -30,7 +27,7 @@ function candidate(prefix: string, index: number): Candidate {
test("@ candidates page to completion and shared popups stay anchored through viewport resize signals", async ({ caseActors, caseResources }) => {
const actors = await caseActors(["alice"])
- const { asUser } = actors
+ const { asUser, userId } = actors
const { seedChannel, seedServer } = actors.seed
const serverId = await seedServer("alice", `Mention pages ${Date.now()}`)
@@ -66,6 +63,7 @@ test("@ candidates page to completion and shared popups stay anchored through vi
})
})
+ const pageScope = { viewerId: userId("alice"), serverId }
const browse = Array.from({ length: 12 }, (_, index) => candidate("Browse", index + 1))
const matches = Array.from({ length: 205 }, (_, index) => candidate("CapMatch", index + 1))
const browseCursors: Array<string | null> = []
@@ -90,29 +88,30 @@ test("@ candidates page to completion and shared popups stay anchored through vi
const cursor = url.searchParams.get("cursor")
searchCursors.set(query, [...(searchCursors.get(query) ?? []), cursor])
if (query === "Fail") {
- await route.fulfill({ status: 500, json: { error: "forced failure" } })
+ await route.fulfill(currentCommunityFixtureError("forced failure", 500))
return
}
if (query === "NoMatch") {
- await route.fulfill({ json: { members: [], limit: 200, hasMore: false } })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, json: CommunityServerMemberSearchReadSchema.parse({ ...pageScope, members: [], limit: 200, hasMore: false }) })
return
}
if (query === "CapMatch" && cursor) {
markSearchTailRequested()
await searchTailReleased
- await route.fulfill({
- json: { members: matches.slice(200), limit: 200, hasMore: false },
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
+ json: CommunityServerMemberSearchReadSchema.parse({ ...pageScope, members: matches.slice(200), limit: 200, hasMore: false }),
})
return
}
if (query === "CapMatch") {
- await route.fulfill({
- json: {
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
+ json: CommunityServerMemberSearchReadSchema.parse({
+ ...pageScope,
members: matches.slice(0, 200),
limit: 200,
hasMore: true,
cursor: "search-page-2",
- },
+ }),
})
return
}
@@ -120,16 +119,17 @@ test("@ candidates page to completion and shared popups stay anchored through vi
const cursor = url.searchParams.get("cursor")
browseCursors.push(cursor)
- await route.fulfill({
- json: cursor
- ? { members: browse.slice(8), limit: 8, total: 12, hasMore: false }
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
+ json: CommunityServerMembersReadSchema.parse(cursor
+ ? { ...pageScope, members: browse.slice(8), limit: 8, total: 12, hasMore: false }
: {
+ ...pageScope,
members: browse.slice(0, 8),
limit: 8,
total: 12,
hasMore: true,
cursor: "browse-page-2",
- },
+ }),
})
})
diff --git a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts
index 3951a8779..fc4b3137b 100644
--- a/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts
+++ b/src/web/src/test/e2e-ui/33-picker-async-layout.spec.ts
@@ -1,3 +1,5 @@
+import { friendBucketScenarioFixture } from "../../test/community-resource-fixtures"
+import { currentCommunityFixtureError, CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import type { Locator, Page } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -164,10 +166,10 @@ test.setTimeout(180_000)
if (route.request().method() !== "GET") return route.continue()
acceptedGets += 1
if (fail) {
- await route.fulfill({ status: 503, contentType: "application/json", body: '{"error":"failed"}' })
+ await route.fulfill(currentCommunityFixtureError("failed", 503))
return
}
- await route.fulfill({ status: 200, contentType: "application/json", body: '{"friends":[]}' })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, contentType: "application/json", body: JSON.stringify(friendBucketScenarioFixture("friends", [], actors.userId("alice"))) })
})
await page.goto(`/c/channels/${inviteServerId}`)
@@ -203,7 +205,7 @@ test.setTimeout(180_000)
if (route.request().method() !== "GET") return route.continue()
participantGets += 1
if (failParticipants) {
- await route.fulfill({ status: 503, contentType: "application/json", body: '{"error":"failed"}' })
+ await route.fulfill(currentCommunityFixtureError("failed", 503))
return
}
await route.continue()
@@ -285,7 +287,7 @@ test.setTimeout(180_000)
if (route.request().method() !== "GET") return route.continue()
parentGets += 1
if (failParent) {
- await route.fulfill({ status: 503, contentType: "application/json", body: '{"error":"failed"}' })
+ await route.fulfill(currentCommunityFixtureError("failed", 503))
return
}
await route.continue()
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 0d2563450..3fa208564 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
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse, currentCommunityFixtureError } from "./_fixtures/business-contract"
import { expect, test } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
@@ -259,9 +260,9 @@ test.describe("Inbox/read refresh ownership", () => {
expect(attentionIndex).toBeGreaterThanOrEqual(0)
expect(attentionIndex).toBeLessThan(readIndex)
- const snapshot = await (await page.request.get(
- "/api/community/users/me/read-state",
- )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const snapshot = await (await confirmCommunityFixtureApiResponse(page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
const readSeq = (channelId: string) => (
snapshot.readStates.find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
)
@@ -300,11 +301,7 @@ test.describe("Inbox/read refresh ownership", () => {
if (route.request().method() !== "PUT") return route.continue()
puts += 1
if (puts === 1) {
- await route.fulfill({
- status: 503,
- contentType: "application/json",
- body: '{"error":"retry"}',
- })
+ await route.fulfill(currentCommunityFixtureError("retry", 503))
return
}
await retryGate.promise
@@ -333,10 +330,10 @@ test.describe("Inbox/read refresh ownership", () => {
await seedJoinServer("alice", "bob", serverId)
const alice = await asUser("alice")
const createEmptyPost = async (label: string) => {
- const response = await alice.page.request.post(
+ const response = await confirmCommunityFixtureApiResponse(alice.page.request.post(
`/api/community/channels/${forumId}/messages`,
- { data: { content: label, nonce: `e2e:${crypto.randomUUID()}:opener` } },
- )
+ { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, data: { content: label, nonce: `e2e:${crypto.randomUUID()}:opener` } },
+ ))
expect(response.status()).toBe(201)
return (await response.json() as { threadId: string }).threadId
}
@@ -345,7 +342,7 @@ test.describe("Inbox/read refresh ownership", () => {
const { page } = await asUser("bob")
await gotoAfterUserWsAuth(page, "/c/me")
- const unreadResponse = await page.request.get("/api/community/users/me/attention")
+ const unreadResponse = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/attention", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(unreadResponse.status()).toBe(200)
const unread = await unreadResponse.json() as {
items: Array<{
@@ -392,9 +389,9 @@ test.describe("Inbox/read refresh ownership", () => {
await expect(page.getByTestId(tid.inboxUnreadChannel(forumId))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadChild(firstChildId))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChild(laterChildId))).toBeVisible()
- const snapshot = await (await page.request.get(
- "/api/community/users/me/read-state",
- )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const snapshot = await (await confirmCommunityFixtureApiResponse(page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
expect(snapshot.readStates.find((row) => row.channelId === forumId)?.lastReadSeq)
.toBe(first!.openerSeq)
expect(snapshot.readStates.some((row) => row.channelId === firstChildId)).toBe(false)
@@ -416,9 +413,9 @@ test.describe("Inbox/read refresh ownership", () => {
await seedMessage("alice", readChildId, `Unread reply under read opener ${stamp}`)
const { page } = await asUser("bob")
- const markRead = await page.request.put(`/api/community/channels/${parentId}/read`, {
+ const markRead = await confirmCommunityFixtureApiResponse(page.request.put(`/api/community/channels/${parentId}/read`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
data: { lastReadMessageId: readOpenerId },
- })
+ }))
expect(markRead.status()).toBe(200)
const unreadOpenerId = await seedMessage("alice", parentId, `Unread opener ${stamp}`)
@@ -437,7 +434,7 @@ test.describe("Inbox/read refresh ownership", () => {
await page.setViewportSize({ width: 768, height: 844 })
await gotoAfterUserWsAuth(page, "/c/me")
- const unreadResponse = await page.request.get("/api/community/users/me/attention")
+ const unreadResponse = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/attention", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(unreadResponse.status()).toBe(200)
const unread = await unreadResponse.json() as {
scopes: Array<{ channelId: string; lastUnreadSeq: number }>
@@ -462,9 +459,9 @@ test.describe("Inbox/read refresh ownership", () => {
openerUnread: true,
})
expect(children.some((child) => child.id === 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 beforeSnapshot = await (await confirmCommunityFixtureApiResponse(page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
const beforeCursor = (channelId: string) => beforeSnapshot.readStates
.find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
@@ -494,9 +491,9 @@ test.describe("Inbox/read refresh ownership", () => {
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 snapshot = await (await confirmCommunityFixtureApiResponse(page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).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(parent?.lastUnreadSeq)
diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
index 699cba7d5..fd44af0ff 100644
--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts
@@ -1,8 +1,10 @@
+import type { MachineObservations, MachineSummary, MachineBackendQuota } from "@/lib/community/machines"
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, communityFixtureFetch } from "./_fixtures/business-contract"
import { randomUUID } from "node:crypto"
import { spawnSync } from "node:child_process"
import { writeFileSync } from "node:fs"
import type { Page, TestInfo } from "@playwright/test"
-import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared"
+import { calendarDayKeyDaysAgo, dayKeyInTimeZone, parseCommunityBotsProfileRead } from "@alook/shared"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
@@ -13,7 +15,7 @@ import type { CaseActors } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors) {
const { sessionCookie } = actors
async function postAsAlice(path: string, body?: unknown): Promise<Response> {
- return fetch(`${WEB_URL}${path}`, {
+ return communityFixtureFetch(`${WEB_URL}${path}`, {
method: "POST",
headers: {
Cookie: sessionCookie("alice"),
@@ -185,12 +187,17 @@ const machine = {
},
},
],
-}
+} satisfies MachineSummary & { quota: MachineBackendQuota[] }
+
+const machineObservations = { quotas: [{ machineId: machine.id, quota: machine.quota }] } satisfies MachineObservations
const bots = [
{
id: "bot_codex",
name: "Alli",
+ avatarVersion: 0,
+ discriminator: "0001",
+ presence: "offline",
description: "",
image: null,
machineId: machine.id,
@@ -203,6 +210,9 @@ const bots = [
{
id: "bot_pi",
name: "Scout",
+ avatarVersion: 0,
+ discriminator: "0002",
+ presence: "offline",
description: "",
image: null,
machineId: machine.id,
@@ -215,6 +225,9 @@ const bots = [
{
id: "bot_claude",
name: "Draft",
+ avatarVersion: 0,
+ discriminator: "0003",
+ presence: "offline",
description: "",
image: null,
machineId: machine.id,
@@ -227,6 +240,9 @@ const bots = [
{
id: "bot_small",
name: "Pocket",
+ avatarVersion: 0,
+ discriminator: "0004",
+ presence: "offline",
description: "",
image: null,
machineId: machine.id,
@@ -239,6 +255,9 @@ const bots = [
{
id: "bot_cursor",
name: "Cursor",
+ avatarVersion: 0,
+ discriminator: "0005",
+ presence: "offline",
description: "",
image: null,
machineId: machine.id,
@@ -250,13 +269,13 @@ const bots = [
},
]
-const botsResponse = {
- bots,
+const botsResponse = (ownerUserId: string) => ({
+ bots: bots.map(bot => ({ ...bot, ownerUserId })),
plan: { id: "house", displayName: "House" },
limit: 40,
ownedCount: bots.length,
activeCount: bots.length,
-}
+})
async function attachScreenshot(page: Page, testInfo: TestInfo, name: string) {
const path = testInfo.outputPath(`${name}.png`)
@@ -280,11 +299,13 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({
const { page } = await asUser("alice", { hasTouch: true })
await page.route("**/api/community/bots", async (route) => {
- await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(botsResponse) })
+ const catalogue = botsResponse(actors.userId("alice"))
+ parseCommunityBotsProfileRead(catalogue, actors.userId("alice"))
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, contentType: "application/json", body: JSON.stringify(catalogue) })
})
await page.route(url => url.pathname === "/api/community/machines", async (route) => {
const optional = new URL(route.request().url()).searchParams.get("view") === "observations"
- await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(optional ? { quotas: [] } : { machines: [machine] }) })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, contentType: "application/json", body: JSON.stringify(optional ? machineObservations : { machines: [(({ quota: _quota, ...identity }) => identity)(machine)], complete: true }) })
})
await page.emulateMedia({ reducedMotion: "reduce", colorScheme: "light" })
await page.setViewportSize({ width: 1280, height: 900 })
@@ -603,7 +624,7 @@ let caseJourneyFailure1Present = false
writeFileSync(d1EvidencePath, `${JSON.stringify(d1Evidence, null, 2)}\n`)
await testInfo.attach("real-pi-d1-token-usage.json", { path: d1EvidencePath })
- const apiResponse = await fetch(`${WEB_URL}/api/community/bots`, {
+ const apiResponse = await communityFixtureFetch(`${WEB_URL}/api/community/bots`, {
headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL },
})
expect(apiResponse.ok).toBe(true)
diff --git a/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts b/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts
index f2ffcd624..99b23bb43 100644
--- a/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts
+++ b/src/web/src/test/e2e-ui/35-channel-ref-directory-states.spec.ts
@@ -1,3 +1,6 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, communityFixtureFetch, confirmCommunityFixtureApiResponse, currentCommunityFixtureError } from "./_fixtures/business-contract"
+import type { CommunityResourceBundle } from "../../../../shared/src/community-resources"
+import { WEB_URL } from "./_setup/paths"
import type { Page } from "@playwright/test"
import { expect, test, type CaseActors } from "./_fixtures/case-fixture"
import { composerEditable } from "./_fixtures/actions"
@@ -14,8 +17,9 @@ function deferred() {
return { promise, resolve }
}
-function directoryEnvelope(serverId: string, channelId: string) {
+function directoryEnvelope(serverId: string, channelId: string, resources: CommunityResourceBundle) {
return {
+ resources: { ...resources, servers: resources.servers.map(server => server.id === serverId ? { ...server, name: "Channel reference states", discriminator: "0042" } : server) },
directory: [{
id: serverId,
name: "Channel reference states",
@@ -70,7 +74,10 @@ async function seedDirectoryCase(actors: CaseActors) {
const channelId = await seedChannel("alice", serverId, "general")
const firstDmId = await seedDm("alice", userId("bob"))
const secondDmId = await seedDm("alice", userId("carol"))
- return { serverId, channelId, firstDmId, secondDmId }
+ const response = await communityFixtureFetch(`${WEB_URL}${DIRECTORY_PATH}`, { headers: { Cookie: actors.sessionCookie("alice") } })
+ if (!response.ok) throw new Error(`Directory resource preparation failed (${response.status})`)
+ const { resources } = await response.json() as { resources: CommunityResourceBundle }
+ return { serverId, channelId, firstDmId, secondDmId, resources }
}
test.describe("DM channel-reference directory states", () => {
@@ -79,7 +86,7 @@ test.describe("DM channel-reference directory states", () => {
test("cold pending stays anchored through query updates and resolves without false-empty", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob", "carol"])
const { asUser } = actors
- const { serverId, channelId, firstDmId } = await seedDirectoryCase(actors)
+ const { serverId, channelId, firstDmId, resources } = await seedDirectoryCase(actors)
const { page } = await asUser("alice")
const gate = deferred()
@@ -88,7 +95,7 @@ test.describe("DM channel-reference directory states", () => {
await page.route(`**${DIRECTORY_PATH}`, async (route) => {
directoryGets += 1
await gate.promise
- await route.fulfill({ status: 200, json: directoryEnvelope(serverId, channelId) })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, json: directoryEnvelope(serverId, channelId, resources) })
})
await page.goto(`/c/me/${firstDmId}`)
@@ -117,13 +124,13 @@ test.describe("DM channel-reference directory states", () => {
test("resolved empty stays anchored with explicit copy", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob", "carol"])
const { asUser } = actors
- const { firstDmId } = await seedDirectoryCase(actors)
+ const { firstDmId, resources } = await seedDirectoryCase(actors)
const { page } = await asUser("alice")
let directoryGets = 0
await page.route(`**${DIRECTORY_PATH}`, async (route) => {
directoryGets += 1
- await route.fulfill({ status: 200, json: { directory: [] } })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, json: { directory: [], resources: { ...resources, servers: [], serverMemberships: [], channels: [], memberships: [], profiles: [], messages: [] } } })
})
await page.goto(`/c/me/${firstDmId}`)
@@ -141,7 +148,7 @@ test.describe("DM channel-reference directory states", () => {
test("cold 500 is one attempt, same-popup input is inert, and a new session retries once", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob", "carol"])
const { asUser } = actors
- const { serverId, channelId, firstDmId } = await seedDirectoryCase(actors)
+ const { serverId, channelId, firstDmId, resources } = await seedDirectoryCase(actors)
const { page } = await asUser("alice")
const statuses: number[] = []
@@ -149,10 +156,10 @@ test.describe("DM channel-reference directory states", () => {
const status = statuses.length === 0 ? 500 : 200
statuses.push(status)
if (status === 500) {
- await route.fulfill({ status, json: { error: "forced failure" } })
+ await route.fulfill(currentCommunityFixtureError("forced failure", status))
return
}
- await route.fulfill({ status, json: directoryEnvelope(serverId, channelId) })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status, json: directoryEnvelope(serverId, channelId, resources) })
})
await page.goto(`/c/me/${firstDmId}`)
@@ -178,13 +185,13 @@ test.describe("DM channel-reference directory states", () => {
test("warm cache crosses DM routes without a duplicate request or status flash", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob", "carol"])
const { asUser } = actors
- const { serverId, channelId, firstDmId, secondDmId } = await seedDirectoryCase(actors)
+ const { serverId, channelId, firstDmId, secondDmId, resources } = await seedDirectoryCase(actors)
const { page } = await asUser("alice")
let directoryGets = 0
await page.route(`**${DIRECTORY_PATH}`, async (route) => {
directoryGets += 1
- await route.fulfill({ status: 200, json: directoryEnvelope(serverId, channelId) })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, json: directoryEnvelope(serverId, channelId, resources) })
})
await page.goto(`/c/me/${firstDmId}`)
@@ -214,7 +221,7 @@ test.describe("DM channel-reference directory states", () => {
test("late completion after exit and SPA route switch only warms the new DM", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob", "carol"])
const { asUser } = actors
- const { serverId, channelId, firstDmId, secondDmId } = await seedDirectoryCase(actors)
+ const { serverId, channelId, firstDmId, secondDmId, resources } = await seedDirectoryCase(actors)
const { page } = await asUser("alice")
const gate = deferred()
@@ -223,7 +230,7 @@ test.describe("DM channel-reference directory states", () => {
await page.route(`**${DIRECTORY_PATH}`, async (route) => {
directoryGets += 1
await gate.promise
- await route.fulfill({ status: 200, json: directoryEnvelope(serverId, channelId) })
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, status: 200, json: directoryEnvelope(serverId, channelId, resources) })
})
await page.goto(`/c/me/${firstDmId}`)
@@ -279,7 +286,7 @@ test.describe("DM channel-reference directory states", () => {
})
async function serverHandle(page: Page, serverId: string) {
- const response = await page.request.get("/api/community/users/me/channel-directory")
+ const response = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/channel-directory", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.status()).toBe(200)
const data = await response.json() as { directory: Array<{ id: string; name: string; discriminator: string }> }
const server = data.directory.find(row => row.id === serverId)
@@ -316,9 +323,9 @@ test.describe("channel ref page navigation", () => {
await page.getByTestId(tid.forumThreadArchiveBtn(archivedId)).click()
expect((await archived).status()).toBe(200)
await expect(card).toHaveCount(0)
- const before = await page.request.get(`/api/community/channels/${archivedId}`)
+ const before = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${archivedId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(before.status()).toBe(200)
- const beforeMetadata = await before.json() as { archived: boolean }
+ const { channel: beforeMetadata } = await before.json() as { channel: { archived: boolean } }
const resolvedRefs: string[] = []
page.on("request", request => {
@@ -347,15 +354,15 @@ test.describe("channel ref page navigation", () => {
await expect(page).toHaveURL(new RegExp(`/c/channels/${serverId}/${archivedId}$`))
expect(resolvedRefs).toContain(`/${handle.toLowerCase()}/ref-forum/#1`)
expect(resolvedRefs.every(ref => !ref.endsWith("#18") && !ref.endsWith("#11") && !ref.endsWith("#27"))).toBe(true)
- const metadata = await page.request.get(`/api/community/channels/${archivedId}`)
+ const metadata = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${archivedId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(metadata.status()).toBe(200)
- expect((await metadata.json() as { archived: boolean }).archived).toBe(beforeMetadata.archived)
- const feed = await page.request.get(`/api/community/channels/${forumId}/threads?archived=false`)
+ expect((await metadata.json() as { channel: { archived: boolean } }).channel.archived).toBe(beforeMetadata.archived)
+ const feed = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${forumId}/threads?archived=false`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(feed.status()).toBe(200)
const rows = await feed.json() as { threads: Array<{ id: string }> }
expect(rows.threads.map(row => row.id)).not.toContain(archivedId)
expect(rows.threads.map(row => row.id)).toContain(activeId)
- const archivedFeed = await page.request.get(`/api/community/channels/${forumId}/threads?tag=archived`)
+ const archivedFeed = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${forumId}/threads?tag=archived`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(archivedFeed.status()).toBe(200)
const archivedRows = await archivedFeed.json() as { threads: Array<{ id: string }> }
expect(archivedRows.threads.map(row => row.id)).toContain(archivedId)
@@ -378,7 +385,7 @@ test.describe("channel ref page navigation", () => {
await page.goto(`/c/me/${dmId}`)
const denied = await response
expect(denied.status()).toBe(403)
- expect(await denied.json()).toEqual({ error: "forbidden" })
+ expect(await denied.json()).toMatchObject({ error: { code: "not_allowed", message: "forbidden" } })
const pill = page.locator('[data-ref-state="forbidden"]').filter({ hasText: ref })
await expect(pill).toBeVisible()
await expect(page.getByTestId(tid.channelRefPill(postId))).toHaveCount(0)
diff --git a/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts b/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
index 32a7a4d7a..3cf923007 100644
--- a/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
+++ b/src/web/src/test/e2e-ui/37-server-rail-dnd.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { devices, type Locator, type Page } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
@@ -650,7 +651,7 @@ test("server rail keeps scroll separate from React DnD native and touch drag", a
})
const readFolderIds = async () => {
- const response = await page.request.get("/api/community/users/me/server-folders")
+ const response = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/server-folders", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.status()).toBe(200)
const body = await response.json() as { topOrder: Array<{ kind: "server" | "folder"; id: string }> }
return body.topOrder.filter((entry) => entry.kind === "folder").map((entry) => entry.id)
diff --git a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
index 86a2e42c8..06991eb7a 100644
--- a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
+++ b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
@@ -148,10 +148,12 @@ test("community checkpoint shows target pending for detail and keeps list surfac
has: page.locator('[data-slot="skeleton"]'),
})
const targetReady = page.locator(
- `[data-slot="community-conversation-surface"][data-channel-id="${channelB}"]`,
+ `[data-community-target-href="/c/channels/${serverId}/${channelB}"]`,
).filter({
has: page.getByRole("heading", { name: channelBName, exact: true }),
- }).filter({ has: page.getByTestId(tid.composerInput) })
+ }).filter({ has: page.locator(
+ `[data-slot="community-conversation-surface"][data-channel-id="${channelB}"]`,
+ ).filter({ has: page.getByTestId(tid.composerInput) }) })
const oldMain = page.locator(
`[data-slot="community-conversation-surface"][data-channel-id="${channelA}"]`,
)
@@ -271,10 +273,12 @@ test("mobile route commits stay stationary while sidebar identity survives same-
has: page.locator('[data-slot="skeleton"]'),
})
const targetReady = page.locator(
- `[data-slot="community-conversation-surface"][data-channel-id="${pendingChannel}"]`,
+ `[data-community-target-href="${pendingPath}"]`,
).filter({
has: page.getByRole("heading", { name: pendingName, exact: true }),
- }).filter({ has: page.getByTestId(tid.composerInput) })
+ }).filter({ has: page.locator(
+ `[data-slot="community-conversation-surface"][data-channel-id="${pendingChannel}"]`,
+ ).filter({ has: page.getByTestId(tid.composerInput) }) })
await expect(pendingMain.or(targetReady).first()).toBeVisible()
await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)
await expect(channelHeader(page, fastName)).toHaveCount(0)
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 122f4ea1e..83b3e8d9f 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
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
import type { ElementHandle, Locator, Page, Request, Route } from "@playwright/test"
import type { TiptapEditorHTMLElement } from "@tiptap/react"
@@ -180,22 +181,15 @@ async function expectReadingRootRetained(previous: ReadingRoot, scroller: Locato
await previous.dispose()
}
-async function expectReadingPositionRestored(scroller: Locator, before: ReadingPosition, fixture: { id: string; paragraphs: readonly string[] }): Promise<void> {
+async function expectOrdinaryReentry(scroller: Locator, before: ReadingPosition, fixture: { id: string; paragraphs: readonly string[] }, tailId: string): Promise<void> {
+ const body = before.rows.find(row => row.id === fixture.id)
+ expect(body, `visible departure fixture ${fixture.id}`).toBeDefined()
+ expect(body?.paragraphs).toEqual(fixture.paragraphs)
+ await expectCanonicalTail(scroller, tailId)
const after = await settledReadingPosition(scroller)
- expect(after.anchor?.id).toBe(before.anchor?.id)
- expect(after.anchor?.key).toBe(before.anchor?.key)
- expect(Math.abs(after.anchor!.offset - before.anchor!.offset), "restored message offset within its viewport").toBeLessThanOrEqual(1)
- for (const key of ["clientWidth", "clientHeight", "scrollHeight", "scrollTop"] as const) {
- expect(Math.abs(after[key] - before[key]), `qualified snapshot ${key}`).toBeLessThanOrEqual(1)
- }
- expect(after.rows.map(({ key, id, text }) => ({ key, id, text }))).toEqual(before.rows.map(({ key, id, text }) => ({ key, id, text })))
- for (const position of [before, after]) {
- const body = position.rows.find(row => row.id === fixture.id)
- expect(body, `visible fixture message ${fixture.id}`).toBeDefined()
- expect(body?.paragraphs).toEqual(fixture.paragraphs)
- }
- for (let index = 0; index < before.rows.length; index += 1) {
- expect(Math.abs(after.rows[index].height - before.rows[index].height), `restored row ${before.rows[index].key}`).toBeLessThanOrEqual(1)
+ expect(Math.abs(after.scrollTop - before.scrollTop), "fresh entry leaves the previous pixel position").toBeGreaterThan(1)
+ for (const key of ["clientWidth", "clientHeight"] as const) {
+ expect(Math.abs(after[key] - before[key]), `unchanged viewport ${key}`).toBeLessThanOrEqual(1)
}
}
@@ -387,9 +381,9 @@ async function typeReplyAfterAuthorMention(
}
async function latestSeq(page: Page, channelId: string): Promise<number> {
- const response = await page.request.get(`/api/community/channels/${channelId}/messages`)
+ const response = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${channelId}/messages`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.ok()).toBe(true)
- return ((await response.json()) as { latestSeq: number }).latestSeq
+ return ((await response.json()) as { page: { latestSeq: number } }).page.latestSeq
}
type ReadState = {
@@ -400,7 +394,7 @@ type ReadState = {
async function settledReadState(page: Page, channelId: string): Promise<ReadState> {
let previous: ReadState | null = null
for (let attempt = 0; attempt < 30; attempt += 1) {
- const response = await page.request.get("/api/community/users/me/read-state")
+ const response = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.ok()).toBe(true)
const snapshot = await response.json() as { readStates: Array<ReadState & { channelId: string }> }
const current = snapshot.readStates.find((row) => row.channelId === channelId)
@@ -1118,7 +1112,7 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await expectReadingRootDetached(departedDmRoot)
await alice.page.getByTestId(tid.dmRow(dmId)).click()
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)
- await expectReadingPositionRestored(dmScroller, dmReadingPosition, { id: dmScrollMessageId, paragraphs: dmScrollLines })
+ await expectOrdinaryReentry(dmScroller, dmReadingPosition, { id: dmScrollMessageId, paragraphs: dmScrollLines }, dmReplyPayload.message.id)
await expectReadingRootRecreated(departedDmRoot, dmScroller)
await expectReturnReadsAndGets(alice.page, dmId, dmReadState, dmReturnGets)
dmReturnGets.stop()
@@ -1204,14 +1198,14 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await clickAuthoritativeOwnerChannelRow(alice.page, channelId)
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
await expect(composerEditable(alice.page)).toContainText(navigationDraft)
- await expectReadingPositionRestored(scroller, channelReadingPosition, { id: channelScrollMessageId, paragraphs: channelScrollLines })
+ await expectOrdinaryReentry(scroller, channelReadingPosition, { id: channelScrollMessageId, paragraphs: channelScrollLines }, typingWsReadyId)
await expectReadingRootRecreated(departedChannelRoot, scroller)
await expectReturnReadsAndGets(alice.page, channelId, channelReadState, channelReturnGets)
channelReturnGets.stop()
expect(await latestSeq(alice.page, channelId)).toBe(channelSequence)
})
-test("mobile thread return recreates its list and restores the qualified reading anchor", async ({ caseActors }) => {
+test("mobile thread return recreates its list at the ordinary tail and retains its parent", async ({ caseActors }) => {
const actors = await caseActors(["alice"])
const { asUser } = actors
const { seedChannel, seedMessage, seedServer, seedThread } = actors.seed
@@ -1293,13 +1287,13 @@ test("mobile thread return recreates its list and restores the qualified reading
await expectReadingRootRetained(parentRoot, scroller)
await alice.page.goForward({ waitUntil: "commit" })
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)
- await expectReadingPositionRestored(threadScroller, threadReadingPosition, { id: threadScrollMessageId, paragraphs: threadScrollLines })
+ await expectOrdinaryReentry(threadScroller, threadReadingPosition, { id: threadScrollMessageId, paragraphs: threadScrollLines }, threadReplyId)
await expectReadingRootRecreated(departedThreadRoot, threadScroller)
await expectReturnReadsAndGets(alice.page, threadId, threadReadState, threadReturnGets)
threadReturnGets.stop()
})
-test("mobile width change invalidates a previously qualified snapshot and falls back to its canonical tail", async ({ caseActors }) => {
+test("mobile fresh entry uses the canonical tail at unchanged and changed widths", async ({ caseActors }) => {
test.setTimeout(120_000)
const actors = await caseActors(["alice"])
const { seedChannel, seedMessage, seedServer } = actors.seed
@@ -1332,7 +1326,7 @@ test("mobile width change invalidates a previously qualified snapshot and falls
expect(departure.scrollTop).toBe(1200)
expect(departure.scrollHeight - departure.clientHeight - departure.scrollTop).toBeGreaterThan(1)
- await test.step("the unchanged viewport recreates the node and restores its qualified anchor", async () => {
+ await test.step("the unchanged viewport recreates the node at the canonical tail", async () => {
const original = await readingRoot(scroller)
const gets = trackSurfaceGets(alice.page, channelId)
await alice.page.getByRole("banner").getByRole("button", { name: "Back" }).click()
@@ -1340,14 +1334,19 @@ test("mobile width change invalidates a previously qualified snapshot and falls
await expectReadingRootDetached(original)
await clickAuthoritativeOwnerChannelRow(alice.page, channelId)
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(href)
- await expectReadingPositionRestored(scroller, departure, { id: widthScrollMessageId, paragraphs: widthScrollLines })
+ await expectOrdinaryReentry(scroller, departure, { id: widthScrollMessageId, paragraphs: widthScrollLines }, tailId)
await expectReadingRootRecreated(original, scroller)
await expectReturnReadsAndGets(alice.page, channelId, read, gets)
gets.stop()
})
- await test.step("a changed viewport rejects that snapshot and lands on the confirmed read tail", async () => {
+ await test.step("a changed viewport also enters at the confirmed read tail", async () => {
+ await scroller.evaluate(element => {
+ element.scrollTop = 1200
+ element.dispatchEvent(new Event("scroll"))
+ })
const qualified = await settledReadingPosition(scroller)
+ expect(qualified.scrollTop).toBe(1200)
expect(qualified.clientWidth).toBe(departure.clientWidth)
const original = await readingRoot(scroller)
const gets = trackSurfaceGets(alice.page, channelId)
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 871326e79..17c1d4718 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,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import type { Page, Request, Response } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
@@ -152,9 +153,9 @@ test.describe("mobile server header direct hierarchy", () => {
await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${postId}`)
await expect(page.locator('[data-mobile-page-active="true"]').getByTestId(tid.composerInput)).toBeVisible()
}
- const metadata = await page.request.get(new URL(`/api/community/channels/${postId}`, page.url()).href)
+ const metadata = await confirmCommunityFixtureApiResponse(page.request.get(new URL(`/api/community/channels/${postId}`, page.url()).href, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(metadata.status()).toBe(200)
- expect(await metadata.json()).toMatchObject({ id: postId, serverId, parentChannelId: forumId })
+ expect((await metadata.json()).channel).toMatchObject({ id: postId, serverId, parentChannelId: forumId })
}
} finally { page.off("request", requested) }
})
diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
index 2f19bd17a..e7f2dbb8a 100644
--- a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { expectInertBackground } from "./_fixtures/inert-background"
import type { Locator, Page, Response } from "@playwright/test"
import { AccountAttentionSnapshotSchema } from "@alook/shared"
@@ -216,7 +217,7 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
fullPage: true,
})
- const seed = await page.request.get("/api/community/servers")
+ const seed = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/servers", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(seed.status()).toBe(200)
const body = await seed.json() as { servers: Array<{ id: string; unread: boolean }> }
expect(body.servers.find((server) => server.id === backgroundServer)?.unread).toBe(true)
@@ -249,7 +250,7 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
}
})
const expectPrimaryCount = async (stage: string, count: number) => {
- const response = await page.request.get("/api/community/users/me/attention")
+ const response = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/attention", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.status()).toBe(200)
const raw: unknown = await response.json()
expect(raw).not.toHaveProperty("stale", true)
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 f764cc360..963642e1f 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
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse, currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Page, Request } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -99,7 +100,7 @@ async function expectNoUnreadDot(row: ReturnType<Page["getByTestId"]>) {
}
async function readSeq(page: Page, channelId: string): Promise<number> {
- const response = await page.request.get("/api/community/users/me/read-state")
+ const response = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.ok()).toBe(true)
const snapshot = await response.json() as {
readStates: Array<{ channelId: string; lastReadSeq: number }>
@@ -239,7 +240,7 @@ test.setTimeout(180_000)
"/api/community/users/me/inbox/unreads/read-all",
"/api/community/users/me/inbox/dms/read-all",
]) {
- expect((await bob.page.request.post(path)).ok()).toBe(true)
+ expect((await confirmCommunityFixtureApiResponse(bob.page.request.post(path, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))).ok()).toBe(true)
}
const observerGate = await installReadObserverGate(bob.page)
const proxy = await proxyCommunityWebSockets(bob.context)
@@ -341,9 +342,9 @@ test.setTimeout(180_000)
const proxy = await proxyCommunityWebSockets(context)
await gotoAfterUserWsAuth(page, `/c/channels/${foregroundServer}/${foregroundChannel}`)
await expect(page.getByTestId(tid.serverIcon(backgroundServer))).toBeVisible({ timeout: 30_000 })
- const beforeSnapshot = await (await page.request.get(
- "/api/community/users/me/read-state",
- )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const beforeSnapshot = await (await confirmCommunityFixtureApiResponse(page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
const beforeCursor = (channelId: string) => beforeSnapshot.readStates
.find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
@@ -431,9 +432,9 @@ test.setTimeout(180_000)
fullPage: true,
})
- const snapshot = await (await page.request.get(
- "/api/community/users/me/read-state",
- )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const snapshot = await (await confirmCommunityFixtureApiResponse(page.request.get(
+ "/api/community/users/me/read-state", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
const cursor = (channelId: string) => snapshot.readStates
.find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
expect(cursor(unreadChannel)).toBeGreaterThan(beforeCursor(unreadChannel))
@@ -525,9 +526,9 @@ test.setTimeout(180_000)
triggerUnread: () => seedMessage("alice", channelId, channelText),
triggerReadback: async () => {
const messageId = await sendRailMention(`channel readback ${stamp}`)
- expect((await page.request.put(`/api/community/channels/${railTriggerChannel}/read`, {
+ expect((await confirmCommunityFixtureApiResponse(page.request.put(`/api/community/channels/${railTriggerChannel}/read`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
data: { lastReadMessageId: messageId },
- })).status()).toBe(200)
+ }))).status()).toBe(200)
},
}, caseResources)
@@ -542,9 +543,9 @@ test.setTimeout(180_000)
triggerUnread: () => seedMessage("alice", childId, childText),
triggerReadback: async () => {
const messageId = await sendRailMention(`child readback ${stamp}`)
- expect((await childPage.request.put(`/api/community/channels/${railTriggerChannel}/read`, {
+ expect((await confirmCommunityFixtureApiResponse(childPage.request.put(`/api/community/channels/${railTriggerChannel}/read`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
data: { lastReadMessageId: messageId },
- })).status()).toBe(200)
+ }))).status()).toBe(200)
},
}, caseResources)
await childPage.close()
@@ -575,11 +576,7 @@ test.setTimeout(180_000)
if (request.method() === "POST" && path.endsWith("/read-all")) paths.push(path)
})
await page.route("**/api/community/users/me/inbox/dms/read-all", async (route) => {
- await route.fulfill({
- status: 503,
- contentType: "application/json",
- body: '{"error":"dm read-all unavailable"}',
- })
+ await route.fulfill(currentCommunityFixtureError("dm read-all unavailable", 503))
})
await page.getByRole("button", { name: "Mark all read" }).click()
await expect.poll(() => paths.length, { timeout: 20_000 }).toBe(3)
diff --git a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts
index 20c52fc8d..d493d9d70 100644
--- a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts
+++ b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import type { Page } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -34,7 +35,7 @@ function deferred(caseResources: CaseResources) {
}
async function uploadSolidAvatar(page: Page, color: string): Promise<AvatarUpload> {
- return page.evaluate(async (fill) => {
+ return page.evaluate(async ({ value: fill, businessHeaders }) => {
const canvas = document.createElement("canvas")
canvas.width = 48
canvas.height = 48
@@ -53,16 +54,16 @@ async function uploadSolidAvatar(page: Page, color: string): Promise<AvatarUploa
))
const form = new FormData()
form.append("file", new File([blob], "avatar.png", { type: "image/png" }))
- const response = await fetch("/api/community/users/me/avatar", {
+ const response = await fetch("/api/community/users/me/avatar", { headers: businessHeaders,
method: "POST",
body: form,
credentials: "include",
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return {
status: response.status,
...await response.json() as { url: string; avatarVersion: number },
}
- }, color)
+ }, { value: color, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
}
async function expectPhoto(locator: ReturnType<Page["locator"]>, url: string) {
@@ -265,7 +266,7 @@ test("versioned avatars converge across live, stale, reconnect, cold, and concur
await expectPhoto(uploader.page.locator("body"), winner.url)
await expectPhoto(sameAccount.page.locator("body"), winner.url)
await expectPhoto(cold.page.locator(`[data-msg-id="${messageId}"]`), winner.url)
- const selfProfile = await uploader.page.request.get("/api/community/users/me/profile")
+ const selfProfile = await confirmCommunityFixtureApiResponse(uploader.page.request.get("/api/community/users/me/profile", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(selfProfile.status()).toBe(200)
expect(await selfProfile.json()).toMatchObject({
id: aliceId,
diff --git a/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
index 93bd253bc..4f3641b2e 100644
--- a/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
+++ b/src/web/src/test/e2e-ui/43-composer-attachment-drafts.spec.ts
@@ -1,3 +1,4 @@
+import { currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Page } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { composerEditable, installInputCapability } from "./_fixtures/actions"
@@ -187,11 +188,7 @@ test.describe("same-tab Community attachment drafts", () => {
if (route.request().method() !== "POST") return route.continue()
uploadAttempts++
if (uploadAttempts === 1) {
- await route.fulfill({
- status: 500,
- contentType: "application/json",
- body: JSON.stringify({ error: "forced upload failure" }),
- })
+ await route.fulfill(currentCommunityFixtureError("forced upload failure", 500))
return
}
await route.continue()
diff --git a/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts
index 4fa19fef3..67f741f67 100644
--- a/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts
+++ b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import type { Locator, Page } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -399,12 +400,12 @@ test.describe("mobile reaction details", () => {
const chip = alice.page.getByTestId(tid.reactionChip(emptyMessageId, "✅"))
await holdReaction(alice.page, chip)
await expectDialogInsideViewport(alice.page, emptyMessageId)
- const status = await alice.page.evaluate(async ({ id, emoji }) => {
- const response = await fetch(`/api/community/messages/${id}/reactions/${encodeURIComponent(emoji)}`, {
+ const status = await alice.page.evaluate(async ({ businessHeaders, id, emoji }) => {
+ const response = await fetch(`/api/community/messages/${id}/reactions/${encodeURIComponent(emoji)}`, { headers: businessHeaders,
method: "DELETE",
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
return response.status
- }, { id: emptyMessageId, emoji: "✅" })
+ }, { id: emptyMessageId, emoji: "✅", businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(status).toBe(204)
await expect(alice.page.getByTestId(tid.reactionEmpty(emptyMessageId))).toBeVisible()
await expect(alice.page.getByTestId(tid.reactionDialog(emptyMessageId))).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts b/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts
index d6a3a4870..8b4d2f94e 100644
--- a/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts
+++ b/src/web/src/test/e2e-ui/50-daemon-update-notice.spec.ts
@@ -1,3 +1,5 @@
+import { encodeCommunityBrowserEvent } from "@alook/shared"
+import { currentCommunityFixtureError, CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import { readFileSync } from "node:fs"
import type { Page, Request } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
@@ -40,10 +42,10 @@ async function serveMachines(page: Page, {
await page.route(url => url.pathname === "/api/community/machines", async (route) => {
const optional = new URL(route.request().url()).searchParams.get("view") === "observations"
if (!optional) requestCount += 1
- await route.fulfill({
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
status: 200,
contentType: "application/json",
- body: JSON.stringify(optional ? { quotas: machines.map(machine => ({ machineId: machine.id, quota: machine.quota })) } : { machines }),
+ body: JSON.stringify(optional ? { quotas: machines.map(machine => ({ machineId: machine.id, quota: machine.quota })) } : { machines: machines.map(({ quota: _quota, ...identity }) => identity), complete: true }),
})
})
await page.route("**/api/community/machines/*/update", async (route) => {
@@ -51,14 +53,10 @@ async function serveMachines(page: Page, {
const machineId = match?.[1]
if (machineId) updateRequests.push(machineId)
if (machineId && remainingFailures.delete(machineId)) {
- await route.fulfill({
- status: 503,
- contentType: "application/json",
- body: JSON.stringify({ error: "temporary unavailable" }),
- })
+ await route.fulfill(currentCommunityFixtureError("temporary unavailable", 503))
return
}
- await route.fulfill({
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
status: 200,
contentType: "application/json",
body: JSON.stringify({ dispatched: true }),
@@ -289,14 +287,20 @@ test("partial dispatch retries only failed eligible Machines and clears from liv
await expect(progressBadge).toHaveAttribute("aria-label", "Machine update in progress")
await expect(progressBadge).toHaveText("")
+ const sendCurrent = (event: unknown) => {
+ const encoded = encodeCommunityBrowserEvent(event)
+ if (!encoded.ok) throw new Error(`Invalid positive machine event: ${encoded.reason}`)
+ if (encoded.envelope.type !== "community:machine.updated") throw new Error("Expected a current machine update event")
+ ws.send(encoded.envelope)
+ }
const { quota: _firstQuota, ...firstUpdated } = outdatedMachine
const { quota: _secondQuota, ...secondUpdated } = secondMachine
- ws.send({
+ sendCurrent({
type: "community:machine.updated",
machine: { ...firstUpdated, daemonVersion: latestDaemonVersion },
})
await expect(progressBadge).toBeVisible()
- ws.send({
+ sendCurrent({
type: "community:machine.updated",
machine: { ...secondUpdated, daemonVersion: latestDaemonVersion },
})
diff --git a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
index 3682cd950..4a14ff639 100644
--- a/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
+++ b/src/web/src/test/e2e-ui/51-mobile-forum-tag-editor.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse, currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Page } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
@@ -316,8 +317,8 @@ test.describe("forum tag editor", () => {
expect(await unarchivedResponse.json()).toEqual({ tags: [] })
await expect.poll(async () => {
const [tags, feed] = await Promise.all([
- tabA.page.request.get(`/api/community/channels/${forumId}/messages/tags`),
- tabA.page.request.get(`/api/community/channels/${forumId}/threads`),
+ confirmCommunityFixtureApiResponse(tabA.page.request.get(`/api/community/channels/${forumId}/messages/tags`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })),
+ confirmCommunityFixtureApiResponse(tabA.page.request.get(`/api/community/channels/${forumId}/threads`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })),
])
expect(tags.status()).toBe(200)
expect(feed.status()).toBe(200)
@@ -416,11 +417,7 @@ test.describe("forum tag editor", () => {
rejectNext = false
sawFailureRequest()
await failureGate
- await routeRequest.fulfill({
- status: 500,
- contentType: "application/json",
- body: JSON.stringify({ error: "archive retry" }),
- })
+ await routeRequest.fulfill(currentCommunityFixtureError("archive retry", 500))
return
}
await routeRequest.continue()
@@ -542,11 +539,7 @@ test.describe("forum tag editor", () => {
await page.route("**/api/community/messages/*/tags", async (routeRequest) => {
if (rejectNext) {
rejectNext = false
- await routeRequest.fulfill({
- status: 500,
- contentType: "application/json",
- body: JSON.stringify({ error: "retry" }),
- })
+ await routeRequest.fulfill(currentCommunityFixtureError("retry", 500))
return
}
await routeRequest.continue()
diff --git a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts b/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
index 27a536177..fdbecff56 100644
--- a/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
+++ b/src/web/src/test/e2e-ui/51-share-image-assets.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import { createServer } from "node:http"
import type { AddressInfo } from "node:net"
import { expect, test } from "./_fixtures/case-fixture"
@@ -57,15 +58,15 @@ async function reloadWithUnavailableImage(page: Page, route: string, image: Loca
async function uploadAvatar(page: Page, color = "rgb(220, 35, 60)"): Promise<void> {
const bytes = await solidPng(page, color, 48, 48)
- const status = await page.evaluate(async (png) => {
+ const status = await page.evaluate(async ({ value: png, businessHeaders }) => {
const form = new FormData()
form.append("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "avatar.png")
- return (await fetch("/api/community/users/me/avatar", {
+ return (await fetch("/api/community/users/me/avatar", { headers: businessHeaders,
method: "POST",
body: form,
credentials: "include",
- })).status
- }, bytes)
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })).status
+ }, { value: bytes, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(status).toBe(200)
}
@@ -75,71 +76,71 @@ async function seedMessage(
content: string,
attachmentIds: string[] = [],
) {
- const result = await page.evaluate(async ({ targetId, body, attachments }) => {
+ const result = await page.evaluate(async ({ businessHeaders, targetId, body, attachments }) => {
const response = await fetch(`/api/community/channels/${targetId}/messages`, {
method: "POST",
credentials: "include",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", ...businessHeaders },
body: JSON.stringify({
content: body,
attachments,
nonce: `e2e:${crypto.randomUUID()}`,
}),
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
const payload = await response.json() as { message: { id: string; createdAt: string } }
return { status: response.status, ...payload.message }
- }, { targetId: channelId, body: content, attachments: attachmentIds })
+ }, { targetId: channelId, body: content, attachments: attachmentIds, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(result.status).toBe(201)
return result
}
async function uploadAttachment(page: Page, channelId: string) {
const bytes = await solidPng(page, "rgb(20, 105, 220)", 96, 64)
- const result = await page.evaluate(async ({ targetId, png }) => {
+ const result = await page.evaluate(async ({ businessHeaders, targetId, png }) => {
const form = new FormData()
form.append("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "blue.png")
- const response = await fetch(`/api/community/channels/${targetId}/attachments`, {
+ const response = await fetch(`/api/community/channels/${targetId}/attachments`, { headers: businessHeaders,
method: "POST",
body: form,
credentials: "include",
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
const payload = await response.json() as { id: string }
return { status: response.status, id: payload.id }
- }, { targetId: channelId, png: bytes })
+ }, { targetId: channelId, png: bytes, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(result.status).toBe(200)
return result.id
}
async function uploadAnimatedAttachment(page: Page, channelId: string) {
- const result = await page.evaluate(async ({ targetId, base64 }) => {
+ const result = await page.evaluate(async ({ businessHeaders, targetId, base64 }) => {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index)
const form = new FormData()
form.append("file", new Blob([bytes], { type: "image/gif" }), "red-blue.gif")
- const response = await fetch(`/api/community/channels/${targetId}/attachments`, {
+ const response = await fetch(`/api/community/channels/${targetId}/attachments`, { headers: businessHeaders,
method: "POST",
body: form,
credentials: "include",
- })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })
const payload = await response.json() as { id: string }
return { status: response.status, id: payload.id }
- }, { targetId: channelId, base64: TWO_FRAME_GIF_BASE64 })
+ }, { targetId: channelId, base64: TWO_FRAME_GIF_BASE64, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(result.status).toBe(200)
return result.id
}
async function uploadServerIcon(page: Page, serverId: string): Promise<void> {
const bytes = await solidPng(page, "rgb(25, 180, 80)", 64, 64)
- const status = await page.evaluate(async ({ targetId, png }) => {
+ const status = await page.evaluate(async ({ businessHeaders, targetId, png }) => {
const form = new FormData()
form.append("file", new Blob([new Uint8Array(png)], { type: "image/png" }), "icon.png")
- return (await fetch(`/api/community/servers/${targetId}/icon`, {
+ return (await fetch(`/api/community/servers/${targetId}/icon`, { headers: businessHeaders,
method: "POST",
body: form,
credentials: "include",
- })).status
- }, { targetId: serverId, png: bytes })
+ }).then(response => { if (response.ok && response.headers.get("X-Alook-Community-Contract") !== businessHeaders["X-Alook-Community-Contract"]) throw new Error("Fixture browser response did not confirm current business version"); return response })).status
+ }, { targetId: serverId, png: bytes, businessHeaders: CURRENT_COMMUNITY_FIXTURE_HEADERS })
expect(status).toBe(200)
}
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 f7298a4ea..a75b81647 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
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./_fixtures/business-contract"
import { expectInertBackground } from "./_fixtures/inert-background"
import type { Page, Request } from "@playwright/test"
import { expect, test, type CaseActors } from "./_fixtures/case-fixture"
@@ -36,11 +37,11 @@ type BorderGeometry = Record<"top" | "right" | "bottom" | "left", {
async function removeServerChannels(serverId: string, sessionCookie: CaseActors["sessionCookie"]) {
const headers = { Cookie: sessionCookie("alice"), Origin: WEB_URL }
- const response = await fetch(`${WEB_URL}/api/community/servers/${serverId}/channels`, { headers })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/servers/${serverId}/channels`, { headers })
if (!response.ok) throw new Error(`list server channels failed (${response.status})`)
const body = await response.json() as { channels: Array<{ id: string }> }
for (const channel of body.channels) {
- const deleted = await fetch(`${WEB_URL}/api/community/channels/${channel.id}`, {
+ const deleted = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channel.id}`, {
method: "DELETE",
headers,
})
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 f2e646075..12a4e448e 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
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./_fixtures/business-contract"
import type { CommunityConversationEntryRead } from "@alook/shared"
import type { Locator, Page, Route, TestInfo } from "@playwright/test"
import { test, expect, type CaseActors } from "./_fixtures/case-fixture"
@@ -141,7 +142,7 @@ async function seedDmProfile(
}
async function setReadCheckpoint(actors: CaseActors, channelId: string, messageId: string): Promise<void> {
- const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
method: "PUT",
headers: {
Cookie: actors.sessionCookie("alice"),
@@ -914,7 +915,7 @@ test.describe("message scroll characterization", () => {
await markScrollTrace(alice.page, `${author}-${distance}-precondition`, { detail: before })
const nonce = `scroll186_${author}_${distance}_${Date.now()}`
const content = `passive ${author} at ${distance} ${nonce}`
- const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {
method: "POST",
headers: { Cookie: sessionCookie(author), "Content-Type": "application/json", Origin: WEB_URL },
body: JSON.stringify({ content, nonce }),
diff --git a/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
index e9454e113..48f6784cf 100644
--- a/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
+++ b/src/web/src/test/e2e-ui/56-inbox-friend-requests.spec.ts
@@ -1,3 +1,5 @@
+import { CommunityAcceptedFriendsReadSchema } from "@alook/shared"
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse, currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Locator, Page } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
import { GEOMETRY_EPSILON, gotoAfterUserWsAuth, waitForElementMotion } from "./_fixtures/actions"
@@ -17,7 +19,7 @@ async function clearMessageInbox(page: Page) {
"/api/community/users/me/inbox/unreads/read-all",
"/api/community/users/me/inbox/dms/read-all",
]) {
- expect((await page.request.post(path)).ok()).toBe(true)
+ expect((await confirmCommunityFixtureApiResponse(page.request.post(path, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))).ok()).toBe(true)
}
}
@@ -221,7 +223,7 @@ test.describe("actionable Inbox friend requests", () => {
if (attempts === 1) {
markFirstAttempt()
await failureGate
- await route.fulfill({ status: 503, json: { error: "forced retry" } })
+ await route.fulfill(currentCommunityFixtureError("forced retry", 503))
return
}
await route.continue()
@@ -267,12 +269,12 @@ test.describe("actionable Inbox friend requests", () => {
await bob.page.getByTestId(tid.inboxTrigger).click()
await bob.page.getByRole("link", { name: "Friends", exact: true }).click()
- const accepted = await bob.page.request.get("/api/community/friends/accepted")
+ const accepted = await confirmCommunityFixtureApiResponse(bob.page.request.get("/api/community/friends/accepted", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(accepted.ok()).toBe(true)
- const acceptedBody = await accepted.json() as {
- friends: Array<{ userId: string; name: string; discriminator: string }>
- }
- const alice = acceptedBody.friends.find((friend) => friend.userId === userId("alice"))
+ const acceptedBody = CommunityAcceptedFriendsReadSchema.parse(await accepted.json())
+ if (acceptedBody.stale) throw new Error("Accepted friend fixture read is stale")
+ const relation = acceptedBody.friends.find(friend => friend.userId === userId("alice"))
+ const alice = acceptedBody.resources.profiles.find(profile => profile.id === relation?.userId)
expect(alice).toBeDefined()
const allFriends = bob.page.getByRole("tabpanel", { name: "All", exact: true })
.getByText("All friends — 1", { exact: true }).locator("..")
@@ -401,10 +403,10 @@ test.describe("actionable Inbox friend requests", () => {
if (!bob.page.isClosed()) await bob.page.unroute(`**${friendsAcceptPath}`)
})
await bob.page.route(`**${inboxAcceptPath}`, async (route) => {
- await route.fulfill({ status: 503, json: { error: "forced inbox geometry retry" } })
+ await route.fulfill(currentCommunityFixtureError("forced inbox geometry retry", 503))
})
await bob.page.route(`**${friendsAcceptPath}`, async (route) => {
- await route.fulfill({ status: 503, json: { error: "forced friends geometry retry" } })
+ await route.fulfill(currentCommunityFixtureError("forced friends geometry retry", 503))
})
try {
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 b39021442..e2d8bd381 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
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, communityFixtureFetch, confirmCommunityFixtureApiResponse, currentCommunityFixtureError } from "./_fixtures/business-contract"
import type { Page, WebSocket } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth, openServer } from "./_fixtures/actions"
@@ -12,7 +13,7 @@ async function prepareCase(actors: CaseActors) {
const { sessionCookie } = actors
const { seedChannel, seedServer } = actors.seed
async function serverIds(key: UserKey): Promise<string[]> {
- const response = await fetch(`${WEB_URL}/api/community/servers`, {
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/servers`, {
headers: { Cookie: sessionCookie(key), Origin: WEB_URL },
})
expect(response.status).toBe(200)
@@ -63,9 +64,9 @@ function deferred<T>(): Deferred<T> {
}
async function firstTextChannelId(page: Page, serverId: string): Promise<string> {
- const response = await page.request.get(
- `/api/community/servers/${serverId}/channels`,
- )
+ const response = await confirmCommunityFixtureApiResponse(page.request.get(
+ `/api/community/servers/${serverId}/channels`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS },
+ ))
expect(response.status()).toBe(200)
const body = await response.json() as {
channels: Array<{ id: string; type: string; parentChannelId?: string | null }>
@@ -213,7 +214,7 @@ test("deleting the only Server replaces once to Home", async ({ caseActors }) =>
await clickDeleteServer(page, route.serverId, async () => {
expect(await serverIds(key)).toEqual([route.serverId])
- const membershipResponse = await page.request.get(`/api/community/servers/${route.serverId}/members`)
+ const membershipResponse = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/servers/${route.serverId}/members`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(membershipResponse.status()).toBe(200)
const body = await membershipResponse.json() as { members: Array<{ userId: string }> }
expect(body.members.map((member) => member.userId)).toContain(userId(key))
@@ -409,11 +410,7 @@ test("a failed DELETE keeps the current route and emits no success frame", async
await request.continue()
return
}
- await request.fulfill({
- status: 500,
- contentType: "application/json",
- body: JSON.stringify({ error: "forced delete failure" }),
- })
+ await request.fulfill(currentCommunityFixtureError("forced delete failure", 500))
})
const response = page.waitForResponse((candidate) => (
candidate.request().method() === "DELETE"
diff --git a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
index 313b06869..8fd9ffd0a 100644
--- a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
+++ b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./_fixtures/business-contract"
import type { Page, Route } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
@@ -8,7 +9,7 @@ import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"
async function prepareCase(actors: CaseActors) {
const { sessionCookie } = actors
async function setReadCheckpoint(channelId: string, messageId: string): Promise<void> {
- const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
method: "PUT",
headers: {
Cookie: sessionCookie("alice"),
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 ed68a68c5..9eecb8488 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,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import { expectInertBackground } from "./_fixtures/inert-background"
import type { Page, Request, Route, TestInfo } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
@@ -156,7 +157,7 @@ async function holdCommunityReads(page: Page, caseResources: CaseResources) {
caseResources.own(release, async (captured) => { captured() })
let hits = 0
await page.route("**/api/community/**", async (route) => {
- if (route.request().method() !== "GET") {
+ if (route.request().method() !== "GET" || new URL(route.request().url()).pathname === "/api/community/users/me/profile") {
await route.continue()
return
}
@@ -170,10 +171,10 @@ async function holdCommunityReads(page: Page, caseResources: CaseResources) {
async function serveOutdatedMachine(page: Page) {
await page.route(url => url.pathname === "/api/community/machines", async (route) => {
const optional = new URL(route.request().url()).searchParams.get("view") === "observations"
- await route.fulfill({
+ await route.fulfill({ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
status: 200,
contentType: "application/json",
- body: JSON.stringify(optional ? { quotas: [{ machineId: outdatedMachine.id, quota: [] }] } : { machines: [outdatedMachine] }),
+ body: JSON.stringify(optional ? { quotas: [{ machineId: outdatedMachine.id, quota: [] }] } : { machines: [(({ quota: _quota, ...identity }) => identity)(outdatedMachine)], complete: true }),
})
})
}
diff --git a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts
index f3525d30d..50bbcee16 100644
--- a/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts
+++ b/src/web/src/test/e2e-ui/63-mobile-notification-chat-route.spec.ts
@@ -1,5 +1,7 @@
+import type { z } from "zod"
+import { communityFixtureFetch } from "./_fixtures/business-contract"
import { devices, type Page } from "@playwright/test"
-import { COMMUNITY_CONTRACT_HEADER, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityConversationEntryRead } from "@alook/shared"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityConversationEntryRead, CommunityMessageReadSchema } from "@alook/shared"
import { expect, test } from "./_fixtures/case-fixture"
import { composerEditable } from "./_fixtures/actions"
import { expectPublicCommunityDocument } from "./_fixtures/community-ssr-frame"
@@ -76,13 +78,13 @@ async function foregroundActivation(page: Page, activation: Activation) {
type MessageDoorEvidence = {
status: number
- payload: { id?: string; channelId?: string }
+ payload: z.infer<typeof CommunityMessageReadSchema>
}
test.describe("mobile notification chat routes (native bridge simulation)", () => {
async function prepareCase1(actors: CaseActors) {
async function deleteAsAlice(path: string) {
- const response = await fetch(`${WEB_URL}${path}`, { method: "DELETE", headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })
+ const response = await communityFixtureFetch(`${WEB_URL}${path}`, { method: "DELETE", headers: { Cookie: sessionCookie("alice"), Origin: WEB_URL } })
expect(response.ok, `${path}: ${response.status}`).toBeTruthy()
}
async function captureMessageDoor(page: Page, targetId: string, messageId: string) {
@@ -124,7 +126,7 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
const dmId: string = await seedDm("alice", userId("bob"))
const dmMessageId: string = await seedDmMessage("alice", dmId, "DM notification route evidence")
const seqs = await Promise.all([[dmId, dmMessageId], [channelId, channelMessageId]].map(async ([targetId, messageId]) => {
- const response = await fetch(`${WEB_URL}/api/community/channels/${targetId}/messages?anchor=${messageId}&limit=1`, { headers: { Cookie: sessionCookie("bob") } })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${targetId}/messages?anchor=${messageId}&limit=1`, { headers: { Cookie: sessionCookie("bob") } })
expect(response.status).toBe(200)
const payload = await response.json() as {
messages: Array<{
@@ -165,7 +167,9 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
const evidence = door.evidence()
if (evidence) {
expect(evidence.status).toBe(200)
- expect(evidence.payload.id).toBe(messageId)
+ expect(evidence.payload.contractVersion).toBe(BUSINESS_SCHEMA_VERSION)
+ expect(evidence.payload.message.id).toBe(messageId)
+ expect(evidence.payload.message.channelId).toBe(targetId)
expect(evidence.payload.channelId).toBe(targetId)
}
else expect(door.requestCount()).toBe(0)
@@ -301,13 +305,13 @@ test.describe("mobile notification chat routes (native bridge simulation)", () =
laterIds.push(await actors.seed.seedMessage("alice", channelId, `Later window message ${index}`))
}
const readPointer = laterIds[DEFAULT_MESSAGE_PAGE_SIZE]
- const checkpoint = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ const checkpoint = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
method: "PUT",
headers: { Cookie: actors.sessionCookie("bob"), Origin: WEB_URL, "Content-Type": "application/json" },
body: JSON.stringify({ lastReadMessageId: readPointer }),
})
expect(checkpoint.ok).toBe(true)
- const defaultResponse = await fetch(`${WEB_URL}/api/community/channels/${channelId}/messages?entry=1`, { headers: { Cookie: actors.sessionCookie("bob"), [COMMUNITY_CONTRACT_HEADER]: "3" } })
+ const defaultResponse = await communityFixtureFetch(`${WEB_URL}/api/community/channels/${channelId}/messages?entry=1`, { headers: { Cookie: actors.sessionCookie("bob"), [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) } })
expect(defaultResponse.ok, `entry precondition status ${defaultResponse.status}`).toBe(true)
const defaultEntry = await defaultResponse.json() as CommunityConversationEntryRead
expect(defaultEntry.selection).toEqual({ reason: "read_pointer", anchorMessageId: readPointer })
diff --git a/src/web/src/test/e2e-ui/64-billing-contact.spec.ts b/src/web/src/test/e2e-ui/64-billing-contact.spec.ts
index 83f7a8845..eff01a020 100644
--- a/src/web/src/test/e2e-ui/64-billing-contact.spec.ts
+++ b/src/web/src/test/e2e-ui/64-billing-contact.spec.ts
@@ -1,3 +1,4 @@
+import { currentCommunityFixtureError } from "./_fixtures/business-contract"
import { expect, test } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -16,7 +17,7 @@ test("plan Contact stays usable without billing data and preserves the plan tab"
actors.onCleanup(async () => { releaseBilling() })
await page.route("**/api/community/billing", async (route) => {
await billingGate
- await route.fulfill({ status: 503, contentType: "application/json", body: JSON.stringify({ error: "Unavailable" }) })
+ await route.fulfill(currentCommunityFixtureError("Unavailable", 503))
})
await page.goto("/c/me/friends?settings=billing")
const panel = page.getByTestId(tid.billingSheet)
diff --git a/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.ts b/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.ts
index 89f68604f..73aed1007 100644
--- a/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.ts
+++ b/src/web/src/test/e2e-ui/64-mobile-parent-return.spec.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import type { Page, Request, Route } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import type { CaseResources } from "./_fixtures/case-fixture"
@@ -64,15 +65,15 @@ for (const parentType of ["forum", "text"] as const) {
const back = foreground.getByRole("banner").getByRole("button", { name: "Back", exact: true })
await expect(back).toBeVisible()
const [childResponse, parentResponse] = await Promise.all([
- page.request.get(new URL(`/api/community/channels/${childId}`, page.url()).href),
- page.request.get(new URL(`/api/community/channels/${parentId}`, page.url()).href),
+ confirmCommunityFixtureApiResponse(page.request.get(new URL(`/api/community/channels/${childId}`, page.url()).href, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })),
+ confirmCommunityFixtureApiResponse(page.request.get(new URL(`/api/community/channels/${parentId}`, page.url()).href, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })),
])
expect(childResponse.status()).toBe(200)
expect(parentResponse.status()).toBe(200)
- const channel = await childResponse.json() as {
+ const { channel } = await childResponse.json() as { channel: {
id: string; serverId: string; parentChannelId: string
- }
- const parent = await parentResponse.json() as { id: string; type: string }
+ } }
+ const { channel: parent } = await parentResponse.json() as { channel: { id: string; type: string } }
expect(channel).toMatchObject({ id: childId, serverId, parentChannelId: parentId })
expect(parent).toMatchObject({ id: parentId, type: parentType })
diff --git a/src/web/src/test/e2e-ui/67-text-sidebar-threads.spec.ts b/src/web/src/test/e2e-ui/67-text-sidebar-threads.spec.ts
index 3edbaceeb..121c76cd3 100644
--- a/src/web/src/test/e2e-ui/67-text-sidebar-threads.spec.ts
+++ b/src/web/src/test/e2e-ui/67-text-sidebar-threads.spec.ts
@@ -1,6 +1,7 @@
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
test("participating text threads share sidebar limits, retention and live membership with forums", async ({ caseActors }, testInfo) => {
test.setTimeout(180_000)
@@ -16,7 +17,7 @@ test("participating text threads share sidebar limits, retention and live member
const viewer = await actors.asUser("bob", { viewport: { width: 1440, height: 1000 }, reducedMotion: "reduce" })
const bobId = actors.userId("bob")
const add = async (id: string) => {
- const response = await owner.page.request.post(`/api/community/channels/${id}/participants`, { data: { userId: bobId } })
+ const response = await confirmCommunityFixtureApiResponse(owner.page.request.post(`/api/community/channels/${id}/participants`, { data: { userId: bobId }, headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(response.status()).toBe(201)
}
const threads: string[] = []
@@ -40,13 +41,13 @@ test("participating text threads share sidebar limits, retention and live member
}))
const query = new URLSearchParams({ type: "thread", parentType: "forum,text", participating: "true", activeWithin: "72h", limitPerParent: "5", include: "parentMessage" })
const endpoint = `/api/community/servers/${serverId}/channels?${query}`
- const canonicalResponse = await page.request.get(endpoint)
+ const canonicalResponse = await confirmCommunityFixtureApiResponse(page.request.get(endpoint, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(canonicalResponse.status()).toBe(200)
const canonical = await canonicalResponse.json() as { canonicalChannels: Array<{ id: string; parentChannelId: string }> }
expect(canonical.canonicalChannels.filter((row) => row.parentChannelId === textId)).toHaveLength(5)
expect(canonical.canonicalChannels.map((row) => row.id)).not.toContain(excludedId)
expect(canonical.canonicalChannels.map((row) => row.id)).not.toContain(privateThread)
- const legacyResponse = await page.request.get(endpoint.replace("forum%2Ctext", "forum"))
+ const legacyResponse = await confirmCommunityFixtureApiResponse(page.request.get(endpoint.replace("forum%2Ctext", "forum"), { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(legacyResponse.status()).toBe(200)
const legacy = await legacyResponse.json() as { canonicalChannels: Array<{ id: string }> }
expect(legacy.canonicalChannels.map((row) => row.id)).toEqual([forumThread])
@@ -66,7 +67,7 @@ test("participating text threads share sidebar limits, retention and live member
await page.goto(`/c/channels/${serverId}/${threads[0]}`, { waitUntil: "commit" })
await expect(sidebarRow(threads[0])).toBeVisible()
await expect(sidebarRow(threads[0])).toHaveAttribute("aria-current", "page")
- const retainedResponse = await page.request.get(`${endpoint}&retainId=${threads[0]}`)
+ const retainedResponse = await confirmCommunityFixtureApiResponse(page.request.get(`${endpoint}&retainId=${threads[0]}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(retainedResponse.status()).toBe(200)
const retained = await retainedResponse.json() as { retainedChannel: { id: string } }
expect(retained.retainedChannel.id).toBe(threads[0])
@@ -75,7 +76,7 @@ test("participating text threads share sidebar limits, retention and live member
await expect(sidebarRow(threads[6])).toBeVisible()
await add(excludedId)
await expect(sidebarRow(excludedId)).toBeVisible()
- const remove = await page.request.delete(`/api/community/channels/${excludedId}/participants/${bobId}`)
+ const remove = await confirmCommunityFixtureApiResponse(page.request.delete(`/api/community/channels/${excludedId}/participants/${bobId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(remove.status()).toBe(204)
await expect(sidebarRow(excludedId)).toHaveCount(0)
await seed.seedMessage("alice", threads[0], "Live activity lifts the oldest thread")
@@ -83,7 +84,7 @@ test("participating text threads share sidebar limits, retention and live member
const ordered = await page.locator(`[data-testid^="${tid.forumSidebarThread("")}"]`).evaluateAll((rows) => rows.map((row) => row.getAttribute("data-testid")))
expect(ordered.indexOf(tid.forumSidebarThread(threads[0]))).toBeLessThan(ordered.indexOf(tid.forumSidebarThread(threads[6])))
await expect.poll(() => events.some((event) => JSON.stringify(event).includes(excludedId))).toBe(true)
- const membershipResponse = await page.request.get(`/api/community/channels/${threads[0]}/members`)
+ const membershipResponse = await confirmCommunityFixtureApiResponse(page.request.get(`/api/community/channels/${threads[0]}/members?relation=notify`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(membershipResponse.status()).toBe(200)
const membership = await membershipResponse.json() as { members: Array<{ userId: string }> }
expect(membership.members.map((member) => member.userId)).toContain(bobId)
diff --git a/src/web/src/test/e2e-ui/68-bot-memberships.spec.ts b/src/web/src/test/e2e-ui/68-bot-memberships.spec.ts
index e689c9ade..adf503e7b 100644
--- a/src/web/src/test/e2e-ui/68-bot-memberships.spec.ts
+++ b/src/web/src/test/e2e-ui/68-bot-memberships.spec.ts
@@ -1,4 +1,5 @@
-import { COMMUNITY_BOT_ACTOR_HEADER, WS_EVENTS } from "@alook/shared"
+import { currentCommunityFixtureError } from "./_fixtures/business-contract"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_BOT_ACTOR_HEADER, COMMUNITY_CONTRACT_HEADER, WS_EVENTS, admitCommunityBrowserEventBatch, decodeCommunityBrowserEvent, isCommunityBrowserEventBatchCandidate, type CommunityWsEvent } from "@alook/shared"
import { spawnSync } from "node:child_process"
import type { Page } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
@@ -9,10 +10,10 @@ import { tid } from "./_fixtures/testids"
import { REPO_ROOT, WEB_URL } from "./_setup/paths"
type Bot = { id: string; name: string; runnerKey: string }
-type MembershipEvent = { type: string; wireType?: string; userId?: string; channelId?: string; serverId?: string; relation?: string; present?: boolean }
+type MembershipEvent = Extract<CommunityWsEvent, { type: typeof WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE | typeof WS_EVENTS.MEMBER_LEAVE }>
async function prepareMembershipCase(actors: CaseActors, resources: CaseResources) {
- const headers = (role: "alice" | "bob" = "alice") => ({ Cookie: actors.sessionCookie(role), Origin: WEB_URL, "Content-Type": "application/json" })
+ const headers = (role: "alice" | "bob" = "alice") => ({ Cookie: actors.sessionCookie(role), Origin: WEB_URL, "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) })
const call = (path: string, method = "GET", body?: unknown, extra: Record<string, string> = {}) => fetch(`${WEB_URL}${path}`, {method, headers:{...headers(),...extra}, ...(body === undefined ? {} : {body:JSON.stringify(body)})})
const pair = await call("/api/community/machines/pair", "POST")
expect(pair.status).toBe(200)
@@ -80,13 +81,16 @@ async function openMemberships(page: Page, bot: Bot) {
function observeMembershipEvents(page: Page) {
const events: MembershipEvent[] = []
- page.on("websocket", socket => socket.on("framereceived", ({payload}) => {
+ page.on("websocket", socket => socket.on("framereceived", async ({payload}) => {
const text = String(payload)
if (!text.startsWith("{")) return
- const event = JSON.parse(text) as MembershipEvent & {events?:MembershipEvent[]}
- for (const item of event.events ?? [event]) {
- if (item.type === WS_EVENTS.CHANNEL_MEMBER_REMOVE) events.push({...item,wireType:item.type,type:WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,relation:"access",present:false})
- else if (([WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE,WS_EVENTS.MEMBER_LEAVE] as string[]).includes(item.type)) events.push(item)
+ const frame: unknown = JSON.parse(text)
+ const admitted = isCommunityBrowserEventBatchCandidate(frame)
+ ? await admitCommunityBrowserEventBatch(frame)
+ : decodeCommunityBrowserEvent(frame)
+ if (!admitted.ok) return
+ for (const item of "events" in admitted ? admitted.events : [admitted.event]) {
+ if (item.type === WS_EVENTS.CHANNEL_MEMBERSHIP_CHANGE || item.type === WS_EVENTS.MEMBER_LEAVE) events.push(item)
}
}))
return events
@@ -149,7 +153,7 @@ test("owned bot exits preserve other identities, child participation boundaries
requests++
expect(route.request().headers()[COMMUNITY_BOT_ACTOR_HEADER.toLowerCase()]).toBe(first.id)
expect(route.request().headers().authorization).toBeUndefined()
- if(fail){await route.fulfill({status:503,contentType:"application/json",body:JSON.stringify({error:"QA temporary failure"})});return}
+ if(fail){await route.fulfill(currentCommunityFixtureError("QA temporary failure",503));return}
const response = await route.fetch()
expect(response.status()).toBe(204)
captured()
@@ -243,7 +247,7 @@ test("membership loading and late responses stay bound to the selected bot on de
caseResources.own(releaseRead,async r=>r())
await page.route("**/api/community/servers/channels",async route=>{
if(route.request().headers()[COMMUNITY_BOT_ACTOR_HEADER.toLowerCase()]!==first.id){await route.continue();return}
- if(fail){await failureGate;await route.fulfill({status:503,contentType:"application/json",body:JSON.stringify({error:"QA loading unavailable"})});return}
+ if(fail){await failureGate;await route.fulfill(currentCommunityFixtureError("QA loading unavailable",503));return}
if(!hold){await route.continue();return}
const response = await route.fetch()
expect(response.status()).toBe(200)
diff --git a/src/web/src/test/e2e-ui/_fixtures/business-contract.ts b/src/web/src/test/e2e-ui/_fixtures/business-contract.ts
new file mode 100644
index 000000000..f26256fca
--- /dev/null
+++ b/src/web/src/test/e2e-ui/_fixtures/business-contract.ts
@@ -0,0 +1,31 @@
+import { BUSINESS_SCHEMA_VERSION } from "../../../../../shared/src/business-schema-version"
+import { COMMUNITY_CONTRACT_HEADER } from "../../../../../shared/src/community-contract"
+
+export function assertCurrentCommunityFixtureResponse(response: Response) {
+ if (response.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) {
+ throw new Error(`Fixture response did not confirm current business version ${BUSINESS_SCHEMA_VERSION}`)
+ }
+}
+
+export async function communityFixtureFetch(input: string | URL, init?: RequestInit): Promise<Response> {
+ const url = new URL(input)
+ if (!url.pathname.startsWith("/api/community/")) throw new Error("Community fixture request requires a community route")
+ const headers = new Headers(init?.headers)
+ headers.set(COMMUNITY_CONTRACT_HEADER, String(BUSINESS_SCHEMA_VERSION))
+ const response = await fetch(input, { ...init, headers })
+ if (response.ok) assertCurrentCommunityFixtureResponse(response)
+ return response
+}
+
+export const CURRENT_COMMUNITY_FIXTURE_HEADERS = { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }
+
+export async function confirmCommunityFixtureApiResponse<T extends { ok(): boolean; headers(): Record<string, string> }>(pending: Promise<T>): Promise<T> {
+ const response = await pending
+ if (response.ok() && Object.entries(response.headers()).find(([name]) => name.toLowerCase() === COMMUNITY_CONTRACT_HEADER.toLowerCase())?.[1] !== String(BUSINESS_SCHEMA_VERSION)) throw new Error("Fixture API response did not confirm current business version")
+ return response
+}
+
+export function currentCommunityFixtureError(message: string, status: number) {
+ const code = status === 401 ? "unauthenticated" : status === 403 ? "not_allowed" : status === 404 ? "not_found" : status === 409 ? "idempotency_conflict" : status === 429 ? "rate_limited" : status >= 500 ? "temporarily_unavailable" : "invalid_input"
+ return { status, headers: CURRENT_COMMUNITY_FIXTURE_HEADERS, contentType: "application/json", body: JSON.stringify({ contractVersion: BUSINESS_SCHEMA_VERSION, error: { code, message, retryable: status === 429 || status >= 500 } }) }
+}
diff --git a/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts b/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts
index a95036e5a..13031503b 100644
--- a/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/case-fixture.ts
@@ -1,3 +1,5 @@
+import { assertCaseProfileBaseline } from "./case-profile-baseline"
+import { communityFixtureFetch } from "./business-contract"
import { createNaturalVisibilityActor } from "./natural-visibility-actor"
import type { APIResponse, BrowserContext, BrowserContextOptions, Page, Response as PlaywrightResponse, TestInfo } from "@playwright/test"
import { createHash } from "crypto"
@@ -180,7 +182,7 @@ export const test = base.extend<{ caseActors: CaseExitOwner["allocate"]; caseRes
return state.cookies.filter((cookie) => cookie.name.startsWith("better-auth")).map((cookie) => `${cookie.name}=${cookie.value}`).join("; ")
}
const read = async (key: UserKey, path: string): Promise<Record<string, unknown>> => {
- const response = await retrySeedRequest(() => fetch(`${WEB_URL}${path}`, { headers: { Cookie: sessionCookie(key), Origin: WEB_URL } }))
+ const response = await retrySeedRequest(() => communityFixtureFetch(`${WEB_URL}${path}`, { headers: { Cookie: sessionCookie(key), Origin: WEB_URL } }))
if (!response.ok) throw new Error(`Case baseline ${key} GET ${path} failed (${response.status})`)
const body = await response.json() as Record<string, unknown>
if (!body || typeof body !== "object" || body.stale === true || body.truncated === true) throw new Error(`Case baseline ${key} GET ${path} is incomplete`)
@@ -320,8 +322,7 @@ export const test = base.extend<{ caseActors: CaseExitOwner["allocate"]; caseRes
})
originalSessions.set(key, sessionCookie(key))
const profile = await read(key, "/api/community/users/me/profile")
- if (profile.id !== user(key).userId || profile.name !== user(key).name) throw new Error(`Case baseline ${key} has a different profile identity`)
- if (profile.aboutMe !== "" || profile.avatarVersion !== 0 || profile.bannerColor !== null || profile.statusEmoji !== null || profile.statusText !== "") throw new Error(`Case baseline ${key} has modified profile defaults`)
+ assertCaseProfileBaseline(profile, user(key), key)
await Promise.all([
assertEmpty(key, "/api/community/servers", "servers"),
assertEmpty(key, "/api/community/users/me/server-folders", "folders"),
diff --git a/src/web/src/test/e2e-ui/_fixtures/case-profile-baseline.ts b/src/web/src/test/e2e-ui/_fixtures/case-profile-baseline.ts
new file mode 100644
index 000000000..89ee7037c
--- /dev/null
+++ b/src/web/src/test/e2e-ui/_fixtures/case-profile-baseline.ts
@@ -0,0 +1,7 @@
+import { CommunitySelfProfileReadSchema } from "@alook/shared"
+
+export function assertCaseProfileBaseline(value: unknown, actor: { userId: string; name: string }, key: string) {
+ const profile = CommunitySelfProfileReadSchema.parse(value)
+ if (profile.id !== actor.userId || profile.name !== actor.name) throw new Error(`Case baseline ${key} has a different profile identity`)
+ if (profile.aboutMe !== "" || profile.avatarVersion !== 0 || profile.bannerColor !== null || profile.statusEmoji !== null || profile.statusText !== null) throw new Error(`Case baseline ${key} has modified profile defaults`)
+}
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 60024c417..9ab597823 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
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./business-contract"
import { expectInertBackground } from "./inert-background"
import type {
BrowserContext,
@@ -82,7 +83,7 @@ async function holdCommunityReads(page: Page, resources?: CaseResources) {
resources?.own(release, async (captured) => { captured() })
let hits = 0
await page.route("**/api/community/**", async (route) => {
- if (route.request().method() !== "GET") {
+ if (route.request().method() !== "GET" || new URL(route.request().url()).pathname === "/api/community/users/me/profile") {
await route.continue()
return
}
@@ -157,7 +158,7 @@ async function holdRequest(page: Page, pattern: string) {
}
async function pairMachine(actors: CaseActors, resources: CaseResources) {
- const pair = await fetch(`${WEB_URL}/api/community/machines/pair`, {
+ const pair = await communityFixtureFetch(`${WEB_URL}/api/community/machines/pair`, {
method: "POST",
headers: { Cookie: actors.sessionCookie("alice"), Origin: WEB_URL },
})
@@ -184,7 +185,7 @@ async function pairMachine(actors: CaseActors, resources: CaseResources) {
expect(activate.status).toBe(200)
const { machineId } = await activate.json() as { machineId: string }
resources.own(machineId, async (id) => {
- const response = await fetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", headers: { Cookie: actors.sessionCookie("alice"), Origin: WEB_URL } })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", headers: { Cookie: actors.sessionCookie("alice"), Origin: WEB_URL } })
expect([204, 404]).toContain(response.status)
})
activationProof.response = activate
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-machine.ts b/src/web/src/test/e2e-ui/_fixtures/community-machine.ts
index 21f46b58a..5282643f5 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-machine.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-machine.ts
@@ -1,3 +1,4 @@
+import { communityFixtureFetch } from "./business-contract"
import { createRequire } from "node:module"
import { resolve } from "node:path"
import { expect } from "@playwright/test"
@@ -42,7 +43,7 @@ export function connectMachine(credential: string, resources: CaseResources, sco
socket.once("close", () => reject(new Error("Machine socket closed before ready")))
})
const readMachine = async () => {
- const response = await fetch(`${WEB_URL}/api/community/machines`, { headers: scope.headers })
+ const response = await communityFixtureFetch(`${WEB_URL}/api/community/machines`, { headers: scope.headers })
expect(response.status).toBe(200)
const body = await response.json() as { machines: CommunityMachineSummary[] }
return body.machines.find(machine => machine.id === scope.machineId)
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 54e8d7aba..52bd8f88f 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
@@ -1,4 +1,4 @@
-import type { CommunityWsEvent } from "@alook/shared"
+import { admitCommunityBrowserEventBatch, decodeCommunityBrowserEvent, isCommunityBrowserEventBatchCandidate, type CommunityWsEvent } from "@alook/shared"
import { expect, type BrowserContext, type Page, type Request } from "@playwright/test"
import { proxyCommunityWebSockets } from "./community-ws-proxy"
@@ -20,6 +20,8 @@ export async function notificationResponsesFinished(page: Page, paths = notifica
export function captureNotificationRequests(page: Page) {
const events: CommunityWsEvent[] = []
+ const rawFrames: string[] = []
+ let frameAdmission = Promise.resolve()
const requests: string[] = []
const pendingNotifications = new Set<Request>()
const requestIds = new Map<Request, number>()
@@ -28,19 +30,25 @@ export function captureNotificationRequests(page: Page) {
const record = (data: Record<string, unknown>) => timeline.push({ at: Date.now(), phase, ...data })
page.on("websocket", (socket) => {
socket.on("framereceived", ({ payload }) => {
- try {
- const frame = JSON.parse(payload.toString()) as CommunityWsEvent
- | { type: "community:events.batch"; events: CommunityWsEvent[] }
- | { type: "community:events.batch.v2"; events: CommunityWsEvent[] }
- record({ kind: "frame", type: frame.type })
- if (!frame.type.startsWith("community:")) return
- for (const event of frame.type === "community:events.batch" || frame.type === "community:events.batch.v2" ? frame.events : [frame]) {
- events.push(event)
- record({ kind: "event", type: event.type,
- channelId: "channelId" in event ? event.channelId : undefined,
- messageId: event.type === "community:message.create" ? event.message.id : undefined })
- }
- } catch {}
+ const raw = payload.toString()
+ const received = { at: Date.now(), phase }
+ rawFrames.push(raw)
+ frameAdmission = frameAdmission.then(async () => {
+ try {
+ const frame: unknown = JSON.parse(raw)
+ record({ ...received, kind: "frame", type: typeof frame === "object" && frame !== null && "type" in frame ? frame.type : undefined })
+ const admitted = isCommunityBrowserEventBatchCandidate(frame)
+ ? await admitCommunityBrowserEventBatch(frame)
+ : decodeCommunityBrowserEvent(frame)
+ if (!admitted.ok) return
+ for (const event of "events" in admitted ? admitted.events : [admitted.event]) {
+ events.push(event)
+ record({ ...received, admittedAt: Date.now(), kind: "event", type: event.type,
+ channelId: "channelId" in event ? event.channelId : undefined,
+ messageId: event.type === "community:message.create" ? event.message.id : undefined })
+ }
+ } catch {}
+ })
})
})
page.on("request", (request) => {
@@ -58,7 +66,8 @@ export function captureNotificationRequests(page: Page) {
pendingNotifications.delete(request)
record({ kind: "request-failed", id: requestIds.get(request), path: new URL(request.url()).pathname })
})
- return { events, requests, pendingNotifications, timeline,
+ return { events, rawFrames, requests, pendingNotifications, timeline,
+ framesSettled: () => frameAdmission,
phase: (next: string) => { phase = next; record({ kind: "phase" }) } }
}
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
index 169a3136e..819907998 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
@@ -22,7 +22,7 @@ export type CapturedConnectionFrame = {
direction: "client-to-server" | "server-to-client"
type: "auth" | "auth.ok" | "connection.ping" | "connection.pong" | "raw.ping" | "raw.pong"
nonce?: string
- communityContract?: 1 | 2
+ communityContract?: number
at: number
}
@@ -104,7 +104,7 @@ function parseConnectionFrame(
direction,
type: value.type,
...(typeof value.nonce === "string" ? { nonce: value.nonce } : {}),
- ...(value.communityContract === 1 || value.communityContract === 2 ? { communityContract: value.communityContract } : {}),
+ ...(typeof value.communityContract === "number" ? { communityContract: value.communityContract } : {}),
at: Date.now(),
}
} catch {
diff --git a/src/web/src/test/e2e-ui/_fixtures/public-static-qa.ts b/src/web/src/test/e2e-ui/_fixtures/public-static-qa.ts
index 5d62f5ee6..f29782d8e 100644
--- a/src/web/src/test/e2e-ui/_fixtures/public-static-qa.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/public-static-qa.ts
@@ -1,3 +1,5 @@
+import { BUSINESS_SCHEMA_VERSION } from "../../../../../shared/src/business-schema-version"
+import { communityFixtureFetch } from "./business-contract"
import { createHash } from "node:crypto"
import { resolve } from "node:path"
import { expect, type BrowserContext, type CDPSession, type Page, type Route, type TestInfo, type Worker } from "@playwright/test"
@@ -497,7 +499,7 @@ export async function qaApi<T>(actors: CaseActors, resources: CaseResources, rol
const request = observation?.start(init?.method ?? "GET", path)
let response: Response
try {
- response = await fetch(`${WEB_URL}${path}`, { ...init, signal: qaDeadlineSignal(resources), headers: { Cookie: actors.sessionCookie(role), Origin: WEB_URL, ...(init?.body ? { "content-type": "application/json" } : {}), ...init?.headers } })
+ response = await communityFixtureFetch(`${WEB_URL}${path}`, { ...init, signal: qaDeadlineSignal(resources), headers: { Cookie: actors.sessionCookie(role), Origin: WEB_URL, ...(init?.body ? { "content-type": "application/json" } : {}), ...init?.headers } })
} catch (error) {
if (request !== undefined) observation!.failed(request)
throw error
@@ -552,7 +554,7 @@ export async function ownD1WsProbe(actors: CaseActors, resources: CaseResources,
const machines = await qaApi<{ machines: Array<{ id: string; hostname: string }> }>(actors, resources, "alice", "/api/community/machines")
const ids = new Set([state.machineId, ...machines.body.machines.filter(value => value.hostname.startsWith(hostname)).map(value => value.id)].filter(Boolean))
for (const id of ids) {
- const deleted = await fetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", signal: qaDeadlineSignal(resources), headers: { Cookie: actors.sessionCookie("alice"), Origin: WEB_URL } })
+ const deleted = await communityFixtureFetch(`${WEB_URL}/api/community/machines/${id}`, { method: "DELETE", signal: qaDeadlineSignal(resources), headers: { Cookie: actors.sessionCookie("alice"), Origin: WEB_URL } })
expect(deleted.status).toBe(204)
}
expect((await qaApi<{ machines: Array<{ id: string; hostname: string }> }>(actors, resources, "alice", "/api/community/machines")).body.machines.some(value => ids.has(value.id) || value.hostname.startsWith(hostname))).toBe(false)
@@ -812,7 +814,7 @@ export async function deviceSnapshot(page: Page): Promise<DeviceSnapshot> {
const records = keys.result.map((key, index) => ({ key: String(key), encoded: JSON.stringify(values.result[index], (_, value) => value instanceof Map ? { nativeMap: [...value.entries()].sort(([a], [b]) => String(a).localeCompare(String(b))) } : value) })).sort((a, b) => a.key.localeCompare(b.key))
const epoch = values.result[keys.result.indexOf("alook:qc:device-epoch")]
db.close()
- resolveRead({ epoch, records, payloadKeys: records.filter(record => /^alook:qc:[^:]+:[^:]+(?::application)?:client$/.test(record.key)).map(record => record.key) })
+ resolveRead({ epoch, records, payloadKeys: records.filter(record => /^alook:(?:qc:[^:]+|business:v\d+):[^:]+(?::application)?:client$/.test(record.key)).map(record => record.key) })
}
tx.onabort = tx.onerror = () => { db.close(); reject(tx.error) }
}
@@ -824,14 +826,17 @@ export function preservedDeviceMetadata(snapshot: DeviceSnapshot) {
}
export async function insertArtificialRetiredResidual(page: Page, userId: string, captured: DeviceSnapshot) {
- const key = `alook:qc:cache:${userId}:client`
+ const key = `alook:business:v${BUSINESS_SCHEMA_VERSION}:${userId}:client`
const record = captured.records.find(record => record.key === key)
if (!record) throw new Error("Retired residual requires a captured real account payload")
const payload = JSON.parse(record.encoded) as unknown
if (typeof payload !== "string") throw new Error("Captured native community payload is not its real JSON string")
- const envelope = JSON.parse(payload) as { version: number; buster: string; clientState: unknown; channelFences: unknown[] }
- if (envelope.version !== 6 || envelope.buster !== "6" || !envelope.clientState || !Array.isArray(envelope.channelFences)) throw new Error("Captured real persistence envelope is not the forwarded version 6 contract")
- const keys = [key, `alook:qc:cache:${userId}:application:client`, `alook:qc:legacy:${userId}:client`]
+ const envelope = JSON.parse(payload) as { version: number; buster: string; clientState: unknown; channelFences: unknown[]; ownerEpochs?: { device: string; account: string } }
+ const accountRecord = captured.records.find(record => record.key === `alook:qc:cache:${userId}:account-epoch`)
+ const account = accountRecord ? JSON.parse(accountRecord.encoded) as unknown : undefined
+ if (envelope.version !== BUSINESS_SCHEMA_VERSION || envelope.buster !== String(BUSINESS_SCHEMA_VERSION) || !envelope.clientState || !Array.isArray(envelope.channelFences)
+ || !envelope.ownerEpochs || envelope.ownerEpochs.device !== captured.epoch || envelope.ownerEpochs.account !== account) throw new Error("Captured persistence envelope is not bound to the current business owner")
+ const keys = [key, `alook:business:v${BUSINESS_SCHEMA_VERSION}:${userId}:application:client`, `alook:qc:cache:${userId}:client`, `alook:qc:cache:${userId}:application:client`, `alook:qc:legacy:${userId}:client`]
const channelFixture = { channelId: crypto.randomUUID(), epoch: crypto.randomUUID(), deleted: true }
await page.evaluate(async ({ keys, payload, userId, channelFixture }) => new Promise<void>((resolveWrite, reject) => {
const request = indexedDB.open("keyval-store")
@@ -850,7 +855,7 @@ export async function insertArtificialRetiredResidual(page: Page, userId: string
tx.onabort = tx.onerror = () => { db.close(); reject(tx.error) }
}
}), { keys, payload, userId, channelFixture })
- return { preparation: "artificial retired account residual and native Map tombstone for an unused fixture channel UUID; compatibility keys copy captured community bytes only for physical deletion", keys, channelFixture, bytes: Buffer.byteLength(payload), sha256: createHash("sha256").update(payload).digest("hex") }
+ return { preparation: "artificial retired account residual and native Map tombstone for an unused fixture channel UUID; obsolete-key negatives copy current community bytes only for physical deletion; no restore or migration", keys, channelFixture, bytes: Buffer.byteLength(payload), sha256: createHash("sha256").update(payload).digest("hex") }
}
export async function observeDeviceClear(page: Page, resources: CaseResources, previousEpoch: string) {
@@ -882,7 +887,7 @@ export async function observeDeviceClear(page: Page, resources: CaseResources, p
retired = true
clearTimeout(timerState.value)
db!.close()
- resolveRead({ epoch, records, payloadKeys: records.filter(record => /^alook:qc:[^:]+:[^:]+(?::application)?:client$/.test(record.key)).map(record => record.key) })
+ resolveRead({ epoch, records, payloadKeys: records.filter(record => /^alook:(?:qc:[^:]+|business:v\d+):[^:]+(?::application)?:client$/.test(record.key)).map(record => record.key) })
}
}
probe()
diff --git a/src/web/src/test/e2e-ui/_fixtures/seed.ts b/src/web/src/test/e2e-ui/_fixtures/seed.ts
index 37b36097c..3fad3be9c 100644
--- a/src/web/src/test/e2e-ui/_fixtures/seed.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/seed.ts
@@ -1,3 +1,5 @@
+import { CommunityReadErrorSchema } from "../../../../../shared/src/community-resources"
+import { communityFixtureFetch, assertCurrentCommunityFixtureResponse } from "./business-contract"
import { WEB_URL } from "../_setup/paths"
import { sessionCookie, userId } from "./community-fixture"
import type { UserKey } from "../_setup/users"
@@ -29,7 +31,7 @@ type SeedIdentity = {
export function createSeed(identity: SeedIdentity) {
const { sessionCookie, userId } = identity
async function postRaw(key: UserKey, path: string, body?: unknown): Promise<Response> {
- return fetch(`${WEB_URL}${path}`, {
+ return communityFixtureFetch(`${WEB_URL}${path}`, {
method: "POST",
headers: {
Cookie: sessionCookie(key),
@@ -59,7 +61,7 @@ export function createSeed(identity: SeedIdentity) {
const errors: unknown[] = []
for (const serverId of serverIds) {
try {
- const response = await retrySeedRequest(() => fetch(`${WEB_URL}/api/community/servers/${serverId}`, {
+ const response = await retrySeedRequest(() => communityFixtureFetch(`${WEB_URL}/api/community/servers/${serverId}`, {
method: "DELETE",
headers: { Cookie: sessionCookie(owner), Origin: WEB_URL },
}))
@@ -119,11 +121,17 @@ export function createSeed(identity: SeedIdentity) {
// "Already a member" and counts as success (idempotent on a Playwright retry).
let lastStatus = 0
for (let attempt = 0; attempt < 3; attempt++) {
- const res = await fetch(`${WEB_URL}/api/community/invites/${token}/join`, {
+ const res = await communityFixtureFetch(`${WEB_URL}/api/community/invites/${token}/join`, {
method: "POST",
headers: { Cookie: sessionCookie(joiner), "Content-Type": "application/json", Origin: WEB_URL },
})
- if (res.ok || res.status === 400) return
+ if (res.ok) return
+ if (res.status === 400) {
+ assertCurrentCommunityFixtureResponse(res)
+ const error = CommunityReadErrorSchema.parse(await res.json())
+ if (error.error.message === "Already a member") return
+ throw new Error(`seedJoinServer join rejected: ${error.error.message}`)
+ }
lastStatus = res.status
if (!isRetryableSeedStatus(res.status)) break
await new Promise((r) => setTimeout(r, seedRetryDelayMs(res)))
@@ -176,7 +184,7 @@ export function createSeed(identity: SeedIdentity) {
// user, from the requester's friends list. Used to recover idempotently when a
// re-run (Playwright retry) finds the pair already friends.
async function findFriendshipId(requester: UserKey, targetUserId: string): Promise<string | undefined> {
- const res = await retrySeedRequest(() => fetch(
+ const res = await retrySeedRequest(() => communityFixtureFetch(
`${WEB_URL}/api/community/friends/accepted`,
{ headers: { Cookie: sessionCookie(requester), Origin: WEB_URL } },
))
@@ -197,8 +205,8 @@ export function createSeed(identity: SeedIdentity) {
}> {
const headers = { Cookie: sessionCookie(key), Origin: WEB_URL }
const [accepted, pending] = await Promise.all([
- retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/accepted`, { headers })),
- retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/pending`, { headers })),
+ retrySeedRequest(() => communityFixtureFetch(`${WEB_URL}/api/community/friends/accepted`, { headers })),
+ retrySeedRequest(() => communityFixtureFetch(`${WEB_URL}/api/community/friends/pending`, { headers })),
])
if (!accepted.ok) throw new Error(`listSeedRelationships accepted failed (${accepted.status})`)
if (!pending.ok) throw new Error(`listSeedRelationships pending failed (${pending.status})`)
@@ -209,7 +217,7 @@ export function createSeed(identity: SeedIdentity) {
}
async function deleteSeedRelationship(key: UserKey, id: string): Promise<Response> {
- return retrySeedRequest(() => fetch(`${WEB_URL}/api/community/friends/${id}`, {
+ return retrySeedRequest(() => communityFixtureFetch(`${WEB_URL}/api/community/friends/${id}`, {
method: "DELETE",
headers: { Cookie: sessionCookie(key), Origin: WEB_URL },
}))
@@ -287,8 +295,8 @@ export function createSeed(identity: SeedIdentity) {
{ userId: targetUserId },
))
if (!response.ok) throw new Error(`seedPendingFriendRequest request failed (${response.status})`)
- const body = (await response.json()) as { id?: string; friendship?: { id: string } | null }
- const id = body.id ?? body.friendship?.id
+ const body = (await response.json()) as { id: string }
+ const id = body.id
if (!id) throw new Error("seedPendingFriendRequest: no friendship id in response")
identity.onResourceCreated?.("friendship", id)
return id
@@ -340,8 +348,8 @@ export function createSeed(identity: SeedIdentity) {
throw new Error("seedFriendship: 409 but no accepted or pending friendship found")
}
if (!reqRes!.ok) throw new Error(`seedFriendship request failed (${reqRes!.status})`)
- const reqData = (await reqRes!.json()) as { id?: string; friendship?: { id: string } | null }
- const friendshipId = reqData.id ?? reqData.friendship?.id
+ const reqData = (await reqRes!.json()) as { id: string }
+ const friendshipId = reqData.id
if (!friendshipId) throw new Error("seedFriendship: no friendship id in response")
return acceptSeedFriendship(requester, addressee, targetUserId, {
id: friendshipId,
@@ -363,7 +371,7 @@ export function createSeed(identity: SeedIdentity) {
async function seedReaction(author: UserKey, messageId: string, emoji: string): Promise<void> {
identity.assertResource?.("message", messageId)
- const response = await retrySeedRequest(() => fetch(
+ const response = await retrySeedRequest(() => communityFixtureFetch(
`${WEB_URL}/api/community/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`,
{ method: "PUT", headers: { Cookie: sessionCookie(author), Origin: WEB_URL } },
))
@@ -373,7 +381,7 @@ export function createSeed(identity: SeedIdentity) {
async function seedMark(author: UserKey, channelId: string, messageId: string): Promise<void> {
identity.assertResource?.("channel", channelId)
identity.assertResource?.("message", messageId)
- const response = await retrySeedRequest(() => fetch(
+ const response = await retrySeedRequest(() => communityFixtureFetch(
`${WEB_URL}/api/community/messages/${messageId}/marks`,
{
method: "PUT",
@@ -436,7 +444,7 @@ export function createSeed(identity: SeedIdentity) {
async function renameUser(key: UserKey, name: string): Promise<void> {
let lastStatus = 0
for (let attempt = 0; attempt < 3; attempt++) {
- const res = await fetch(`${WEB_URL}/api/community/users/me/profile`, {
+ const res = await communityFixtureFetch(`${WEB_URL}/api/community/users/me/profile`, {
method: "PATCH",
headers: { Cookie: sessionCookie(key), "Content-Type": "application/json", Origin: WEB_URL },
body: JSON.stringify({ name }),
@@ -463,7 +471,7 @@ export function createSeed(identity: SeedIdentity) {
): Promise<{ id: string; name: string; discriminator: string }> {
identity.assertResource?.("server", serverId)
identity.assertResource?.("user", targetUserId)
- const res = await fetch(`${WEB_URL}/api/community/servers/${serverId}/members`, {
+ const res = await communityFixtureFetch(`${WEB_URL}/api/community/servers/${serverId}/members`, {
headers: { Cookie: sessionCookie(viewer), Origin: WEB_URL },
})
if (!res.ok) throw new Error(`memberInfo list failed (${res.status})`)
diff --git a/src/web/src/test/e2e-ui/_qa/public-static/clear.qa.ts b/src/web/src/test/e2e-ui/_qa/public-static/clear.qa.ts
index 7c1ec4a6d..b9dd8495b 100644
--- a/src/web/src/test/e2e-ui/_qa/public-static/clear.qa.ts
+++ b/src/web/src/test/e2e-ui/_qa/public-static/clear.qa.ts
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "../../_fixtures/business-contract"
import { expect, test } from "../../_fixtures/case-fixture"
import { communityFrameEvents, proxyCommunityWebSockets } from "../../_fixtures/community-ws-proxy"
import { gotoAfterUserWsAuth } from "../../_fixtures/actions"
@@ -80,7 +81,7 @@ test("real Alice logout and Bob login retain server facts while device Clear rem
const identity = await context.request.get("/api/ws/token?refresh=1")
expect(identity.status()).toBe(200)
expect((await identity.json()).userId).toBe(actors.userId("bob"))
- const denied = await context.request.get(`/api/community/channels/${aliceChannel}/messages`)
+ const denied = await confirmCommunityFixtureApiResponse(context.request.get(`/api/community/channels/${aliceChannel}/messages`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect([403, 404]).toContain(denied.status())
const retained = (await qaApi<{ messages: typeof bobMessagesBefore.body.messages }>(actors, caseResources, "bob", `/api/community/channels/${bobChannel}/messages`)).body.messages.find(message => message.id === bobMessage)
expect(retained).toEqual(original)
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
index 092e1851c..438f3b8bb 100644
--- 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
@@ -1,3 +1,4 @@
+import { CURRENT_COMMUNITY_FIXTURE_HEADERS, confirmCommunityFixtureApiResponse } from "./_fixtures/business-contract"
import { createRequire } from "node:module"
import { resolve } from "node:path"
import { readFileSync } from "node:fs"
@@ -7,7 +8,7 @@ import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "./_setup/paths"
import type { APIResponse, Page, Request, TestInfo } from "@playwright/test"
import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
import { expectPublicCommunityDocument, expectUniqueSsrCommunityFrame } from "./_fixtures/community-ssr-frame"
-import { PERSIST_CACHE_PREFIX } from "@/lib/query-persister"
+import { PERSIST_ACCOUNT_PREFIX, PERSIST_CACHE_PREFIX } from "@/lib/query-persister"
import { expect, test } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -642,7 +643,7 @@ async function holdOriginalPersistedRead(page: Page, viewerId: string, oldId: st
}
return request
}
- }, { key: `${PERSIST_CACHE_PREFIX}:${viewerId}:client`, accountKey: `${PERSIST_CACHE_PREFIX}:${viewerId}:account-epoch`, channelsKey: `${PERSIST_CACHE_PREFIX}:${viewerId}:account-epoch:channels`, oldId, newId })
+ }, { key: `${PERSIST_CACHE_PREFIX}:${viewerId}:client`, accountKey: `${PERSIST_ACCOUNT_PREFIX}:${viewerId}:account-epoch`, channelsKey: `${PERSIST_ACCOUNT_PREFIX}:${viewerId}:account-epoch:channels`, oldId, newId })
}
async function captureOriginalPersistedReadDiagnostics(page: Page, testInfo: TestInfo, label: string) {
@@ -668,7 +669,7 @@ async function releaseOriginalPersistedRead(page: Page) {
}
async function retiredAccountDiskState(page: Page, viewerId: string, channelId: string) {
- return page.evaluate(({ prefix, viewerId, channelId }) => new Promise<{ payloadAbsent: boolean; applicationPayloadAbsent: boolean; accountEpochPresent: boolean; scopeEpochPresent: boolean; channelsReset: boolean; oldChannelFenceAbsent: boolean }>((resolveState, reject) => {
+ return page.evaluate(({ prefix, accountPrefix, viewerId, channelId }) => new Promise<{ payloadAbsent: boolean; applicationPayloadAbsent: boolean; accountEpochPresent: boolean; scopeEpochPresent: boolean; channelsReset: boolean; oldChannelFenceAbsent: boolean }>((resolveState, reject) => {
const open = indexedDB.open("keyval-store")
open.onerror = () => reject(open.error ?? new Error("failed to inspect retired account"))
open.onsuccess = () => {
@@ -678,9 +679,10 @@ async function retiredAccountDiskState(page: Page, viewerId: string, channelId:
const namespace = `${prefix}:${viewerId}`
const payload = store.get(`${namespace}:client`)
const application = store.get(`${namespace}:application:client`)
- const account = store.get(`${namespace}:account-epoch`)
+ const accountNamespace = `${accountPrefix}:${viewerId}`
+ const account = store.get(`${accountNamespace}:account-epoch`)
const scope = store.get(`${namespace}:client:epoch`)
- const channels = store.get(`${namespace}:account-epoch:channels`)
+ const channels = store.get(`${accountNamespace}:account-epoch:channels`)
transaction.onabort = transaction.onerror = () => { db.close(); reject(transaction.error ?? new Error("retired account inspection failed")) }
transaction.oncomplete = () => {
const fences: unknown = channels.result
@@ -689,7 +691,7 @@ async function retiredAccountDiskState(page: Page, viewerId: string, channelId:
resolveState(result)
}
}
- }), { prefix: PERSIST_CACHE_PREFIX, viewerId, channelId })
+ }), { prefix: PERSIST_CACHE_PREFIX, accountPrefix: PERSIST_ACCOUNT_PREFIX, viewerId, channelId })
}
test("late original IDB cannot revive a DM after a real WS block", async ({ caseActors, caseResources }, testInfo) => {
@@ -734,10 +736,10 @@ test("late original IDB cannot revive a DM after a real WS block", async ({ case
await expect(alice.page.getByTestId(tid.composerInput)).toHaveCount(0)
expect(targetGets).toEqual([])
await expect.poll(() => proxy.connectionFrames.some(frame => frame.type === "auth.ok")).toBe(true)
- const blocked = await bob.page.request.post(`/api/community/users/${userId("alice")}/block`)
+ const blocked = await confirmCommunityFixtureApiResponse(bob.page.request.post(`/api/community/users/${userId("alice")}/block`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(blocked.status()).toBe(200)
await expect.poll(() => proxy.frames.some(frame => frame.type === "community:friend.block" && frame.userId === userId("bob"))).toBe(true)
- const denied = await alice.page.request.get(`/api/community/channels/${dmId}/messages?entry=1`, { headers: { "x-alook-community-contract": "3" } })
+ const denied = await confirmCommunityFixtureApiResponse(alice.page.request.get(`/api/community/channels/${dmId}/messages?entry=1`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(denied.status()).toBe(403)
await expect(alice.page.getByTestId(tid.message(oldId))).toHaveCount(0)
await expect(alice.page.getByTestId(tid.message(newId))).toHaveCount(0)
@@ -799,7 +801,7 @@ test("a real empty machine list is usable before optional observations or bots r
})
async function activateRealMachine(page: Page, caseResources: CaseResources) {
- const paired = await page.request.post("/api/community/machines/pair")
+ const paired = await confirmCommunityFixtureApiResponse(page.request.post("/api/community/machines/pair", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(paired.status()).toBe(200)
const { tokenId } = await paired.json() as { tokenId: string }
const activationProof: { response?: APIResponse; machineId?: string } = {}
@@ -813,7 +815,7 @@ async function activateRealMachine(page: Page, caseResources: CaseResources) {
})
expect(activated.status()).toBe(200)
const { machineId, credential } = await activated.json() as { machineId: string; credential: string }
- caseResources.own(machineId, async id => { const removed = await page.request.delete(`/api/community/machines/${id}`); expect([204, 404]).toContain(removed.status()) })
+ caseResources.own(machineId, async id => { const removed = await confirmCommunityFixtureApiResponse(page.request.delete(`/api/community/machines/${id}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS })); expect([204, 404]).toContain(removed.status()) })
activationProof.response = activated
activationProof.machineId = machineId
await pairingToken.close()
@@ -961,19 +963,19 @@ test("real machine status, removal and creation retire an older list response",
await connection.opened
connection.socket.send(JSON.stringify(HostReadyMessageSchema.parse({ type: "ready", runtimeReport: [{ id: "pi", status: "healthy" }], capabilities: [CONTROL_HEARTBEAT_CAPABILITY], runningAgents: [], hostname: first.hostname, platform: "linux", arch: "x64", daemonVersion: (JSON.parse(readFileSync(resolve(REPO_ROOT, "src/daemon/package.json"), "utf8")) as { version: string }).version })))
await expect.poll(() => proxy.frames.some(frame => frame.type === "community:machine.status" && frame.machineId === first.machineId && frame.status === "online")).toBe(true)
- const online = await page.request.get("/api/community/machines?view=list")
+ const online = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/machines?view=list", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(online.status()).toBe(200)
expect((await online.json()).machines).toEqual(expect.arrayContaining([expect.objectContaining({ id: first.machineId, status: "online" })]))
await connection.close()
await expect.poll(() => proxy.frames.some(frame => frame.type === "community:machine.status" && frame.machineId === first.machineId && frame.status === "offline")).toBe(true)
- const removed = await page.request.delete(`/api/community/machines/${first.machineId}`)
+ const removed = await confirmCommunityFixtureApiResponse(page.request.delete(`/api/community/machines/${first.machineId}`, { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(removed.status()).toBe(204)
await expect.poll(() => proxy.frames.some(frame => frame.type === "community:machine.removed" && frame.machineId === first.machineId)).toBe(true)
const second = await activateRealMachine(page, caseResources)
await expect.poll(() => proxy.frames.some(frame => frame.type === "community:machine.created" && (frame.machine as { id?: string } | undefined)?.id === second.machineId)).toBe(true)
await page.getByRole("link", { name: "Machines", exact: true }).click()
await expect(page.getByText(second.hostname, { exact: true })).toBeVisible()
- const current = await page.request.get("/api/community/machines?view=list")
+ const current = await confirmCommunityFixtureApiResponse(page.request.get("/api/community/machines?view=list", { headers: CURRENT_COMMUNITY_FIXTURE_HEADERS }))
expect(current.status()).toBe(200)
expect((await current.json()).machines.map((machine: { id: string }) => machine.id)).toEqual([second.machineId])
held.release()
diff --git a/src/web/src/test/e2e/auth.test.ts b/src/web/src/test/e2e/auth.test.ts
index 2aea3150b..73264873d 100644
--- a/src/web/src/test/e2e/auth.test.ts
+++ b/src/web/src/test/e2e/auth.test.ts
@@ -1,3 +1,4 @@
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
import { afterAll, describe, expect, it } from "vitest"
import { randomUUID } from "crypto"
import { signUp, signIn, sessionRequest, sqlRun } from "@alook/test-utils"
@@ -29,7 +30,7 @@ describe("auth", () => {
})
it("GET /api/community/users/me/profile without auth returns 401", async () => {
- const res = await fetch(`${APP_URL}/api/community/users/me/profile`)
+ const res = await fetch(`${APP_URL}/api/community/users/me/profile`, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_CONTRACT_VERSION) } })
expect(res.status).toBe(401)
})
diff --git a/src/web/src/test/e2e/community-rate-limit.test.ts b/src/web/src/test/e2e/community-rate-limit.test.ts
index 5f2d66625..e01efbd2a 100644
--- a/src/web/src/test/e2e/community-rate-limit.test.ts
+++ b/src/web/src/test/e2e/community-rate-limit.test.ts
@@ -11,7 +11,7 @@
*/
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
-import { DEV_WS_DO_URL, RATE_LIMITS, type RateLimitResult } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, DEV_WS_DO_URL, RATE_LIMITS, type RateLimitResult } from "@alook/shared"
import {
seedTestData,
cleanupTestData,
@@ -84,7 +84,7 @@ describe("community message rate limit — DO-backed", () => {
cookie,
{
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: { "Content-Type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_CONTRACT_VERSION) },
body: JSON.stringify({ content }),
},
)
diff --git a/src/web/src/test/e2e/device-code.test.ts b/src/web/src/test/e2e/device-code.test.ts
index 0fdae2f23..895369ffe 100644
--- a/src/web/src/test/e2e/device-code.test.ts
+++ b/src/web/src/test/e2e/device-code.test.ts
@@ -1,3 +1,4 @@
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
import { signUp, signIn, sessionRequest, tokenRequest, sqlRun } from "@alook/test-utils"
@@ -121,7 +122,7 @@ describe("device-code-flow", () => {
const tokenData = await tokenRes.json() as Record<string, unknown>
const accessToken = tokenData.access_token as string
- const meRes = await tokenRequest("/api/community/users/me/profile", accessToken)
+ const meRes = await tokenRequest("/api/community/users/me/profile", accessToken, { headers: { [COMMUNITY_CONTRACT_HEADER]: String(COMMUNITY_CONTRACT_VERSION) } })
expect(meRes.status).toBe(200)
const me = await meRes.json() as Record<string, unknown>
expect(me.name).toBe(testName)
diff --git a/src/web/src/test/e2e/message-delivery-retry.test.ts b/src/web/src/test/e2e/message-delivery-retry.test.ts
index cacd59d9c..84cdeb1a0 100644
--- a/src/web/src/test/e2e/message-delivery-retry.test.ts
+++ b/src/web/src/test/e2e/message-delivery-retry.test.ts
@@ -1,6 +1,7 @@
import { createServer, type Server } from "node:http"
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"
-import type { MessageDeliveryBatch } from "@alook/shared"
+import { messageResourceFixture, profileResourceFixture } from "../community-resource-fixtures"
+import { BUSINESS_SCHEMA_VERSION, type MessageDeliveryBatch } from "@alook/shared"
const fake = vi.hoisted(() => ({ url: "" }))
@@ -18,12 +19,15 @@ let server: Server
function batch(): MessageDeliveryBatch {
return {
+ communityContract: BUSINESS_SCHEMA_VERSION,
messageId: "message-qa-1",
messageEvent: {
type: "community:message.create",
channelId: "channel-qa-1",
serverId: "server-qa-1",
- message: {
+ profiles: [profileResourceFixture({ id: "author", name: "Author", avatarVersion: 0 })],
+ message: messageResourceFixture({
+ channelId: "channel-qa-1",
id: "message-qa-1",
seq: 3,
authorId: "author",
@@ -32,7 +36,7 @@ function batch(): MessageDeliveryBatch {
content: "failed-only retry",
type: "chat",
createdAt: "2026-08-18T00:00:00.000Z",
- },
+ }),
},
contentUserIds: ["author", "healthy", "retry"],
unreadPlainUserIds: ["healthy", "retry"],
diff --git a/src/web/src/test/e2e/ws.test.ts b/src/web/src/test/e2e/ws.test.ts
index 8640f97fe..7b4d287e8 100644
--- a/src/web/src/test/e2e/ws.test.ts
+++ b/src/web/src/test/e2e/ws.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest"
import { randomUUID } from "crypto"
-import { DEV_WS_DO_URL } from "@alook/shared"
+import { COMMUNITY_CONTRACT_VERSION, DEV_WS_DO_URL } from "@alook/shared"
import { signUp, signIn, sessionRequest, sqlRun } from "@alook/test-utils"
const WS_DO_WS = DEV_WS_DO_URL.replace(/^http/, "ws")
@@ -97,7 +97,7 @@ describe("ws (dev direct to ws-do)", () => {
if (!available) return
const ws = await openWs(userId)
- ws.send(JSON.stringify({ type: "auth", token }))
+ ws.send(JSON.stringify({ type: "auth", token, communityContract: COMMUNITY_CONTRACT_VERSION }))
const ack = await waitForMessage<{ type: string }>(ws, (m) => m.type === "auth.ok")
expect(ack.type).toBe("auth.ok")
@@ -121,7 +121,7 @@ describe("ws (dev direct to ws-do)", () => {
if (!available) return
const ws = await openWs(userId)
- ws.send(JSON.stringify({ type: "auth", token }))
+ ws.send(JSON.stringify({ type: "auth", token, communityContract: COMMUNITY_CONTRACT_VERSION }))
await waitForMessage<{ type: string }>(ws, (message) => message.type === "auth.ok")
const nonce = randomUUID()
@@ -139,7 +139,7 @@ describe("ws (dev direct to ws-do)", () => {
if (!available) return
const ws = await openWs(userId)
- ws.send(JSON.stringify({ type: "auth", token: "not-a-real-token" }))
+ ws.send(JSON.stringify({ type: "auth", token: "not-a-real-token", communityContract: COMMUNITY_CONTRACT_VERSION }))
const closeEvent = await waitForClose(ws)
expect(closeEvent.code).toBe(1008)
diff --git a/src/web/src/test/message-scroll-fixture.ts b/src/web/src/test/message-scroll-fixture.ts
index 56a1a27a4..eab8876fd 100644
--- a/src/web/src/test/message-scroll-fixture.ts
+++ b/src/web/src/test/message-scroll-fixture.ts
@@ -14,6 +14,8 @@ let height: number
let width: number
let firstPrefix: number
let bodyHeights: Map<string, number>
+let overflowHeights: Map<string, number>
+let overflowModes: Map<string, "visible" | "hidden">
let frames: Map<number, FrameRequestCallback>
let frameId: number
let resizeObservers: Array<{
@@ -93,7 +95,7 @@ function Probe({ input, onLayout }: { input: Input; onLayout?: (result: Result)
"data-message-divider-for": item.kind === "divider" ? item.messageId : undefined,
},
item.kind === "divider" && item.newDivider ? createElement("div", { "data-new-divider": "" }) : null,
- item.kind === "message" ? createElement("div", { "data-msg-id": item.m.id }) : null,
+ item.kind === "message" ? createElement("div", { "data-msg-id": item.m.id, style: { overflowY: overflowModes.get(item.m.id) } }) : null,
),
}),
),
@@ -175,6 +177,8 @@ export function installMessageScrollFixture() {
width = 320
firstPrefix = 88
bodyHeights = new Map()
+ overflowHeights = new Map()
+ overflowModes = new Map()
frames = new Map()
frameId = 0
resizeObservers = []
@@ -207,7 +211,8 @@ export function installMessageScrollFixture() {
return isScrollRoot(this)
? Math.max(this.clientHeight, Number.parseFloat(this.querySelector<HTMLElement>('[data-message-list-content]')?.style.height
|| this.querySelector<HTMLElement>('[data-message-list-content] > div')?.style.height || "0") || 0)
- : rowGeometry(this).height
+ : Math.max(rowGeometry(this).height, this.matches('[data-index], [data-msg-id]')
+ ? overflowHeights.get(this.dataset.msgId ?? this.querySelector<HTMLElement>('[data-msg-id]')?.dataset.msgId ?? "") ?? 0 : 0)
})
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
return isScrollRoot(this) ? DOMRect.fromRect({ width, height }) : rowGeometry(this)
@@ -239,6 +244,8 @@ export const scrollFixture = {
get firstPrefix() { return firstPrefix },
set firstPrefix(value: number) { firstPrefix = value },
get bodyHeights() { return bodyHeights },
+ get overflowHeights() { return overflowHeights },
+ get overflowModes() { return overflowModes },
get frames() { return frames },
get scrollCalls() { return scrollCalls },
}
diff --git a/src/web/test-runtime/worker.runtime.test.ts b/src/web/test-runtime/worker.runtime.test.ts
index 2c3d799d5..c1a846b4b 100644
--- a/src/web/test-runtime/worker.runtime.test.ts
+++ b/src/web/test-runtime/worker.runtime.test.ts
@@ -3,6 +3,10 @@
import { runInDurableObject } from "cloudflare:test"
import { env, exports } from "cloudflare:workers"
import { describe, expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, CommunityForumSidebarEnvelopeSchema, CommunityForumSidebarChannelSummarySchema, ClaimedTaskRowSchema, createDb, queries, schema } from "@alook/shared"
+import { bindCacheKV, businessCacheKey, cacheKeys } from "@/lib/cache"
+import { TaskPayloadBuilder } from "@/lib/services/task-payload-builder"
+import { hydrateAttentionResources, readCommunityResourceBundle } from "@/lib/community/attention-resources.server"
const runtimeEnv = env as unknown as CloudflareEnv
const worker = (exports as unknown as {
@@ -10,6 +14,136 @@ const worker = (exports as unknown as {
}).default
describe("Web workerd runtime", () => {
+ it("hydrates an actual unread DM projection into full current scoped resources", async () => {
+ const db = createDb(runtimeEnv.DB)
+ const sender = await queries.user.createUser(db, { name: "AttentionSender", email: `${crypto.randomUUID()}@runtime.test` })
+ const viewer = await queries.user.createUser(db, { name: "AttentionViewer", email: `${crypto.randomUUID()}@runtime.test` })
+ const dm = await queries.communityDm.createOrGetDM(db, { userId1: sender.id, userId2: viewer.id })
+ const message = await queries.communityMessage.createMessage(db, { channelId: dm.id, authorId: sender.id, authorKind: "human", content: "Current unread resource", clientNonce: "private-sender-nonce" })
+ const projection = await queries.communityAttention.getAccountAttentionProjection(db, viewer.id)
+ const snapshot = await hydrateAttentionResources(db, viewer.id, projection)
+ expect(snapshot.scopes.some(row => row.channelId === dm.id && row.ordinaryUnread)).toBe(true)
+ expect(snapshot.resources.viewerId).toBe(viewer.id)
+ expect(snapshot.resources.channels.find(row => row.id === dm.id)).toMatchObject({ type: "dm", serverId: null, categoryId: null, topic: "", messageCount: 1 })
+ const actual = await readCommunityResourceBundle(db, viewer.id, { channelIds: [dm.id], messageIds: [message.id] })
+ expect(actual.messages).toHaveLength(1)
+ expect(actual.messages[0]).toMatchObject({ channelId: dm.id, id: message.id, replyToId: null, clientNonce: null, attachments: [] })
+ const authorRead = await readCommunityResourceBundle(db, sender.id, { channelIds: [dm.id], messageIds: [message.id] })
+ expect(authorRead.messages[0]).toMatchObject({ id: message.id, authorId: sender.id, clientNonce: "private-sender-nonce" })
+ expect(actual.profiles.find(row => row.id === sender.id)).toMatchObject({ name: "AttentionSender", avatar: null, avatarVersion: 0 })
+ expect(actual.memberships).toEqual([{ channelId: dm.id, userId: viewer.id, relation: "access", source: "added" }])
+ expect(Object.keys(actual.messages[0])).not.toContain("resourceComplete")
+ })
+
+ it("rejects unauthorized resource scope before a faulted message D1 table is opened", async () => {
+ const db = createDb(runtimeEnv.DB)
+ const [sender, peer, stranger] = await Promise.all(["Sender", "Peer", "Stranger"].map(name => queries.user.createUser(db, { name, email: `${crypto.randomUUID()}@runtime.test` })))
+ const dm = await queries.communityDm.createOrGetDM(db, { userId1: sender.id, userId2: peer.id })
+ await runtimeEnv.DB.prepare("ALTER TABLE community_message RENAME TO community_message_resource_unavailable").run()
+ try {
+ await expect(readCommunityResourceBundle(db, stranger.id, { channelIds: [dm.id], messageIds: ["missing"] })).rejects.toThrow("Attention access changed")
+ const failure = await readCommunityResourceBundle(db, peer.id, { channelIds: [dm.id], messageIds: ["missing"] }).then(
+ () => { throw new Error("Expected message-table failure") },
+ error => error as unknown,
+ )
+ const causes: string[] = []
+ const seen = new Set<unknown>()
+ for (let cause: unknown = failure; cause && typeof cause === "object" && !seen.has(cause);) {
+ seen.add(cause)
+ if ("message" in cause && typeof cause.message === "string") causes.push(cause.message)
+ cause = "cause" in cause ? cause.cause : undefined
+ }
+ expect(causes.join("\n")).toContain("no such table: community_message")
+ } finally {
+ await runtimeEnv.DB.prepare("ALTER TABLE community_message_resource_unavailable RENAME TO community_message").run()
+ }
+ await expect(readCommunityResourceBundle(db, peer.id, { channelIds: [dm.id], messageIds: ["missing"] })).rejects.toThrow("Requested message resource missing from scope")
+ })
+
+ it("closes actual Forum sidebar references over full D1 resources and notify membership", async () => {
+ const db = createDb(runtimeEnv.DB)
+ const viewer = await queries.user.createUser(db, { name: "ForumViewer", email: `${crypto.randomUUID()}@runtime.test` })
+ const { server, ownerMember } = await queries.communityServer.createServer(db, { name: "Current Forum", ownerId: viewer.id })
+ const forum = await queries.communityChannel.createChannel(db, { serverId: server.id, name: "Forum", type: "forum", creatorId: viewer.id })
+ const threadId = crypto.randomUUID()
+ const opener = await queries.communityMessage.createMessage(db, { channelId: forum.id, authorId: viewer.id, authorKind: "human", content: "Full opener",
+ forumThread: { id: threadId, serverId: server.id, name: "Current post" } })
+ const now = Date.now()
+ const projection = await queries.communityThread.listParticipatingForumThreads(db, { parentChannelIds: [forum.id], userId: viewer.id, activeAfter: new Date(now - 72 * 60 * 60 * 1000).toISOString(), limitPerParent: 5 })
+ expect(projection.canonical.map(row => row.id)).toEqual([threadId])
+ const resources = await readCommunityResourceBundle(db, viewer.id, { channelIds: [forum.id, threadId], messageIds: [opener.id], serverIds: [server.id] })
+ const canonicalChannels = projection.canonical.map(row => CommunityForumSidebarChannelSummarySchema.strip().parse({ ...row, unread: false, expiresAt: new Date(Date.parse(row.activityAt) + 72 * 60 * 60 * 1000).toISOString() }))
+ const value = { schemaVersion: BUSINESS_SCHEMA_VERSION, serverId: server.id, channels: canonicalChannels, canonicalChannels,
+ retainedChannel: null, retainedDisposition: null, resources, serverNow: new Date(now).toISOString() }
+ expect(CommunityForumSidebarEnvelopeSchema.parse(value)).toEqual(value)
+ expect(resources.serverMemberships).toEqual([{ serverId: server.id, userId: viewer.id, memberId: ownerMember.id, role: "owner" }])
+ expect(resources.memberships).toContainEqual({ channelId: threadId, userId: viewer.id, relation: "notify", source: "spoke" })
+ expect(resources.messages[0]).toMatchObject({ id: opener.id, channelId: forum.id, attachments: [], replyToId: null })
+ for (const broken of [
+ { ...value, schemaVersion: BUSINESS_SCHEMA_VERSION - 1 },
+ { ...value, resources: { ...resources, messages: [] } },
+ { ...value, resources: { ...resources, memberships: resources.memberships.filter(row => row.relation !== "notify") } },
+ ]) expect(CommunityForumSidebarEnvelopeSchema.safeParse(broken).success).toBe(false)
+ })
+
+ it.each(["hit", "wrong-version", "bad-json", "missing-field", "wrong-scope", "wrong-value-identity", "unversioned"])(
+ "uses actual TaskPayloadBuilder D1/KV inputs for a %s cache value",
+ async mode => {
+ const db = createDb(runtimeEnv.DB)
+ bindCacheKV(runtimeEnv.CACHE_KV)
+ const owner = await queries.user.createUser(db, { name: "D1 Owner", email: `${crypto.randomUUID()}@runtime.test` })
+ const [workspace] = await db.insert(schema.workspace).values({ name: "Runtime workspace", slug: crypto.randomUUID() }).returning()
+ const [runtime] = await db.insert(schema.agentRuntime).values({ workspaceId: workspace.id, daemonId: crypto.randomUUID(), provider: "codex" }).returning()
+ await queries.member.createMember(db, { workspaceId: workspace.id, userId: owner.id, role: "owner" })
+ await queries.member.updateMemberGlobalInstruction(db, owner.id, workspace.id, "D1 instructions")
+ const agent = await queries.agent.createAgent(db, { workspaceId: workspace.id, name: "Runtime agent", ownerId: owner.id, runtimeId: runtime.id })
+ const conversation = await queries.conversation.createConversation(db, { workspaceId: workspace.id, agentId: agent.id, userId: owner.id, title: "Runtime conversation" })
+ const row = await queries.task.createTask(db, { workspaceId: workspace.id, agentId: agent.id, runtimeId: runtime.id, conversationId: conversation.id, prompt: "Runtime cache check" })
+ await queries.emailAccount.createEmailAccount(db, {
+ workspaceId: workspace.id, agentId: agent.id, emailAddress: "[email protected]",
+ imapHost: "imap.runtime.test", imapUsername: "fixture", imapPassword: "fixture-unused",
+ smtpHost: "smtp.runtime.test", smtpUsername: "fixture", smtpPassword: "fixture-unused",
+ })
+ const values = [
+ [cacheKeys.allEmailAccounts(workspace.id), [{ workspaceId: workspace.id, agentId: agent.id, emailAddress: "[email protected]" }]],
+ [cacheKeys.member(workspace.id, owner.id), { workspaceId: workspace.id, userId: owner.id, globalInstruction: "Cached instructions" }],
+ [cacheKeys.user(owner.id), { id: owner.id, name: "Cached Owner", email: owner.email }],
+ ] as const
+ for (const [key, value] of values) {
+ let cacheKey: string = key
+ let payload: unknown = value
+ if (mode === "missing-field") payload = Array.isArray(value) ? [{}] : {}
+ if (mode === "wrong-scope") cacheKey = `other:${key}`
+ if (mode === "wrong-value-identity") {
+ if (Array.isArray(value)) payload = value.map(row => ({ ...row, workspaceId: "other-workspace" }))
+ else if ("userId" in value) payload = { ...value, userId: "other-user", workspaceId: "other-workspace" }
+ else payload = { ...value, id: "other-user" }
+ }
+ const body = mode === "unversioned" ? payload : {
+ schemaVersion: mode === "wrong-version" ? BUSINESS_SCHEMA_VERSION - 1 : BUSINESS_SCHEMA_VERSION,
+ cacheKey, value: payload,
+ }
+ await runtimeEnv.CACHE_KV.put(businessCacheKey(key), mode === "bad-json" ? "not-json" : JSON.stringify(body))
+ }
+ try {
+ const [payload] = await new TaskPayloadBuilder(db).buildFullPayloads([ClaimedTaskRowSchema.parse(row)], workspace.id)
+ expect(payload.agent?.user_name).toBe(mode === "hit" ? "Cached Owner" : "D1 Owner")
+ expect(payload.agent?.instructions).toBe(mode === "hit" ? "Cached instructions" : "D1 instructions")
+ expect(payload.agent?.email_addresses).toEqual([mode === "hit" ? "[email protected]" : "[email protected]"])
+ expect(payload.sender?.name).toBe(mode === "hit" ? "Cached Owner" : "D1 Owner")
+ for (const [key] of values) {
+ const saved = JSON.parse((await runtimeEnv.CACHE_KV.get(businessCacheKey(key)))!)
+ expect(saved).toMatchObject({ schemaVersion: BUSINESS_SCHEMA_VERSION, cacheKey: key })
+ expect(Object.keys(saved).sort()).toEqual(["cacheKey", "schemaVersion", "value"])
+ expect(JSON.stringify(saved.value)).not.toContain("fixture-unused")
+ }
+ } finally {
+ await Promise.all(values.map(([key]) => runtimeEnv.CACHE_KV.delete(businessCacheKey(key))))
+ bindCacheKV(null)
+ }
+ },
+ )
+
it("loads production migrations and local storage bindings", async () => {
const schema = await runtimeEnv.DB.prepare(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index cb0b1bc1b..6ecc5c963 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -103,7 +103,6 @@ binding = "CACHE_KV"
id = "3aaa92b4c2c74185b888977e5552e9bf"
[vars]
-COMMUNITY_EVENT_CONTRACT = "1"
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.1.47"
BLOG_DISCOVERY_REQUIRED = "true"
diff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.ts
index ede330568..d90b0ae41 100644
--- a/src/ws-do/src/community-browser-event-ingress.test.ts
+++ b/src/ws-do/src/community-browser-event-ingress.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest"
import {
+ BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER,
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
COMMUNITY_BULK_BODY_MAX_BYTES,
deriveCommunityDeliveryOperationId,
@@ -37,7 +38,7 @@ function corruptRequiredField(event: CommunityWsEvent, path: readonly string[])
}
function requestFromBytes(bytes: BodyInit, headers?: HeadersInit) {
- return new Request("http://internal/community", { method: "POST", headers, body: bytes })
+ return new Request("http://internal/community", { method: "POST", headers: headers ?? { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, body: bytes })
}
function maximizePadding<T extends CommunityWsEvent>(build: (padding: string) => T) {
@@ -69,15 +70,17 @@ function worstEscapingTarget(index: number) {
}
describe("community browser event ingress", () => {
- it("normalizes all 48 current fixtures without a contract version field", () => {
+ it("normalizes all 46 current versioned wire fixtures", () => {
const fixtures = Object.values(communityWsEventFixtures)
- expect(fixtures).toHaveLength(48)
+ expect(fixtures).toHaveLength(46)
for (const fixture of fixtures) {
- const normalized = normalizeCommunityBrowserEvent(fixture)
- expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: fixture })
+ const encoded = encodeCommunityBrowserEvent(fixture)
+ if (!encoded.ok) throw new Error("invalid current fixture")
+ const normalized = normalizeCommunityBrowserEvent(encoded.envelope)
+ expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: { ...fixture, schemaVersion: BUSINESS_SCHEMA_VERSION } })
if (!normalized.ok) continue
expect(normalized.envelope).not.toHaveProperty("contractVersion")
- expect(JSON.parse(normalized.body)).toEqual(fixture)
+ expect(JSON.parse(normalized.body)).toEqual({ ...fixture, schemaVersion: BUSINESS_SCHEMA_VERSION })
}
})
@@ -88,8 +91,8 @@ describe("community browser event ingress", () => {
path.length ? corruptRequiredField(fixture, path) : { ...fixture, entries: [] },
)).toMatchObject({ ok: false, reason: "invalid-payload" })
}
- expect(normalizeCommunityBrowserEvent({ type: "task.updated" })).toMatchObject({ reason: "wrong-family" })
- expect(normalizeCommunityBrowserEvent({ type: "community:future" })).toMatchObject({ reason: "unknown-community-type" })
+ expect(normalizeCommunityBrowserEvent({ type: "task.updated", schemaVersion: BUSINESS_SCHEMA_VERSION })).toMatchObject({ reason: "wrong-family" })
+ expect(normalizeCommunityBrowserEvent({ type: "community:future", schemaVersion: BUSINESS_SCHEMA_VERSION })).toMatchObject({ reason: "unknown-community-type" })
expect(normalizeCommunityBrowserEvent({
...communityWsEventFixtures["community:presence.update"],
contractVersion: 1,
@@ -130,9 +133,9 @@ describe("community browser event ingress", () => {
content: "m".repeat(4000),
attachments: Array.from({ length: 10 }, (_, index) => ({
id: `attachment-${index}`,
- filename: `file-${index}.txt`,
+ name: `file-${index}.txt`, thumbnailUrl: null, contentType: null, width: null, height: null,
url: `/attachment/${index}`,
- size: 25 * 1024 * 1024,
+ sizeBytes: 25 * 1024 * 1024,
})),
embeds: [{ padding }],
},
@@ -160,6 +163,7 @@ describe("community browser event ingress", () => {
if (!prepared.ok) throw new Error("bundle fixture must prepare")
const operationId = await deriveCommunityDeliveryOperationId("message-1")
const body = {
+ communityContract: BUSINESS_SCHEMA_VERSION,
operationId,
operationDigest: prepared.prepared.digest,
events: prepared.prepared.envelopes,
@@ -204,7 +208,7 @@ describe("community browser event ingress", () => {
const targets = Array.from({ length: 1000 }, (_, index) => worstEscapingTarget(index))
const body = JSON.stringify({
userIds: targets,
- message: event.event,
+ message: event.envelope,
excludeUserId: worstEscapingTarget(1000),
})
expect(utf8ByteLength(body)).toBe(COMMUNITY_BULK_BODY_MAX_BYTES)
diff --git a/src/ws-do/src/community-browser-event-ingress.ts b/src/ws-do/src/community-browser-event-ingress.ts
index dcc896b7e..903de9754 100644
--- a/src/ws-do/src/community-browser-event-ingress.ts
+++ b/src/ws-do/src/community-browser-event-ingress.ts
@@ -2,6 +2,8 @@ import { readBoundedJsonRequest as readBoundedHttpJsonRequest } from "@alook/sha
import {
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
COMMUNITY_CONTRACT_HEADER,
+ BUSINESS_SCHEMA_VERSION,
+ type CommunityBrowserEventEnvelope,
type CommunityContract,
MESSAGE_DELIVERY_BODY_MAX_BYTES,
MESSAGE_DELIVERY_MAX_EVENTS_PER_USER,
@@ -29,7 +31,7 @@ export type CommunityBrowserEventIngressFailure = {
type CommunityBrowserEventIngressSuccess = {
ok: true
event: CommunityWsEvent
- envelope: CommunityWsEvent
+ envelope: CommunityBrowserEventEnvelope
body: string
byteCount: number
contract: CommunityContract
@@ -51,7 +53,7 @@ export async function readBoundedJsonRequest(request: Request, maxBytes: number)
export function normalizeCommunityBrowserEvent(
value: unknown,
byteCount?: number,
- contract: CommunityContract = 2,
+ contract: CommunityContract = BUSINESS_SCHEMA_VERSION,
): CommunityBrowserEventIngressResult {
const decoded = decodeCommunityBrowserEvent(value, contract)
if (!decoded.ok) return { ...decoded, ok: false, ...(byteCount === undefined ? {} : { byteCount }) }
@@ -67,7 +69,7 @@ export function normalizeCommunityBrowserEvent(
return {
ok: true,
event: decoded.event,
- envelope: encoded.event,
+ envelope: encoded.envelope,
body: encoded.body,
byteCount: encoded.byteLength,
contract,
@@ -79,9 +81,8 @@ export async function readCommunityBrowserEventRequest(
): Promise<CommunityBrowserEventIngressResult> {
const parsed = await readBoundedJsonRequest(request, COMMUNITY_BROWSER_EVENT_MAX_BYTES)
if (!parsed.ok) return parsed
- const version = request.headers.get(COMMUNITY_CONTRACT_HEADER)
- if (version !== null && version !== "1" && version !== "2" && version !== "3") return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
- return normalizeCommunityBrowserEvent(parsed.value, parsed.byteCount, version === "3" ? 3 : version === "1" ? 1 : 2)
+ if (request.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
+ return normalizeCommunityBrowserEvent(parsed.value, parsed.byteCount, BUSINESS_SCHEMA_VERSION)
}
export async function readCommunityBrowserEventBundleRequest(
@@ -98,11 +99,12 @@ export async function readCommunityBrowserEventBundleRequest(
> {
const parsed = await readBoundedJsonRequest(request, MESSAGE_DELIVERY_BODY_MAX_BYTES)
if (!parsed.ok) return parsed
+ if (request.headers.get(COMMUNITY_CONTRACT_HEADER) !== String(BUSINESS_SCHEMA_VERSION)) return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
if (
typeof parsed.value !== "object"
|| parsed.value === null
|| Array.isArray(parsed.value)
- || Object.keys(parsed.value).length !== ("communityContract" in parsed.value && parsed.value.communityContract === 3 ? 4 : 3)
+ || Object.keys(parsed.value).length !== 4
|| !Object.prototype.hasOwnProperty.call(parsed.value, "operationId")
|| !Object.prototype.hasOwnProperty.call(parsed.value, "operationDigest")
|| !Object.prototype.hasOwnProperty.call(parsed.value, "events")
@@ -116,7 +118,7 @@ export async function readCommunityBrowserEventBundleRequest(
events?: unknown
}
if (
- (Object.hasOwn(input, "communityContract") && input.communityContract !== 3)
+ input.communityContract !== BUSINESS_SCHEMA_VERSION
|| !isCommunityDeliveryOperationId(input.operationId)
|| !isCommunityDeliveryDigest(input.operationDigest)
) {
@@ -130,7 +132,9 @@ export async function readCommunityBrowserEventBundleRequest(
) {
return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
}
- const prepared = await prepareCommunityDeliveryEvents(events, input.communityContract === 3 ? 3 : 2)
+ const decoded = events.map(event => decodeCommunityBrowserEvent(event))
+ if (decoded.some(event => !event.ok)) return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
+ const prepared = await prepareCommunityDeliveryEvents(decoded.flatMap(result => result.ok ? [result.event] : []), BUSINESS_SCHEMA_VERSION)
if (!prepared.ok || prepared.prepared.digest !== input.operationDigest) {
return { ok: false, reason: "invalid-payload", type: "unknown", byteCount: parsed.byteCount }
}
diff --git a/src/ws-do/src/community-content-access.test.ts b/src/ws-do/src/community-content-access.test.ts
index 0acb08c4d..de3354519 100644
--- a/src/ws-do/src/community-content-access.test.ts
+++ b/src/ws-do/src/community-content-access.test.ts
@@ -34,7 +34,7 @@ describe("community target content access", () => {
it("never lets a control child bypass mixed content access", async () => {
readable.mockResolvedValue([])
expect(await canDeliverCommunityContent({} as never, "user-1", [
- communityWsEventFixtures["community:channel.member_add"],
+ communityWsEventFixtures["community:channel.membership.change"],
communityWsEventFixtures["community:message.create"],
])).toBe(false)
})
@@ -52,7 +52,7 @@ describe("community target content access", () => {
expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(false)
expect(await canDeliverCommunityContent({} as never, "user-1", [{ type: "community:unread.bump", userId: "other", channelId: "child" }])).toBe(false)
})
- it("resolves legacy attention scope and propagates transient lookup failure", async () => {
+ it("resolves the named message-only attention scope and propagates transient lookup failure", async () => {
const event = { type: "community:mention.create" as const, userId: "user-1", messageId: "message-1", authorName: "Author" }
expect(await canDeliverCommunityContent({} as never, "user-1", [event])).toBe(true)
expect(messageScope).toHaveBeenCalledWith({}, "user-1", "message-1")
diff --git a/src/ws-do/src/community-content-access.ts b/src/ws-do/src/community-content-access.ts
index f863bad8a..ad737ea79 100644
--- a/src/ws-do/src/community-content-access.ts
+++ b/src/ws-do/src/community-content-access.ts
@@ -18,10 +18,8 @@ export const communityContentAccessKinds = {
"community:unread.bump": "notification",
"community:mention.create": "mention",
"community:channel.delete": "control",
- "community:channel.member_remove": "control",
"community:member.leave": "control",
"community:server.delete": "control",
- "community:channel.member_add": "control",
"community:channel.membership.change": "control",
"community:member.join": "control",
"community:server.update": "control",
diff --git a/src/ws-do/src/internal-user-broadcast.test.ts b/src/ws-do/src/internal-user-broadcast.test.ts
index c1af3d59e..749efd70f 100644
--- a/src/ws-do/src/internal-user-broadcast.test.ts
+++ b/src/ws-do/src/internal-user-broadcast.test.ts
@@ -1,16 +1,23 @@
import { describe, expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER, deriveCommunityDeliveryOperationId, prepareCommunityDeliveryEvents } from "@alook/shared"
import { createInternalCommunityUserBundleRequest, getInternalCommunityUserTarget } from "./internal-user-broadcast"
+import { readCommunityBrowserEventBundleRequest } from "./community-browser-event-ingress"
-describe("internal community bundle request", () => {
- it("defaults to the legacy contract while keeping the target and operation intact", async () => {
+describe("internal current community bundle request", () => {
+ it("keeps the target and current operation bytes intact and refuses an old consumer contract", async () => {
const events = [{ type: "community:presence.update", userId: "peer", online: true }]
- const request = createInternalCommunityUserBundleRequest("viewer/你好", "operation", "digest", events)
+ const prepared = await prepareCommunityDeliveryEvents(events)
+ if (!prepared.ok) throw new Error("invalid fixture")
+ const id = await deriveCommunityDeliveryOperationId("message")
+ const request = createInternalCommunityUserBundleRequest("viewer/你好", id, prepared.prepared.digest, prepared.prepared.envelopes)
expect(request.url).toBe("http://internal/community-broadcast-bundle")
expect(request.method).toBe("POST")
expect(request.headers.get("content-type")).toBe("application/json")
+ expect(request.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
expect(getInternalCommunityUserTarget(request)).toBe("viewer/你好")
- expect(await request.json()).toEqual({ operationId: "operation", operationDigest: "digest", events })
- expect(await createInternalCommunityUserBundleRequest("viewer", "operation", "digest", events, 3).json())
- .toEqual({ operationId: "operation", operationDigest: "digest", events, communityContract: 3 })
+ expect(await request.clone().json()).toEqual({ operationId: id, operationDigest: prepared.prepared.digest, events: prepared.prepared.envelopes, communityContract: BUSINESS_SCHEMA_VERSION })
+ expect(await readCommunityBrowserEventBundleRequest(request)).toMatchObject({ ok: true })
+ const old = createInternalCommunityUserBundleRequest("viewer", id, prepared.prepared.digest, prepared.prepared.envelopes, 3 as never)
+ expect(await readCommunityBrowserEventBundleRequest(old)).toMatchObject({ ok: false })
})
})
diff --git a/src/ws-do/src/internal-user-broadcast.ts b/src/ws-do/src/internal-user-broadcast.ts
index 8ae01b07a..97c397d94 100644
--- a/src/ws-do/src/internal-user-broadcast.ts
+++ b/src/ws-do/src/internal-user-broadcast.ts
@@ -1,4 +1,5 @@
import {
+ BUSINESS_SCHEMA_VERSION,
encodeCommunityBrowserEvent,
COMMUNITY_CONTRACT_HEADER,
type CommunityContract,
@@ -31,13 +32,13 @@ export function createInternalUserBroadcastRequest(
export function createInternalCommunityUserBroadcastRequest(
targetUserId: string,
body: BodyInit | null,
- contract: CommunityContract = 2,
+ contract: CommunityContract = BUSINESS_SCHEMA_VERSION,
): Request {
const headers = new Headers({
"content-type": "application/json",
[INTERNAL_USER_TARGET_HEADER]: encodeURIComponent(targetUserId),
})
- if (contract === 3) headers.set(COMMUNITY_CONTRACT_HEADER, "3")
+ headers.set(COMMUNITY_CONTRACT_HEADER, String(contract))
return new Request("http://internal/community-broadcast", {
method: "POST",
headers,
@@ -50,16 +51,17 @@ export function createInternalCommunityUserBundleRequest(
operationId: string,
operationDigest: string,
events: readonly unknown[],
- contract: CommunityContract = 2,
+ contract: CommunityContract = BUSINESS_SCHEMA_VERSION,
): Request {
const headers = new Headers({
"content-type": "application/json",
[INTERNAL_USER_TARGET_HEADER]: encodeURIComponent(targetUserId),
})
+ headers.set(COMMUNITY_CONTRACT_HEADER, String(contract))
return new Request("http://internal/community-broadcast-bundle", {
method: "POST",
headers,
- body: JSON.stringify({ operationId, operationDigest, events, ...(contract === 3 ? { communityContract: 3 } : {}) }),
+ body: JSON.stringify({ operationId, operationDigest, events, communityContract: contract }),
})
}
diff --git a/src/ws-do/src/routes/broadcast.test.ts b/src/ws-do/src/routes/broadcast.test.ts
index ea2d74fe9..9405fb75e 100644
--- a/src/ws-do/src/routes/broadcast.test.ts
+++ b/src/ws-do/src/routes/broadcast.test.ts
@@ -8,6 +8,7 @@ import {
} from "./test-harness"
import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"
import {
+ BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER,
COMMUNITY_BROWSER_EVENT_MAX_BYTES,
COMMUNITY_BULK_BODY_MAX_BYTES,
encodeCommunityBrowserEvent,
@@ -36,6 +37,7 @@ function makeBulkRequest(body: string): Request {
}
const communityPresenceEvent = {
+ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:presence.update",
userId: "presence-user",
online: true,
@@ -52,7 +54,7 @@ function maximumAuditEnvelope() {
payload: { padding: "x".repeat(mid) },
})
if (encoded.ok) {
- best = encoded.event
+ best = encoded.envelope
low = mid + 1
} else {
high = mid - 1
@@ -169,7 +171,7 @@ describe("ws-do router", () => {
doMock.stubFetch.mockImplementation(async () => Response.json({ sent: 1 }))
const req = new Request(
`http://localhost/broadcast/community/user/${encodeCommunityUserTargetPathSegment(target)}`,
- { method: "POST", body: JSON.stringify(communityPresenceEvent) },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: JSON.stringify(communityPresenceEvent) },
)
const res = await handler.fetch(req, env as any)
@@ -190,7 +192,7 @@ describe("ws-do router", () => {
])("rejects a %s before Durable Object access", async (_label, event) => {
const res = await handler.fetch(new Request(
"http://localhost/broadcast/community/user/u:user-1",
- { method: "POST", body: JSON.stringify(event) },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: JSON.stringify(event) },
), env as any)
expect(res.status).toBe(400)
@@ -201,7 +203,7 @@ describe("ws-do router", () => {
doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1 }))
const res = await handler.fetch(new Request(
"http://localhost/broadcast/community/user/u:user-1",
- { method: "POST", body: JSON.stringify(communityPresenceEvent) },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: JSON.stringify(communityPresenceEvent) },
), env as any)
expect(res.status).toBe(200)
@@ -212,14 +214,14 @@ describe("ws-do router", () => {
it("rejects malformed target escapes and generic bodies on the strict route", async () => {
const malformedTarget = await handler.fetch(new Request(
"http://localhost/broadcast/community/user/u:%zz",
- { method: "POST", body: JSON.stringify(communityPresenceEvent) },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: JSON.stringify(communityPresenceEvent) },
), env as any)
const spoofedGeneric = await handler.fetch(new Request(
"http://localhost/broadcast/community/user/u:user-1",
{
method: "POST",
- headers: { "x-alook-ws-message-type": "generic" },
- body: JSON.stringify({ type: "task.updated", taskId: "t1" }),
+ headers: { "x-alook-ws-message-type": "generic", [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
+ body: JSON.stringify({ type: "task.updated", taskId: "t1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
},
), env as any)
@@ -239,7 +241,7 @@ describe("ws-do router", () => {
it("rejects an oversized strict community frame before Durable Object access", async () => {
const res = await handler.fetch(new Request(
"http://localhost/broadcast/community/user/u:user-1",
- { method: "POST", body: "x".repeat(65_537) },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: "x".repeat(65_537) },
), env as any)
expect(res.status).toBe(400)
@@ -250,7 +252,7 @@ describe("ws-do router", () => {
doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1 }))
const res = await handler.fetch(new Request(
"http://localhost/broadcast/community/users",
- {
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
method: "POST",
body: JSON.stringify({
userIds: ["u2", "u1", "u2"],
@@ -267,6 +269,26 @@ describe("ws-do router", () => {
await expect(internal.json()).resolves.toEqual(communityPresenceEvent)
})
+ it("rejects a producer's business-only event and forwards only its current envelope", async () => {
+ const event = communityWsEventFixtures["community:channel.delete"]
+ const encoded = encodeCommunityBrowserEvent(event)
+ if (!encoded.ok) throw new Error("Current fixture event did not encode")
+ const request = (message: unknown) => new Request("http://localhost/broadcast/community/users", {
+ method: "POST", headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
+ body: JSON.stringify({ userIds: ["viewer"], message }),
+ })
+ const refused = await handler.fetch(request(encoded.event), env as any)
+ expect(refused.status).toBe(400)
+ expect(doMock.idFromName).not.toHaveBeenCalled()
+ expect(doMock.stubFetch).not.toHaveBeenCalled()
+ doMock.stubFetch.mockResolvedValue(Response.json({ sent: 1 }))
+ const accepted = await handler.fetch(request(encoded.envelope), env as any)
+ expect(accepted.status).toBe(200)
+ expect(doMock.idFromName).toHaveBeenCalledWith("user:viewer")
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(1)
+ await expect((doMock.stubFetch.mock.calls[0][0] as Request).json()).resolves.toEqual(encoded.envelope)
+ })
+
it("accepts the exact worst-case 837,347-byte strict bulk body", async () => {
doMock.stubFetch.mockImplementation(async () => Response.json({ sent: 1 }))
const body = JSON.stringify({
@@ -278,7 +300,7 @@ describe("ws-do router", () => {
const res = await handler.fetch(new Request(
"http://localhost/broadcast/community/users",
- { method: "POST", body },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body },
), env as any)
expect(res.status).toBe(200)
@@ -293,7 +315,7 @@ describe("ws-do router", () => {
])("rejects strict community bulk with %s", async (_label, body) => {
const res = await handler.fetch(new Request(
"http://localhost/broadcast/community/users",
- { method: "POST", body: JSON.stringify(body) },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: JSON.stringify(body) },
), env as any)
expect(res.status).toBe(400)
@@ -308,7 +330,7 @@ describe("ws-do router", () => {
])("rejects %s as invalid-target before namespace access", async (_label, body) => {
const res = await handler.fetch(new Request(
"http://localhost/broadcast/community/users",
- { method: "POST", body: JSON.stringify(body) },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: JSON.stringify(body) },
), env as any)
expect(res.status).toBe(400)
diff --git a/src/ws-do/src/routes/broadcast.ts b/src/ws-do/src/routes/broadcast.ts
index 8252fe68a..c9065fd1c 100644
--- a/src/ws-do/src/routes/broadcast.ts
+++ b/src/ws-do/src/routes/broadcast.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import type { RouterContext } from "../router-context"
import {
COMMUNITY_BULK_BODY_MAX_BYTES,
@@ -295,8 +296,8 @@ export async function handleCommunityUsersBroadcast({ request, env, url, traceId
return invalidCommunityBrowserEventResponse(failure)
}
const version = request.headers.get(COMMUNITY_CONTRACT_HEADER)
- if (version !== null && version !== "1" && version !== "2" && version !== "3") return invalidCommunityBrowserEventResponse(strictFailure("invalid-payload", parsed.byteCount))
- const event = normalizeCommunityBrowserEvent(body.message, undefined, version === "3" ? 3 : version === "1" ? 1 : 2)
+ if (version !== String(BUSINESS_SCHEMA_VERSION)) return invalidCommunityBrowserEventResponse(strictFailure("invalid-payload", parsed.byteCount))
+ const event = normalizeCommunityBrowserEvent(body.message, undefined, BUSINESS_SCHEMA_VERSION)
if (!event.ok) {
logCommunityBrowserEventRejected(log, "strict-bulk", event, body.userIds.length)
return invalidCommunityBrowserEventResponse(event)
diff --git a/src/ws-do/src/routes/message-delivery.test.ts b/src/ws-do/src/routes/message-delivery.test.ts
index cc49012bd..c22d6e932 100644
--- a/src/ws-do/src/routes/message-delivery.test.ts
+++ b/src/ws-do/src/routes/message-delivery.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
+ BUSINESS_SCHEMA_VERSION,
COMMUNITY_DELIVERY_OPERATION_ID_HEADER,
MESSAGE_DELIVERY_MAX_EVENTS_PER_USER,
deriveCommunityDeliveryOperationId,
@@ -16,11 +17,12 @@ import {
const messageEvent = {
type: "community:message.create" as const,
+ profiles: [{ id: "author", name: "Alice", discriminator: "0001", avatar: null, avatarVersion: 0 }],
channelId: "thread-1",
serverId: "server-1",
parentChannelId: "forum-1",
message: {
- id: "message-1",
+ id: "message-1", channelId: "thread-1", replyToId: null, clientNonce: null, attachments: [],
seq: 4,
authorId: "author",
authorName: "Alice",
@@ -32,13 +34,13 @@ const messageEvent = {
}
const batch = {
+ communityContract: BUSINESS_SCHEMA_VERSION,
messageId: "message-1",
messageEvent,
contentUserIds: ["author", "overlap"],
unreadPlainUserIds: [],
unreadMentionUserIds: ["overlap"],
mentionUserIds: ["overlap", "mention-only"],
- memberAdded: { userId: "author", serverId: "server-1", channelId: "thread-1" },
parentProjection: {
type: "community:channel.child_update" as const,
parentChannelId: "forum-1",
@@ -101,12 +103,12 @@ describe("message delivery route", () => {
inputs.set(target, await request.clone().json() as InternalBundleBody)
return successfulReceipt(request)
})
- const input: MessageDeliveryBatch = { ...batch, memberAdded: undefined,
+ const input: MessageDeliveryBatch = { ...batch,
contentUserIds: ["author", "overlap", "joined-reply", "reader"], joinedParticipantUserIds: ["author", "overlap", "joined-reply"], rosterRefreshUserId: "author" }
expect((await handler.fetch(await deliveryRequest(input), env as never)).status).toBe(200)
for (const id of input.contentUserIds) {
const changes = inputs.get(id)!.events.filter((event) => event.type === "community:channel.membership.change")
- expect(changes).toEqual([{ type: "community:channel.membership.change", channelId: "thread-1", serverId: "server-1",
+ expect(changes).toEqual([{ schemaVersion: BUSINESS_SCHEMA_VERSION, type: "community:channel.membership.change", channelId: "thread-1", serverId: "server-1",
userId: id === "reader" ? "author" : id, relation: "notify", present: true }])
expect(inputs.get(id)!.events.length).toBeLessThanOrEqual(MESSAGE_DELIVERY_MAX_EVENTS_PER_USER)
}
@@ -126,7 +128,7 @@ describe("message delivery route", () => {
if (target === "transient" && failTransient) return Response.json({ error: "D1 unavailable" }, { status: 503 })
return successfulReceipt(request)
})
- const mixed = { messageId: batch.messageId, messageEvent, contentUserIds: ["success", "revoked", "transient"], unreadPlainUserIds: ["success", "revoked", "transient"], unreadMentionUserIds: [], mentionUserIds: [] }
+ const mixed = { communityContract: BUSINESS_SCHEMA_VERSION, messageId: batch.messageId, messageEvent, contentUserIds: ["success", "revoked", "transient"], unreadPlainUserIds: ["success", "revoked", "transient"], unreadMentionUserIds: [], mentionUserIds: [] }
const first = await handler.fetch(await deliveryRequest(mixed), env as never)
expect(first.status).toBe(207)
expect(await first.json()).toEqual({ failedUserIds: ["transient"] })
@@ -180,9 +182,7 @@ describe("message delivery route", () => {
railChannelId: "forum-1",
isMention: true,
})
- // Exact legacy strict shape: scope travels on the pre-existing bump so an
- // already-open client running the previous decoder accepts the whole batch.
- expect(byUser.get("mention-only")?.events[1]).toEqual({
+ expect(byUser.get("mention-only")?.events[1]).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:mention.create",
userId: "mention-only",
messageId: "message-1",
@@ -234,7 +234,6 @@ describe("message delivery route", () => {
contentUserIds: [],
unreadMentionUserIds: [],
mentionUserIds: ["mention-only"],
- memberAdded: undefined,
parentProjectionUserIds: ["mention-only"],
}
const first = await handler.fetch(await deliveryRequest(retryBatch), env as never)
@@ -248,20 +247,19 @@ describe("message delivery route", () => {
expect(mentionOnlyBodies[0]?.events).toHaveLength(3)
})
- it("keeps a mention-only DM scoped as a DM in the legacy-compatible batch", async () => {
+ it("keeps a mention-only DM scoped as a DM in the current batch", async () => {
doMock.stubFetch.mockImplementation(successfulReceipt)
const dmBatch = {
...batch,
messageEvent: {
...batch.messageEvent,
- channelId: "dm-1",
+ channelId: "dm-1", message: { ...batch.messageEvent.message, channelId: "dm-1" },
serverId: undefined,
parentChannelId: undefined,
},
contentUserIds: [],
unreadMentionUserIds: [],
mentionUserIds: ["mention-only"],
- memberAdded: undefined,
parentProjection: undefined,
parentProjectionUserIds: undefined,
}
@@ -271,13 +269,13 @@ describe("message delivery route", () => {
const request = doMock.stubFetch.mock.calls[0]?.[0] as Request
const body = await request.clone().json() as InternalBundleBody
expect(body.events).toEqual([
- {
+ { schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:unread.bump",
userId: "mention-only",
channelId: "dm-1",
isMention: true,
},
- {
+ { schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:mention.create",
userId: "mention-only",
messageId: "message-1",
@@ -397,7 +395,6 @@ describe("message delivery route", () => {
unreadPlainUserIds: [],
unreadMentionUserIds: [],
mentionUserIds: [],
- memberAdded: undefined,
parentProjection: undefined,
parentProjectionUserIds: undefined,
}), env as never)
@@ -410,7 +407,7 @@ describe("message delivery route", () => {
it.each([
["invalid JSON", "{"],
["extra key", JSON.stringify({ ...batch, extra: true })],
- ["cross-scope member", JSON.stringify({ ...batch, memberAdded: { ...batch.memberAdded, channelId: "other" } })],
+ ["obsolete memberAdded field", JSON.stringify({ ...batch, memberAdded: { userId: "author", serverId: "server-1", channelId: "thread-1" } })],
])("rejects %s before DO access", async (_label, body) => {
const response = await handler.fetch(new Request(
"http://localhost/broadcast/community/message-delivery",
diff --git a/src/ws-do/src/routes/message-delivery.ts b/src/ws-do/src/routes/message-delivery.ts
index 0e375ba83..859e70d5f 100644
--- a/src/ws-do/src/routes/message-delivery.ts
+++ b/src/ws-do/src/routes/message-delivery.ts
@@ -2,6 +2,7 @@ import {
COMMUNITY_DELIVERY_OPERATION_ID_HEADER,
MESSAGE_DELIVERY_BODY_MAX_BYTES,
WS_EVENTS,
+ type CommunityContract,
deriveCommunityDeliveryOperationId,
isCommunityDeliveryOperationId,
parseMessageDeliveryBatch,
@@ -36,7 +37,7 @@ async function deliverTarget(
userId: string,
events: CommunityWsEvent[],
operationId: CommunityDeliveryOperationId,
- contract: 2 | 3,
+ contract: CommunityContract,
): Promise<TargetResult> {
const prepared = await prepareCommunityDeliveryEvents(events, contract)
if (!prepared.ok) return { ok: false, kind: "invalid-receipt" }
@@ -132,10 +133,6 @@ export async function handleMessageDelivery(
}
const unreadMentionUsers = new Set(batch.unreadMentionUserIds)
for (const userId of batch.mentionUserIds) {
- // Keep mention.create's production strict shape rollout-safe. A user who
- // only receives attention (for example through a visible forum parent)
- // first gets the existing scoped bump so both old and new clients decode
- // the batch and the new projection knows its server/rail scope.
if (!unreadMentionUsers.has(userId)) {
addEvent(bundles, userId, {
type: WS_EVENTS.UNREAD_BUMP,
@@ -156,12 +153,6 @@ export async function handleMessageDelivery(
authorName: batch.messageEvent.message.authorName,
})
}
- if (batch.memberAdded) {
- addEvent(bundles, batch.memberAdded.userId, {
- type: WS_EVENTS.CHANNEL_MEMBER_ADD,
- ...batch.memberAdded,
- })
- }
if (batch.joinedParticipantUserIds && batch.rosterRefreshUserId && batch.messageEvent.serverId) {
const joined = new Set(batch.joinedParticipantUserIds)
for (const userId of batch.contentUserIds) {
@@ -182,7 +173,7 @@ export async function handleMessageDelivery(
const startedAt = Date.now()
const results = await settleInBatches(
entries,
- ([userId, events]) => deliverTarget(env, userId, events, operationId, batch.communityContract ?? 2),
+ ([userId, events]) => deliverTarget(env, userId, events, operationId, batch.communityContract),
targetBatchSize,
)
const failedUserIds: string[] = []
diff --git a/src/ws-do/src/ws-durable/agent-interrupt.test.ts b/src/ws-do/src/ws-durable/agent-interrupt.test.ts
index b626fd13a..0abd2ec7a 100644
--- a/src/ws-do/src/ws-durable/agent-interrupt.test.ts
+++ b/src/ws-do/src/ws-durable/agent-interrupt.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it } from "vitest"
import { createMockWebSocket } from "../__mocks__/cf"
import {
@@ -25,7 +26,7 @@ describe("agent running-turn interrupt WS routing", () => {
function userSocket(userId = "owner_1") {
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId, authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId, authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
return ws
}
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index f405810fc..e2b872220 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createMockWebSocket } from "../__mocks__/cf"
import {
@@ -650,8 +651,8 @@ describe("WebSocketDurableObject", () => {
const parsed = bodies.map((b) => JSON.parse(b)).filter((b) => b.type === "community:status.update")
expect(parsed).toEqual(
expect.arrayContaining([
- { type: "community:status.update", userId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
- { type: "community:status.update", userId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
+ { schemaVersion: BUSINESS_SCHEMA_VERSION, type: "community:status.update", userId: "bot_1", statusEmoji: "💤", statusText: "Idle" },
+ { schemaVersion: BUSINESS_SCHEMA_VERSION, type: "community:status.update", userId: "bot_2", statusEmoji: "💤", statusText: "Idle" },
])
)
})
diff --git a/src/ws-do/src/ws-durable/machine-restart.test.ts b/src/ws-do/src/ws-durable/machine-restart.test.ts
index 4940ee15f..1cd4c75c5 100644
--- a/src/ws-do/src/ws-durable/machine-restart.test.ts
+++ b/src/ws-do/src/ws-durable/machine-restart.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createMockWebSocket } from "../__mocks__/cf"
import {
@@ -171,7 +172,7 @@ describe("WebSocketDurableObject", () => {
const call = auditBroadcast()
expect(call).toBeDefined()
const body = JSON.parse(await (call!).clone().text()) as Record<string, unknown>
- expect(body).toEqual({
+ expect(body).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:bot.audit_event",
botId: "bot_1",
id: "bae_reset",
diff --git a/src/ws-do/src/ws-durable/machine-telemetry.test.ts b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
index 9940aa971..9020702ac 100644
--- a/src/ws-do/src/ws-durable/machine-telemetry.test.ts
+++ b/src/ws-do/src/ws-durable/machine-telemetry.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { calendarDayKeyDaysAgo, dayKeyInTimeZone } from "@alook/shared"
import { createMockWebSocket } from "../__mocks__/cf"
@@ -105,7 +106,7 @@ describe("WebSocketDurableObject", () => {
statusEmoji: string
statusText: string
}
- expect(body).toEqual({
+ expect(body).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:status.update",
userId: "bot_1",
statusEmoji: "⚡",
@@ -738,7 +739,7 @@ describe("WebSocketDurableObject", () => {
}
// Bot path carries name/discriminator from the binding (getBotBindingWithOwner's
// existing join) so the client renders the bot's name without a roster lookup.
- expect(body).toEqual({
+ expect(body).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:typing.start",
userId: "bot_1",
channelId: "dm_1",
@@ -890,7 +891,7 @@ describe("WebSocketDurableObject", () => {
userId: string
channelId: string
}
- expect(body).toEqual({
+ expect(body).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:typing.stop",
userId: "bot_1",
channelId: "dm_1",
@@ -928,7 +929,7 @@ describe("WebSocketDurableObject", () => {
expect(env.WS_DO.idFromName).toHaveBeenCalledExactlyOnceWith("user:owner_1")
const notified = mockStubFetch.mock.calls.map((call: any[]) => call[0] as Request).filter((request) => request.url.endsWith("/community-broadcast"))
expect(notified).toHaveLength(1)
- expect(await notified[0]!.clone().json()).toMatchObject({ type: "community:bot.audit_event", botId: "bot_1", kind: "text", payload })
+ expect(await notified[0]!.clone().json()).toMatchObject({ schemaVersion: BUSINESS_SCHEMA_VERSION, type: "community:bot.audit_event", botId: "bot_1", kind: "text", payload })
})
it("persists a daemon-accepted turn interrupt", async () => {
@@ -1037,7 +1038,7 @@ describe("WebSocketDurableObject", () => {
(c[0] as Request).url.endsWith("/community-broadcast"),
)
expect(call).toBeDefined()
- expect(JSON.parse(await (call![0] as Request).clone().text())).toMatchObject({
+ expect(JSON.parse(await (call![0] as Request).clone().text())).toMatchObject({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:bot.audit_event",
botId: "bot_1",
id: "bae_idle_reset",
@@ -1141,7 +1142,7 @@ describe("WebSocketDurableObject", () => {
payload: unknown
createdAt: string
}
- expect(body).toEqual({
+ expect(body).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:bot.audit_event",
botId: "bot_1",
id: "bae_abc",
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 c5ba129e1..39d81c92b 100644
--- a/src/ws-do/src/ws-durable/presence-typing.test.ts
+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { readFileSync } from "node:fs"
import { createMockWebSocket } from "../__mocks__/cf"
@@ -71,7 +72,7 @@ describe("WebSocketDurableObject", () => {
// Set up two WebSockets: one authenticated, one not
const wsAuth = createMockWebSocket()
- wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ wsAuth.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const wsUnauth = createMockWebSocket()
wsUnauth.serializeAttachment({ type: "user", userId: "", authenticated: false })
; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth, wsUnauth])
@@ -112,9 +113,9 @@ describe("WebSocketDurableObject", () => {
const { durable, ctx } = createDO()
const wsOpen = createMockWebSocket(WebSocket.OPEN)
- wsOpen.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ wsOpen.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const wsClosed = createMockWebSocket(WebSocket.CLOSED)
- wsClosed.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ wsClosed.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
wsClosed.send.mockImplementation(() => { throw new Error("Connection closed") })
; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsOpen, wsClosed])
@@ -134,7 +135,7 @@ describe("WebSocketDurableObject", () => {
it("sweeps an authenticated historical mismatch before sending", async () => {
const { durable, ctx } = createDO()
const attacker = createMockWebSocket()
- attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ attacker.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker])
const res = await durable.fetch(new Request("http://internal/broadcast", {
@@ -167,9 +168,9 @@ describe("WebSocketDurableObject", () => {
it("sends only to the matching user while sweeping mixed historical sockets", async () => {
const { durable, ctx } = createDO()
const victim = createMockWebSocket()
- victim.serializeAttachment({ type: "user", userId: "victim", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ victim.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "victim", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const attacker = createMockWebSocket()
- attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ attacker.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker, victim])
const res = await durable.fetch(new Request("http://internal/broadcast", {
@@ -214,7 +215,7 @@ describe("WebSocketDurableObject", () => {
const daemon = createMockWebSocket()
daemon.serializeAttachment({ type: "daemon", daemonId: "daemon-1", userId: "user-1", authenticated: true })
const user = createMockWebSocket()
- user.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ user.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([user, daemon])
const response = await durable.fetch(new Request("http://internal/check-alive"))
@@ -268,7 +269,7 @@ describe("WebSocketDurableObject", () => {
const { durable, ctx } = createDO()
mockGetUserInternal.mockResolvedValue({ isBot: false } as any)
const wsAuth = createMockWebSocket()
- wsAuth.serializeAttachment({ type: "user", userId: "human-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ wsAuth.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "human-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])
const res = await durable.fetch(new Request("http://internal/check-user-online?userId=human-1"))
@@ -280,7 +281,7 @@ describe("WebSocketDurableObject", () => {
it("fails closed and sweeps user sockets when userId is missing entirely", async () => {
const { durable, ctx } = createDO()
const wsAuth = createMockWebSocket()
- wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ wsAuth.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "u1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
; (ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([wsAuth])
const res = await durable.fetch(new Request("http://internal/check-user-online"))
@@ -299,7 +300,7 @@ describe("WebSocketDurableObject", () => {
const { durable, ctx } = createDO()
mockGetUserInternal.mockResolvedValue({ isBot: false } as any)
const attacker = createMockWebSocket()
- attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ attacker.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker])
const res = await durable.fetch(
@@ -407,7 +408,7 @@ describe("WebSocketDurableObject", () => {
await (durable as unknown as PresenceInternals).sendPresenceSnapshot(ws as any, "user-1")
expect(ws.send).toHaveBeenCalledWith(
- JSON.stringify({ type: "community:presence.update", userId: "friend-c", online: true }),
+ JSON.stringify({ type: "community:presence.update", userId: "friend-c", online: true, schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
})
@@ -441,12 +442,12 @@ describe("WebSocketDurableObject", () => {
authenticated: false,
})
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
await flushAsyncWork()
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(ws.send).toHaveBeenCalledWith(
- JSON.stringify({ type: "community:presence.update", userId: "online", online: true }),
+ JSON.stringify({ type: "community:presence.update", userId: "online", online: true, schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
expect(ws.send).toHaveBeenCalledTimes(2)
})
@@ -629,11 +630,11 @@ describe("WebSocketDurableObject", () => {
it("does nothing when a typing frame has no channelId", async () => {
const { durable } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start" }),
+ JSON.stringify({ type: "community:typing.start", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flush()
@@ -646,25 +647,25 @@ describe("WebSocketDurableObject", () => {
mockGetChannelForMember.mockResolvedValue({ id: "channel-1", serverId: "server-1" })
mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const now = vi.spyOn(Date, "now")
try {
now.mockReturnValue(10_000)
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "channel-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "channel-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
now.mockReturnValue(17_999)
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "channel-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "channel-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
now.mockReturnValue(18_000)
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "channel-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "channel-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -678,20 +679,20 @@ describe("WebSocketDurableObject", () => {
const { durable } = createDO()
mockGetChannelForMember.mockResolvedValue(null)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
let timestamp = 100_000
const now = vi.spyOn(Date, "now").mockImplementation(() => timestamp)
try {
for (let index = 0; index < 200; index++) {
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: `stale-${index}` }),
+ JSON.stringify({ type: "community:typing.start", channelId: `stale-${index}`, schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
}
timestamp = 140_001
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "current" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "current", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
const typingDedup = (durable as unknown as {
@@ -709,11 +710,11 @@ describe("WebSocketDurableObject", () => {
mockGetChannelForMember.mockResolvedValueOnce(null)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-private" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-private", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flush()
@@ -732,11 +733,11 @@ describe("WebSocketDurableObject", () => {
mockResolveScopeMemberUserIds.mockResolvedValueOnce(["member-1", "member-2", "sender-1"])
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flush()
@@ -761,11 +762,11 @@ describe("WebSocketDurableObject", () => {
mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "member-1"])
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-p" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-p", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flush()
@@ -789,11 +790,11 @@ describe("WebSocketDurableObject", () => {
mockResolveScopeMemberUserIds.mockResolvedValueOnce(["sender-1", "reader-1"])
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "t-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "t-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flush()
@@ -813,8 +814,8 @@ describe("WebSocketDurableObject", () => {
let clock = 10_000
const now = vi.spyOn(Date, "now").mockImplementation(() => clock)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
- const start = JSON.stringify({ type: "community:typing.start", channelId: "t-1" })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ const start = JSON.stringify({ type: "community:typing.start", channelId: "t-1", schemaVersion: BUSINESS_SCHEMA_VERSION })
try {
await durable.webSocketMessage(ws as any, start)
await flushAsyncWork()
@@ -826,7 +827,7 @@ describe("WebSocketDurableObject", () => {
expect(mockStubFetch).toHaveBeenCalledTimes(1)
expect(mockResolveChannelRecipientUserIds).toHaveBeenCalledTimes(1)
expect(mockIsThreadParticipant).toHaveBeenCalledTimes(2)
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "community:typing.stop", channelId: "t-1" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "community:typing.stop", channelId: "t-1", schemaVersion: BUSINESS_SCHEMA_VERSION }))
await flushAsyncWork()
expect(mockStubFetch).toHaveBeenCalledTimes(2)
mockIsThreadParticipant.mockResolvedValue(true)
@@ -850,11 +851,11 @@ describe("WebSocketDurableObject", () => {
mockGetChannelForMember.mockResolvedValueOnce(null)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flush()
@@ -871,11 +872,11 @@ describe("WebSocketDurableObject", () => {
mockGetDMPeer.mockResolvedValueOnce({ otherUserId: "bob" })
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flush()
@@ -892,15 +893,15 @@ describe("WebSocketDurableObject", () => {
mockAreFriends.mockResolvedValue(false)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.stop", channelId: "dm-1" }),
+ JSON.stringify({ type: "community:typing.stop", channelId: "dm-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -919,10 +920,10 @@ describe("WebSocketDurableObject", () => {
mockAreFriends.mockResolvedValue(true)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "alice", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "dm-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "dm-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -941,11 +942,11 @@ describe("WebSocketDurableObject", () => {
try { return await fn() } catch { return fn() }
})
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -957,7 +958,7 @@ describe("WebSocketDurableObject", () => {
"ws-do:agent-typing-recipients",
])
const request = mockStubFetch.mock.calls[0]![0] as Request
- expect(JSON.parse(await request.text())).toEqual({
+ expect(JSON.parse(await request.text())).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:typing.start",
channelId: "chan-1",
userId: "sender-1",
@@ -981,11 +982,11 @@ describe("WebSocketDurableObject", () => {
})
;(env.WS_DO.get as ReturnType<typeof vi.fn>).mockReturnValue({ fetch })
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -1000,15 +1001,15 @@ describe("WebSocketDurableObject", () => {
.mockResolvedValueOnce({ id: "chan-1", serverId: "server-1" })
mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.start", channelId: "chan-1" }),
+ JSON.stringify({ type: "community:typing.start", channelId: "chan-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.stop", channelId: "chan-1" }),
+ JSON.stringify({ type: "community:typing.stop", channelId: "chan-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
expect(mockLogWarn).toHaveBeenCalledWith("community:typing.start fan-out failed", {
@@ -1016,7 +1017,7 @@ describe("WebSocketDurableObject", () => {
})
expect(mockStubFetch).toHaveBeenCalledTimes(1)
const request = mockStubFetch.mock.calls[0]![0] as Request
- expect(JSON.parse(await request.text())).toEqual({
+ expect(JSON.parse(await request.text())).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:typing.stop",
channelId: "chan-1",
userId: "sender-1",
@@ -1030,7 +1031,7 @@ describe("WebSocketDurableObject", () => {
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.stop", channelId: "chan-1" }),
+ JSON.stringify({ type: "community:typing.stop", channelId: "chan-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -1042,11 +1043,11 @@ describe("WebSocketDurableObject", () => {
it("consumes a typing.stop without a channel and does not fan out", async () => {
const { durable } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.stop" }),
+ JSON.stringify({ type: "community:typing.stop", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -1067,15 +1068,11 @@ describe("WebSocketDurableObject", () => {
mockGetChannelForMember.mockResolvedValue({ id: "chan-1", serverId: "server-1" })
mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({
- type: "community:typing.stop",
- channelId: "chan-1",
- userId: "spoofed-user",
- }),
+ JSON.stringify({ type: "community:typing.stop", channelId: "chan-1", userId: "spoofed-user", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -1085,7 +1082,7 @@ describe("WebSocketDurableObject", () => {
expect((env.WS_DO as any).idFromName).toHaveBeenCalledWith("user:recipient-1")
expect((env.WS_DO as any).idFromName).not.toHaveBeenCalledWith("user:sender-1")
const request = mockStubFetch.mock.calls[0]![0] as Request
- expect(JSON.parse(await request.text())).toEqual({
+ expect(JSON.parse(await request.text())).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:typing.stop",
channelId: "chan-1",
userId: "sender-1",
@@ -1096,11 +1093,11 @@ describe("WebSocketDurableObject", () => {
const { durable } = createDO()
mockGetChannelForMember.mockResolvedValue(null)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "community:typing.stop", channelId: "chan-private" }),
+ JSON.stringify({ type: "community:typing.stop", channelId: "chan-private", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -1118,7 +1115,7 @@ describe("WebSocketDurableObject", () => {
mockGetChannelForMember.mockResolvedValue({ id: "chan-1", serverId: "server-1" })
mockResolveScopeMemberUserIds.mockResolvedValue(["sender-1", "recipient-1"])
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "sender-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
let releaseFirstFetch!: () => void
mockStubFetch.mockImplementationOnce(() => new Promise<Response>((resolve) => {
releaseFirstFetch = () => resolve(new Response(null, { status: 200 }))
@@ -1132,7 +1129,7 @@ describe("WebSocketDurableObject", () => {
].map((type) => (
durable.webSocketMessage(
ws as any,
- JSON.stringify({ type, channelId: "chan-1" }),
+ JSON.stringify({ type, channelId: "chan-1", schemaVersion: BUSINESS_SCHEMA_VERSION }),
)
))
await flushAsyncWork()
diff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.ts
index a37f4d7ae..86eb8419f 100644
--- a/src/ws-do/src/ws-durable/presence-typing.ts
+++ b/src/ws-do/src/ws-durable/presence-typing.ts
@@ -4,6 +4,7 @@ import {
withD1Retry,
WS_EVENTS,
encodeCommunityBrowserEvent,
+ validateCommunityWsEvent,
isCommunityEventCandidate,
visibilityIsDmParticipant,
type Database,
@@ -12,7 +13,6 @@ import type { UserConnectionState, WsDurableContext } from "./internal"
import { createInternalBrowserBroadcastRequest } from "../internal-user-broadcast"
import {
logCommunityBrowserEventRejected,
- normalizeCommunityBrowserEvent,
} from "../community-browser-event-ingress"
function normalizeBrowserPayload(
@@ -20,7 +20,7 @@ function normalizeBrowserPayload(
payload: unknown,
): { ok: true; payload: unknown } | { ok: false } {
if (!isCommunityEventCandidate(payload)) return { ok: true, payload }
- const normalized = normalizeCommunityBrowserEvent(payload)
+ const normalized = validateCommunityWsEvent(payload)
if (!normalized.ok) {
logCommunityBrowserEventRejected(context.log, "ws-do-producer", normalized)
return { ok: false }
diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.ts
index 14f1aa527..441e84b9d 100644
--- a/src/ws-do/src/ws-durable/user-auth.test.ts
+++ b/src/ws-do/src/ws-durable/user-auth.test.ts
@@ -1,3 +1,4 @@
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import {
deriveCommunityDeliveryOperationId,
@@ -73,16 +74,16 @@ describe("WebSocketDurableObject", () => {
const { durable, getWebSockets, storage, store } = createDO()
const owner = createMockWebSocket()
const other = createMockWebSocket()
- const ownerState = { type: "user", userId: "owner", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 }
+ const ownerState = { communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "owner", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 }
owner.serializeAttachment(ownerState)
other.serializeAttachment({ ...ownerState, userId: "other" })
getWebSockets.mockReturnValue([owner, other])
const event = { type: "community:bot.pii", machineId: "machine", botId: "bot", requestId: "preview", result: { status: "complete", snapshot: { revision: 1, plugins: [] }, output: "private-output-fixture" } }
const response = await durable.fetch(new Request("http://internal/community-broadcast", {
- method: "POST", headers: { [INTERNAL_USER_TARGET_HEADER]: "owner" }, body: JSON.stringify(event),
+ method: "POST", headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: "owner" }, body: JSON.stringify({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }),
}))
expect(await response.json()).toEqual({ sent: 1 })
- expect(owner.send).toHaveBeenCalledWith(JSON.stringify(event))
+ expect(owner.send).toHaveBeenCalledWith(JSON.stringify({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }))
expect(other.send).not.toHaveBeenCalled()
expect(storage.put).not.toHaveBeenCalled()
expect(owner.deserializeAttachment()).toEqual(ownerState)
@@ -100,28 +101,28 @@ describe("WebSocketDurableObject", () => {
it("delivers a validated self-event to the authenticated target socket", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
const res = await durable.fetch(new Request("http://internal/community-broadcast", {
method: "POST",
- headers: { [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
- body: JSON.stringify(event),
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
+ body: JSON.stringify({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }),
}))
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({ sent: 1 })
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify(event))
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }))
})
it("rejects removed-version, invalid, and oversized frames before socket delivery", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
const request = (body: string) => new Request("http://internal/community-broadcast", {
method: "POST",
- headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: "user-42" },
body,
})
@@ -141,12 +142,12 @@ describe("WebSocketDurableObject", () => {
it("gates single content, preserves removal controls, and reports transient D1 failure", async () => {
const { durable, ctx } = createDO()
const socket = createMockWebSocket()
- socket.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ socket.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([socket])
const send = (event: unknown) => durable.fetch(new Request("http://internal/community-broadcast", {
method: "POST",
- headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },
- body: JSON.stringify(event),
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: "user-42" },
+ body: JSON.stringify({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }),
}))
const typing = { type: "community:typing.start", channelId: "private", userId: "author" }
mockListReadableChannelsForUser.mockResolvedValueOnce([])
@@ -155,7 +156,7 @@ describe("WebSocketDurableObject", () => {
mockListReadableChannelsForUser.mockRejectedValueOnce(new Error("D1 temporary"))
expect((await send(typing)).status).toBe(503)
expect(socket.send).not.toHaveBeenCalled()
- const control = { type: "community:channel.member_remove", channelId: "private", serverId: "server", userId: "user-42" }
+ const control = { type: "community:channel.membership.change", channelId: "private", serverId: "server", userId: "user-42", relation: "access", present: false }
expect((await send(control)).status).toBe(200)
expect(socket.send).toHaveBeenCalledOnce()
})
@@ -163,12 +164,12 @@ describe("WebSocketDurableObject", () => {
it.each(["none", "unauthenticated", "other-user", "daemon"])("skips single-content D1 checks for %s sockets after strict validation", async (kind) => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: kind === "daemon" ? "daemon" : "user", userId: kind === "other-user" ? "other" : "user-42", authenticated: kind !== "unauthenticated" })
+ ws.serializeAttachment({ communityContract: kind === "daemon" ? undefined : BUSINESS_SCHEMA_VERSION, type: kind === "daemon" ? "daemon" : "user", userId: kind === "other-user" ? "other" : "user-42", authenticated: kind !== "unauthenticated" })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue(kind === "none" ? [] : [ws])
const send = (event: unknown) => durable.fetch(new Request("http://internal/community-broadcast", {
method: "POST",
- headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },
- body: JSON.stringify(event),
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: "user-42" },
+ body: JSON.stringify({ ...event, schemaVersion: BUSINESS_SCHEMA_VERSION }),
}))
const event = { type: "community:typing.start", channelId: "private", userId: "author" }
mockListReadableChannelsForUser.mockRejectedValue(new Error("offline D1 must not run"))
@@ -183,9 +184,10 @@ describe("WebSocketDurableObject", () => {
const events = [
{
type: "community:message.create",
+ profiles: [{ id: "author", name: "Alice", discriminator: "0001", avatar: null, avatarVersion: 0 }],
channelId: "ch-1",
message: {
- id: "m-1",
+ id: "m-1", channelId: "ch-1", replyToId: null, clientNonce: null, attachments: [],
seq: 1,
authorId: "author",
authorName: "Alice",
@@ -212,18 +214,17 @@ describe("WebSocketDurableObject", () => {
async function requestFor(
inputEvents: readonly unknown[] = events,
- overrides: { operationId?: string; operationDigest?: string; contract?: 2 | 3 } = {},
+ overrides: { operationId?: string; operationDigest?: string; contract?: number } = {},
): Promise<Request> {
- const prepared = await prepareCommunityDeliveryEvents(inputEvents, overrides.contract ?? 2)
+ const prepared = await prepareCommunityDeliveryEvents(inputEvents, overrides.contract ?? BUSINESS_SCHEMA_VERSION)
if (!prepared.ok) throw new Error(`invalid fixture: ${prepared.reason}`)
return new Request("http://internal/community-broadcast-bundle", {
method: "POST",
- headers: { [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
- body: JSON.stringify({
- operationId: overrides.operationId ?? await deriveCommunityDeliveryOperationId("m-1"),
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
+ body: JSON.stringify({ operationId: overrides.operationId ?? await deriveCommunityDeliveryOperationId("m-1"),
operationDigest: overrides.operationDigest ?? prepared.prepared.digest,
events: prepared.prepared.envelopes,
- ...(overrides.contract === 3 ? { communityContract: 3 } : {}),
+ communityContract: overrides.contract ?? BUSINESS_SCHEMA_VERSION,
}),
})
}
@@ -231,7 +232,7 @@ describe("WebSocketDurableObject", () => {
it("cancels revoked content without changing progress, and retries transient failures", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
const request = await requestFor()
const original = ws.deserializeAttachment()
@@ -255,7 +256,7 @@ describe("WebSocketDurableObject", () => {
it("reads current sockets and progress only after concurrent authorization awaits", async () => {
const { durable, ctx } = createDO()
const old = createMockWebSocket()
- old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ old.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const sockets = ctx.getWebSockets as ReturnType<typeof vi.fn>
sockets.mockReturnValue([old])
const releases: Array<(rows: Array<{ id: string }>) => void> = []
@@ -266,7 +267,7 @@ describe("WebSocketDurableObject", () => {
const second = durable.fetch(request.clone())
await vi.waitFor(() => expect(releases).toHaveLength(2))
const current = createMockWebSocket()
- current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ current.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
sockets.mockReturnValue([current])
releases[1]!([{ id: "ch-1" }])
await second
@@ -280,7 +281,7 @@ describe("WebSocketDurableObject", () => {
const { durable } = createDO()
const response = await durable.fetch(new Request(
"http://internal/community-broadcast-bundle",
- { method: "POST", body: "{}" },
+ { headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) }, method: "POST", body: "{}" },
))
expect(response.status).toBe(400)
@@ -295,12 +296,12 @@ describe("WebSocketDurableObject", () => {
const { durable, ctx } = createDO()
const first = createMockWebSocket()
const second = createMockWebSocket()
- first.serializeAttachment({
+ first.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
})
- second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ second.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])
const response = await durable.fetch(await requestFor())
@@ -316,12 +317,12 @@ describe("WebSocketDurableObject", () => {
})
expect(first.send).toHaveBeenCalledTimes(1)
expect(JSON.parse(first.send.mock.calls[0][0] as string)).toMatchObject({
- type: "community:events.batch",
+ type: `community:events.batch.v${BUSINESS_SCHEMA_VERSION}`,
events: expect.any(Array),
})
expect(second.send).toHaveBeenCalledTimes(1)
expect(JSON.parse(second.send.mock.calls[0][0] as string)).toMatchObject({
- type: "community:events.batch",
+ type: `community:events.batch.v${BUSINESS_SCHEMA_VERSION}`,
events: expect.any(Array),
})
expect(first.deserializeAttachment()).toMatchObject({
@@ -332,27 +333,33 @@ describe("WebSocketDurableObject", () => {
})
})
- it("restores selected formats from attachments and retains source progress for mixed tabs", async () => {
+ it("retires old authenticated business sockets and delivers only the current tab", async () => {
const { durable, ctx } = createDO()
- const old = createMockWebSocket(), current = createMockWebSocket()
- old.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
- current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 2 })
- ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([old, current])
+ const old = [undefined, 1, 2, 3, BUSINESS_SCHEMA_VERSION - 1].map(version => {
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, ...(version === undefined ? {} : { communityContract: version }) })
+ return ws
+ })
+ const current = createMockWebSocket()
+ current.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: BUSINESS_SCHEMA_VERSION })
+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([...old, current])
const change = { type: "community:channel.membership.change", channelId: "thread", serverId: "server", userId: "user-42", relation: "notify", present: true }
const request = await requestFor([change])
const source = await request.clone().json() as { operationDigest: string }
expect((await durable.fetch(request.clone())).status).toBe(200)
- const oldFrame = JSON.parse(old.send.mock.calls[0]![0] as string)
- const newFrame = JSON.parse(current.send.mock.calls[0]![0] as string)
- expect(Object.keys(oldFrame)).toHaveLength(4)
- expect(oldFrame.events).toEqual([{ type: "community:channel.member_add", serverId: "server", channelId: "thread", userId: "user-42" }])
- expect(newFrame).toMatchObject({ type: "community:events.batch.v2", operationDigest: source.operationDigest, events: [change] })
- expect(oldFrame.operationDigest).not.toBe(source.operationDigest)
- expect((old.deserializeAttachment() as { communityDeliveryProgress: string[][] }).communityDeliveryProgress[0]![1]).toBe(source.operationDigest)
+ for (const ws of old) {
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.error", error: "Unsupported community contract", communityContract: BUSINESS_SCHEMA_VERSION }))
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unsupported community contract")
+ expect(ws.deserializeAttachment()).toMatchObject({ authenticated: false })
+ expect(ws.deserializeAttachment()).not.toHaveProperty("communityDeliveryProgress")
+ }
+ const frame = JSON.parse(current.send.mock.calls[0]![0] as string)
+ expect(frame.type).toBe(`community:events.batch.v${BUSINESS_SCHEMA_VERSION}`)
+ expect(await decodeCommunityBrowserEventBatch(frame)).toMatchObject({ ok: true, events: [change] })
expect((current.deserializeAttachment() as { communityDeliveryProgress: string[][] }).communityDeliveryProgress[0]![1]).toBe(source.operationDigest)
expect((await durable.fetch(request)).status).toBe(200)
- expect(old.send).toHaveBeenCalledTimes(1)
- expect(current.send).toHaveBeenCalledTimes(1)
+ expect(current.send).toHaveBeenCalledOnce()
+ for (const ws of old) expect(ws.send).toHaveBeenCalledOnce()
})
const resourceEvents = [
@@ -368,29 +375,26 @@ describe("WebSocketDurableObject", () => {
...events.slice(1),
]
- it("delivers exact resource data to 1/2/3 sockets and restores source progress after reconstruction", async () => {
+ it("delivers exact current resources to three tabs and restores their progress after reconstruction", async () => {
const { durable, ctx, env } = createDO()
- const sockets = [1, 2, 3].map((communityContract) => {
+ const sockets = Array.from({ length: 3 }, () => {
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract })
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: BUSINESS_SCHEMA_VERSION })
return ws
})
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue(sockets)
- const request = await requestFor(resourceEvents, { contract: 3 })
+ const request = await requestFor(resourceEvents)
const source = await request.clone().json() as { operationId: string; operationDigest: string; events: unknown[] }
expect((await durable.fetch(request.clone())).status).toBe(200)
- for (const [index, ws] of sockets.entries()) {
+ for (const ws of sockets) {
const frame = ws.send.mock.calls[0]![0] as string
- const decoded = await decodeCommunityBrowserEventBatch(JSON.parse(frame))
- expect(decoded.ok).toBe(true)
- if (index === 2 && decoded.ok) expect(decoded.events).toEqual(source.events)
+ expect(await decodeCommunityBrowserEventBatch(JSON.parse(frame))).toMatchObject({ ok: true, events: resourceEvents })
expect(utf8ByteLength(frame)).toBe(new TextEncoder().encode(frame).byteLength)
- expect(JSON.parse(frame).type).toBe(index === 0 ? "community:events.batch" : `community:events.batch.v${index + 1}`)
+ expect(JSON.parse(frame).events).toEqual(source.events)
+ expect(JSON.parse(frame).type).toBe(`community:events.batch.v${BUSINESS_SCHEMA_VERSION}`)
expect(ws.deserializeAttachment()).toMatchObject({ communityDeliveryProgress: [[source.operationId, source.operationDigest, 1, 1]] })
ws.send.mockClear()
}
- const encoded = await prepareCommunityDeliveryEvents(resourceEvents, 3)
- expect(encoded.ok && encoded.prepared.envelopes).toEqual(source.events)
const { WebSocketDurableObject } = await import("../ws-durable")
const restored = new WebSocketDurableObject(ctx, env)
const retry = await restored.fetch(request)
@@ -399,28 +403,25 @@ describe("WebSocketDurableObject", () => {
for (const ws of sockets) expect(ws.send).not.toHaveBeenCalled()
})
- it("retries the original three-key payload after reconstruction and rejects a rebuilt cross-version operation before any frame or progress change", async () => {
+ it("retries exact current bytes after reconstruction and rejects changed bytes before progress or sends", async () => {
const { durable, ctx, env } = createDO()
const completed = createMockWebSocket(), retrying = createMockWebSocket()
- completed.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 1 })
- retrying.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 2 })
+ for (const ws of [completed, retrying]) ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: BUSINESS_SCHEMA_VERSION })
retrying.send.mockImplementationOnce(() => { throw new Error("transient send") })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying])
const original = await requestFor()
const originalBody = await original.clone().text()
- expect(Object.keys(JSON.parse(originalBody))).toEqual(["operationId", "operationDigest", "events"])
+ expect(Object.keys(JSON.parse(originalBody)).sort()).toEqual(["communityContract", "events", "operationDigest", "operationId"])
expect((await durable.fetch(original.clone())).status).toBe(503)
- const saved = [completed, retrying].map((ws) => ws.deserializeAttachment())
- completed.send.mockClear()
- retrying.send.mockClear()
+ const saved = [completed, retrying].map(ws => ws.deserializeAttachment())
+ completed.send.mockClear(); retrying.send.mockClear()
const unstarted = createMockWebSocket()
- unstarted.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 3 })
+ unstarted.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: BUSINESS_SCHEMA_VERSION })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying, unstarted])
const { WebSocketDurableObject } = await import("../ws-durable")
const restored = new WebSocketDurableObject(ctx, env)
- const rebuilt = await requestFor(resourceEvents, { contract: 3 })
- expect((await restored.fetch(rebuilt)).status).toBe(409)
- expect([completed, retrying].map((ws) => ws.deserializeAttachment())).toEqual(saved)
+ expect((await restored.fetch(await requestFor(resourceEvents))).status).toBe(409)
+ expect([completed, retrying].map(ws => ws.deserializeAttachment())).toEqual(saved)
expect(unstarted.deserializeAttachment()).not.toHaveProperty("communityDeliveryProgress")
for (const ws of [completed, retrying, unstarted]) expect(ws.send).not.toHaveBeenCalled()
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([completed, retrying])
@@ -428,39 +429,44 @@ describe("WebSocketDurableObject", () => {
expect(await original.text()).toBe(originalBody)
expect(retry.status).toBe(200)
await expect(retry.json()).resolves.toMatchObject({ enqueued: 1, alreadyEnqueued: 1, attempted: 1 })
- expect(completed.send).not.toHaveBeenCalled()
- expect(retrying.send).toHaveBeenCalledTimes(1)
- expect(JSON.parse(retrying.send.mock.calls[0]![0] as string).type).toBe("community:events.batch.v2")
+ expect(completed.send).not.toHaveBeenCalled(); expect(retrying.send).toHaveBeenCalledOnce()
})
- it("rejects unknown bundle versions and does not upgrade original v2 summary bytes for a v3 socket", async () => {
+ it("rejects missing, old and future internal contracts and weak current resource bytes before delivery", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: 3 })
+ ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: BUSINESS_SCHEMA_VERSION })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
const request = await requestFor()
- const body = await request.clone().json()
- expect((await durable.fetch(new Request(request.url, { method: "POST", headers: request.headers, body: JSON.stringify({ ...body, communityContract: 4 }) }))).status).toBe(400)
- expect((await durable.fetch(request)).status).toBe(503)
- expect(ws.send).not.toHaveBeenCalled()
- expect(ws.deserializeAttachment()).not.toHaveProperty("communityDeliveryProgress")
+ const body = await request.clone().json() as { communityContract?: number; events: Array<{ message?: Record<string, unknown> }> }
+ for (const version of [undefined, 1, 2, 3, BUSINESS_SCHEMA_VERSION - 1, BUSINESS_SCHEMA_VERSION + 1]) {
+ const candidate = { ...body, communityContract: version }
+ expect((await durable.fetch(new Request(request.url, { method: "POST", headers: request.headers, body: JSON.stringify(candidate) }))).status).toBe(400)
+ }
+ for (const version of [null, String(BUSINESS_SCHEMA_VERSION - 1)]) {
+ const headers = new Headers(request.headers)
+ if (version === null) headers.delete(COMMUNITY_CONTRACT_HEADER); else headers.set(COMMUNITY_CONTRACT_HEADER, version)
+ expect((await durable.fetch(new Request(request.url, { method: "POST", headers, body: JSON.stringify(body) }))).status).toBe(400)
+ }
+ const weak = structuredClone(body)
+ delete weak.events[0]!.message!.channelId
+ expect((await durable.fetch(new Request(request.url, { method: "POST", headers: request.headers, body: JSON.stringify(weak) }))).status).toBe(400)
+ expect(ws.send).not.toHaveBeenCalled(); expect(ws.deserializeAttachment()).not.toHaveProperty("communityDeliveryProgress")
+ expect((await durable.fetch(request)).status).toBe(200)
+ expect(ws.send).toHaveBeenCalledOnce()
})
it("sends zero frames when any event is invalid", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
const prepared = await prepareCommunityDeliveryEvents(events)
if (!prepared.ok) throw new Error("fixture must prepare")
const response = await durable.fetch(new Request("http://internal/community-broadcast-bundle", {
method: "POST",
- headers: { [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
- body: JSON.stringify({
- operationId: await deriveCommunityDeliveryOperationId("m-1"),
- operationDigest: prepared.prepared.digest,
- events: [...prepared.prepared.envelopes, { type: "community:unknown" }],
- }),
+ headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: encodeURIComponent("user-42") },
+ body: JSON.stringify({ operationId: await deriveCommunityDeliveryOperationId("m-1"), operationDigest: prepared.prepared.digest, events: [...prepared.prepared.envelopes, { schemaVersion: BUSINESS_SCHEMA_VERSION, type: "community:unknown" }], communityContract: BUSINESS_SCHEMA_VERSION }),
}))
expect(response.status).toBe(400)
@@ -470,7 +476,7 @@ describe("WebSocketDurableObject", () => {
it("suppresses a completed same-digest retry and rejects same-ID/different-digest before sends", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
@@ -496,9 +502,9 @@ describe("WebSocketDurableObject", () => {
it("records a successful tab, reports a sibling batch send failure, and retries only the sibling", async () => {
const { durable, ctx } = createDO()
const first = createMockWebSocket()
- first.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ first.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const second = createMockWebSocket()
- second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ second.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
second.send.mockImplementationOnce(() => { throw new Error("send failed") })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])
@@ -522,19 +528,19 @@ describe("WebSocketDurableObject", () => {
await expect(retry.json()).resolves.toMatchObject({ attempted: 1, enqueued: 1, alreadyEnqueued: 1 })
expect(first.send).not.toHaveBeenCalled()
expect(second.send).toHaveBeenCalledTimes(1)
- expect(JSON.parse(second.send.mock.calls[0][0] as string).type).toBe("community:events.batch")
+ expect(JSON.parse(second.send.mock.calls[0][0] as string).type).toBe(`community:events.batch.v${BUSINESS_SCHEMA_VERSION}`)
})
it("aborts phase A for every socket when one attachment preflight fails", async () => {
const { durable, ctx } = createDO()
const ready = createMockWebSocket()
- ready.serializeAttachment({
+ ready.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
})
const malformed = createMockWebSocket()
- malformed.serializeAttachment({
+ malformed.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
@@ -567,7 +573,7 @@ describe("WebSocketDurableObject", () => {
const operationId = await deriveCommunityDeliveryOperationId("m-1")
const prepared = await prepareCommunityDeliveryEvents(events)
if (!prepared.ok) throw new Error("fixture must prepare")
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
@@ -590,7 +596,7 @@ describe("WebSocketDurableObject", () => {
const ws = createMockWebSocket()
let progressReads = 0
const state = {
- type: "user" as const,
+ type: "user" as const, communityContract: BUSINESS_SCHEMA_VERSION, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
userId: "user-42",
authenticated: true,
get communityDeliveryProgress() {
@@ -611,7 +617,7 @@ describe("WebSocketDurableObject", () => {
it("fails phase A when the next persisted cursor would exceed the attachment budget", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
@@ -629,13 +635,13 @@ describe("WebSocketDurableObject", () => {
it("treats a batch encoder invariant fault as all-socket zero-send", async () => {
const { durable, ctx } = createDO()
const first = createMockWebSocket()
- first.serializeAttachment({
+ first.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
})
const second = createMockWebSocket()
- second.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ second.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([first, second])
mockEncodeCommunityBrowserEventBatchForContract.mockReturnValueOnce({
ok: false,
@@ -661,7 +667,7 @@ describe("WebSocketDurableObject", () => {
it.each(["none", "unauthenticated", "other-user", "daemon"])("returns an exact zero-matched receipt without D1 for %s sockets", async (kind) => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: kind === "daemon" ? "daemon" : "user", userId: kind === "other-user" ? "other" : "user-42", authenticated: kind !== "unauthenticated" })
+ ws.serializeAttachment({ communityContract: kind === "daemon" ? undefined : BUSINESS_SCHEMA_VERSION, type: kind === "daemon" ? "daemon" : "user", userId: kind === "other-user" ? "other" : "user-42", authenticated: kind !== "unauthenticated" })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue(kind === "none" ? [] : [ws])
mockListReadableChannelsForUser.mockRejectedValue(new Error("offline D1 must not run"))
@@ -701,7 +707,7 @@ describe("WebSocketDurableObject", () => {
await expect((await durable.fetch(request.clone())).json()).resolves.toMatchObject({ matched: 0, enqueued: 0 })
expect(mockCreateDb).not.toHaveBeenCalled()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
sockets.mockReturnValue([ws])
mockListReadableChannelsForUser.mockResolvedValueOnce([])
await expect((await durable.fetch(request.clone())).json()).resolves.toMatchObject({ status: "cancelled", targetUserId: "user-42" })
@@ -714,7 +720,7 @@ describe("WebSocketDurableObject", () => {
it("returns zero matches when the last target closes during its access query", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const sockets = ctx.getWebSockets as ReturnType<typeof vi.fn>
sockets.mockReturnValue([ws])
let release!: (rows: Array<{ id: string }>) => void
@@ -725,13 +731,13 @@ describe("WebSocketDurableObject", () => {
release([{ id: "ch-1" }])
await expect((await pending).json()).resolves.toMatchObject({ matched: 0, enqueued: 0 })
expect(ws.send).not.toHaveBeenCalled()
- expect(ws.deserializeAttachment()).toMatchObject({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number) })
+ expect(ws.deserializeAttachment()).toMatchObject({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number) })
})
it("closes a socket and reports ambiguity when attachment persistence fails after send", async () => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
@@ -801,7 +807,7 @@ describe("WebSocketDurableObject", () => {
it("echoes an exact connection nonce only for an authenticated user", async () => {
const { durable } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
targetUserId: "user-42",
@@ -848,7 +854,7 @@ describe("WebSocketDurableObject", () => {
])("consumes invalid or client-response control frame %#", async (frame) => {
const { durable } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
targetUserId: "user-42",
@@ -862,17 +868,17 @@ describe("WebSocketDurableObject", () => {
expect(mockGetChannelForMember).not.toHaveBeenCalled()
})
- it("ignores array frames without treating them as connection controls", async () => {
+ it.each([[], {}, { type: 4 }, null, "text", 4])("ignores malformed control frames %j", async frame => {
const { durable } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
targetUserId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000,
})
- await durable.webSocketMessage(ws as any, JSON.stringify([]))
+ await durable.webSocketMessage(ws as any, JSON.stringify(frame))
expect(ws.send).not.toHaveBeenCalled()
expect(ws.close).not.toHaveBeenCalled()
@@ -910,16 +916,16 @@ describe("WebSocketDurableObject", () => {
authenticated: false,
})
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(mockGetValidSessionWithIdentity).toHaveBeenCalledWith({}, "valid-token")
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(ws.deserializeAttachment()).toMatchObject({
type: "user",
userId: "user-42",
targetUserId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number),
- communityContract: 1,
+ communityContract: BUSINESS_SCHEMA_VERSION,
name: "Ana",
discriminator: "0012",
})
@@ -931,7 +937,7 @@ describe("WebSocketDurableObject", () => {
const operationId = await deriveCommunityDeliveryOperationId("message-reauth")
const progress = [[operationId, "a".repeat(64), 1, 1]]
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
targetUserId: "user-42",
@@ -939,9 +945,9 @@ describe("WebSocketDurableObject", () => {
communityDeliveryProgress: progress,
})
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
- expect(ws.deserializeAttachment()).toMatchObject({
+ expect(ws.deserializeAttachment()).toMatchObject({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "user-42",
authenticated: true, sessionId: "test-session", sessionValidUntil: expect.any(Number),
@@ -949,36 +955,36 @@ describe("WebSocketDurableObject", () => {
})
})
- it.each([1, 2, 3] as const)("keeps contract %s fixed across successful reauthentication", async (version) => {
+ it.each([1, 2, 3, BUSINESS_SCHEMA_VERSION - 1])("refuses reauthentication from an obsolete business socket %s", async version => {
const { durable } = createDO()
mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "user-42", targetUserId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000, communityContract: version })
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: version === 1 ? 2 : 1 }))
- expect(ws.deserializeAttachment()).toMatchObject({ authenticated: true, communityContract: version })
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", ...(version !== 1 ? { communityContract: version } : {}) }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unsupported community contract")
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.error", error: "Unsupported community contract", communityContract: BUSINESS_SCHEMA_VERSION }))
+ expect(ws.send.mock.calls.every(([frame]) => JSON.parse(frame).type !== "auth.ok")).toBe(true)
})
- it.each([2, 3])("confirms an explicitly requested contract %s on first authentication", async (communityContract) => {
+ it.each([undefined, 1, 2, 3, BUSINESS_SCHEMA_VERSION - 1, BUSINESS_SCHEMA_VERSION + 1])("rejects requested contract %s before storing current authentication", async version => {
const { durable } = createDO()
mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "", targetUserId: "user-42", authenticated: false })
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract }))
- expect(ws.deserializeAttachment()).toMatchObject({ authenticated: true, communityContract })
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", communityContract }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", ...(version === undefined ? {} : { communityContract: version }) }))
+ expect(ws.deserializeAttachment()).toMatchObject({ authenticated: false })
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unsupported community contract")
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.error", error: "Unsupported community contract", communityContract: BUSINESS_SCHEMA_VERSION }))
})
- it("rejects an unknown requested contract before storing authentication", async () => {
+ it("confirms the explicit current contract on first authentication", async () => {
const { durable } = createDO()
mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })
const ws = createMockWebSocket()
- const original = { type: "user", userId: "", targetUserId: "user-42", authenticated: false }
- ws.serializeAttachment(original)
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: 4 }))
- expect(ws.deserializeAttachment()).toEqual(original)
- expect(ws.close).toHaveBeenCalledWith(1008, "Unsupported community contract")
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.error", error: "Unsupported community contract" }))
+ ws.serializeAttachment({ type: "user", userId: "", targetUserId: "user-42", authenticated: false })
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
+ expect(ws.deserializeAttachment()).toMatchObject({ authenticated: true, communityContract: BUSINESS_SCHEMA_VERSION })
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION }))
})
it("retries a transient session lookup before authenticating", async () => {
@@ -1001,13 +1007,13 @@ describe("WebSocketDurableObject", () => {
authenticated: false,
})
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(mockWithD1Retry).toHaveBeenCalledWith(expect.any(Function), {
route: "ws-do:user-auth-session",
})
expect(mockGetValidSessionWithIdentity).toHaveBeenCalledTimes(2)
- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))
+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(ws.close).not.toHaveBeenCalled()
})
@@ -1030,7 +1036,7 @@ describe("WebSocketDurableObject", () => {
authenticated: false,
})
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
await flushAsyncWork()
const requests = mockStubFetch.mock.calls.map(([request]) => request as Request)
@@ -1044,7 +1050,7 @@ describe("WebSocketDurableObject", () => {
mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])
mockStubFetch.mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ online: false })))
const existing = createMockWebSocket()
- existing.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ existing.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([existing])
const ws = createMockWebSocket()
ws.serializeAttachment({
@@ -1054,7 +1060,7 @@ describe("WebSocketDurableObject", () => {
authenticated: false,
})
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token", communityContract: BUSINESS_SCHEMA_VERSION }))
await flushAsyncWork()
const requests = mockStubFetch.mock.calls.map(([request]) => request as Request)
@@ -1088,7 +1094,7 @@ describe("WebSocketDurableObject", () => {
await durable.webSocketMessage(
accepted,
- JSON.stringify({ type: "auth", token: "attacker-session-token" }),
+ JSON.stringify({ type: "auth", token: "attacker-session-token", communityContract: BUSINESS_SCHEMA_VERSION }),
)
await flushAsyncWork()
@@ -1113,12 +1119,12 @@ describe("WebSocketDurableObject", () => {
discriminator: "0066",
})
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "attacker", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "auth", token: "attacker-session-token" }),
+ JSON.stringify({ type: "auth", token: "attacker-session-token", communityContract: BUSINESS_SCHEMA_VERSION }),
)
expect(ws.deserializeAttachment()).toMatchObject({
@@ -1147,7 +1153,7 @@ describe("WebSocketDurableObject", () => {
new (globalThis.Response as any)(JSON.stringify({ sent: 1 })),
)
const ws = createMockWebSocket()
- ws.serializeAttachment({
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "victim",
targetUserId: "victim",
@@ -1157,10 +1163,10 @@ describe("WebSocketDurableObject", () => {
await durable.webSocketMessage(
ws as any,
- JSON.stringify({ type: "auth", token: "attacker-session-token" }),
+ JSON.stringify({ type: "auth", token: "attacker-session-token", communityContract: BUSINESS_SCHEMA_VERSION }),
)
- expect(ws.deserializeAttachment()).toMatchObject({
+ expect(ws.deserializeAttachment()).toMatchObject({ communityContract: BUSINESS_SCHEMA_VERSION,
type: "user",
userId: "victim",
targetUserId: "victim",
@@ -1171,7 +1177,7 @@ describe("WebSocketDurableObject", () => {
await flushAsyncWork()
const [request] = mockStubFetch.mock.calls[0] as [Request]
- expect(await request.clone().json()).toEqual({
+ expect(await request.clone().json()).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:presence.update",
userId: "victim",
online: false,
@@ -1185,7 +1191,7 @@ describe("WebSocketDurableObject", () => {
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "bad" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "bad", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
expect(ws.send).not.toHaveBeenCalled()
@@ -1198,7 +1204,7 @@ describe("WebSocketDurableObject", () => {
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
expect(ws.send).not.toHaveBeenCalled()
@@ -1211,7 +1217,7 @@ describe("WebSocketDurableObject", () => {
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
expect(ws.send).not.toHaveBeenCalled()
@@ -1236,7 +1242,7 @@ describe("WebSocketDurableObject", () => {
const ws = createMockWebSocket()
ws.serializeAttachment({ type: "user", userId: "", authenticated: false })
- await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "expired-token" }))
+ await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "expired-token", communityContract: BUSINESS_SCHEMA_VERSION }))
expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")
expect(ws.send).not.toHaveBeenCalled()
@@ -1397,7 +1403,7 @@ describe("WebSocketDurableObject", () => {
; (env.WS_DO as any).get = vi.fn().mockReturnValue(aliveStub)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
@@ -1415,7 +1421,7 @@ describe("WebSocketDurableObject", () => {
; (env.WS_DO as any).get = vi.fn().mockReturnValue(deadStub)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
@@ -1427,7 +1433,7 @@ describe("WebSocketDurableObject", () => {
mockGetLatestTokenForUser.mockResolvedValue(null)
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
@@ -1441,7 +1447,7 @@ describe("WebSocketDurableObject", () => {
fetch: vi.fn().mockRejectedValue(new Error("daemon DO unavailable")),
})
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
await durable.webSocketMessage(ws as any, JSON.stringify({ type: "check_daemon_status" }))
@@ -1468,9 +1474,9 @@ describe("WebSocketDurableObject", () => {
it("keeps user presence online while another authenticated tab remains", async () => {
const { durable, ctx } = createDO()
const closing = createMockWebSocket()
- closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ closing.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const other = createMockWebSocket()
- other.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ other.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([closing, other])
await durable.webSocketClose(closing as any, 1000, "test complete", true)
@@ -1483,9 +1489,9 @@ describe("WebSocketDurableObject", () => {
it("keeps user presence online when auto-reply already removed the closing tab", async () => {
const { durable, ctx } = createDO()
const closing = createMockWebSocket()
- closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ closing.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
const other = createMockWebSocket()
- other.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ other.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([other])
await durable.webSocketClose(closing as any, 1000, "test complete", true)
@@ -1500,14 +1506,14 @@ describe("WebSocketDurableObject", () => {
mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])
mockStubFetch.mockResolvedValue(new (globalThis.Response as any)(JSON.stringify({ sent: 1 })))
const closing = createMockWebSocket()
- closing.serializeAttachment({ type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
+ closing.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-1", authenticated: true, sessionId: "test-session", sessionValidUntil: Date.now() + 60_000 })
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([closing])
await durable.webSocketClose(closing as any, 1000, "test complete", true)
await flushAsyncWork()
const [request] = mockStubFetch.mock.calls[0] as [Request]
- expect(await request.clone().json()).toEqual({
+ expect(await request.clone().json()).toEqual({ schemaVersion: BUSINESS_SCHEMA_VERSION,
type: "community:presence.update",
userId: "user-1",
online: false,
@@ -1543,15 +1549,15 @@ describe("persisted user session lease", () => {
it.each(["revoked", "db-failure", "historical"])("does not deliver private events to a %s session", async (mode) => {
const { durable, ctx } = createDO()
const ws = createMockWebSocket()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true,
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true,
...(mode === "historical" ? {} : { sessionId: "old-session", sessionValidUntil: 0 }),
})
;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])
if (mode === "db-failure") mockGetValidSessionByIdForUser.mockRejectedValue(new Error("D1 unavailable"))
else mockGetValidSessionByIdForUser.mockResolvedValue(null)
await durable.fetch(new Request("http://internal/community-broadcast", {
- method: "POST", headers: { [INTERNAL_USER_TARGET_HEADER]: "user-42" },
- body: JSON.stringify({ type: "community:status.update", userId: "user-42", statusEmoji: null, statusText: "private" }),
+ method: "POST", headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION), [INTERNAL_USER_TARGET_HEADER]: "user-42" },
+ body: JSON.stringify({ ...{ schemaVersion: BUSINESS_SCHEMA_VERSION, type: "community:status.update", userId: "user-42", statusEmoji: null, statusText: "private" }, schemaVersion: BUSINESS_SCHEMA_VERSION }),
}))
expect(ws.send).not.toHaveBeenCalled()
expect(ws.close).toHaveBeenCalledWith(1008, "Session expired or revoked")
@@ -1561,7 +1567,7 @@ describe("persisted user session lease", () => {
const { durable } = createDO()
const ws = createMockWebSocket()
const expiresAt = new Date(Date.now() + 10_000).toISOString()
- ws.serializeAttachment({ type: "user", userId: "user-42", authenticated: true, sessionId: "session", sessionValidUntil: 0 })
+ ws.serializeAttachment({ communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "session", sessionValidUntil: 0 })
mockGetValidSessionByIdForUser.mockResolvedValue({ expiresAt })
await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify({ type: "connection.ping", nonce: "ping" }))
expect(mockGetValidSessionByIdForUser).toHaveBeenCalledWith({}, "session", "user-42")
@@ -1569,3 +1575,19 @@ describe("persisted user session lease", () => {
expect(ws.close).not.toHaveBeenCalled()
})
})
+
+describe("current socket frame version admission", () => {
+ beforeEach(() => resetHarness())
+ afterEach(() => cleanupHarness())
+ it.each([undefined, BUSINESS_SCHEMA_VERSION - 1, BUSINESS_SCHEMA_VERSION + 1])("closes a current authenticated socket for community frame version %s before side effects", async version => {
+ const { durable } = createDO()
+ const ws = createMockWebSocket()
+ const state = { communityContract: BUSINESS_SCHEMA_VERSION, type: "user", userId: "user-42", authenticated: true, sessionId: "session", sessionValidUntil: Date.now() + 60_000 }
+ ws.serializeAttachment(state)
+ await durable.webSocketMessage(ws as unknown as WebSocket, JSON.stringify({ type: "community:status.update", schemaVersion: version, userId: "user-42", statusEmoji: null, statusText: "Must not publish" }))
+ expect(ws.close).toHaveBeenCalledWith(1008, "Unsupported community contract")
+ expect(mockUpdateProfile).not.toHaveBeenCalled()
+ expect(ws.send).not.toHaveBeenCalled()
+ expect(ws.deserializeAttachment()).toEqual(state)
+ })
+})
diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.ts
index a8a4986b1..33818c9a5 100644
--- a/src/ws-do/src/ws-durable/user-auth.ts
+++ b/src/ws-do/src/ws-durable/user-auth.ts
@@ -1,9 +1,9 @@
import {
+ BUSINESS_SCHEMA_VERSION,
type CommunityContract,
createDb,
encodeCommunityBrowserEventBatchForContract,
encodeCommunityBrowserEvent,
- projectCommunityEventForContract,
isUserWsConnectionPing,
isValidCommunityUserTarget,
queries,
@@ -50,7 +50,8 @@ const USER_SESSION_CHECK_INTERVAL_MS = 60_000
async function refreshUserSession(context: WsDurableContext, ws: WebSocket): Promise<void> {
const state = ws.deserializeAttachment() as ConnectionState
- if (state?.type !== "user" || !state.authenticated || (state.sessionValidUntil ?? 0) > Date.now()) return
+ if (state?.type !== "user" || !state.authenticated) return
+ if (!isCurrentBusinessSocket(ws, state) || (state.sessionValidUntil ?? 0) > Date.now()) return
try {
const session = state.sessionId
? await queries.session.getValidSessionByIdForUser(createDb(context.env.DB), state.sessionId, state.userId)
@@ -244,6 +245,8 @@ export async function handleWebSocketMessage(
let parsed: unknown
try { parsed = JSON.parse(message) } catch { ws.close(1008, "Invalid JSON"); return }
+ const originalState = ws.deserializeAttachment() as ConnectionState
+ if (originalState?.type === "user" && originalState.authenticated && !isCurrentBusinessSocket(ws, originalState)) return
await refreshUserSession(context, ws)
const state = ws.deserializeAttachment() as ConnectionState
@@ -267,6 +270,8 @@ export async function handleWebSocketMessage(
return
}
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || typeof (parsed as Record<string, unknown>).type !== "string") return
+
const msg = parsed as {
type: string
token?: string
@@ -326,13 +331,13 @@ export async function handleWebSocketMessage(
return
}
const wasOnline = countAuthenticatedUserConnections(context, userId) > 0
- const selected = state?.type === "user" && state.authenticated ? state.communityContract : msg.communityContract
- if (selected !== undefined && selected !== 1 && selected !== 2 && selected !== 3) {
- ws.send(JSON.stringify({ type: "auth.error", error: "Unsupported community contract" }))
+ if (msg.communityContract !== BUSINESS_SCHEMA_VERSION
+ || (state?.type === "user" && state.authenticated && state.communityContract !== BUSINESS_SCHEMA_VERSION)) {
+ ws.send(JSON.stringify({ type: "auth.error", error: "Unsupported community contract", communityContract: BUSINESS_SCHEMA_VERSION }))
ws.close(1008, "Unsupported community contract")
return
}
- const communityContract: CommunityContract = selected ?? 1
+ const communityContract = BUSINESS_SCHEMA_VERSION
ws.serializeAttachment({
type: "user",
userId,
@@ -348,7 +353,7 @@ export async function handleWebSocketMessage(
: {}),
} as ConnectionState)
context.log.info("websocket authenticated", { userId })
- ws.send(JSON.stringify({ type: "auth.ok", ...(communityContract !== 1 ? { communityContract } : {}) }))
+ ws.send(JSON.stringify({ type: "auth.ok", communityContract }))
if (!wasOnline) {
broadcastPresence(context, userId, true).catch(() => { })
}
@@ -379,6 +384,11 @@ export async function handleWebSocketMessage(
return
}
+ if (state.type === "user" && !isCurrentBusinessSocket(ws, state)) return
+ if (state.type === "user" && msg.type.startsWith("community:") && (parsed as Record<string, unknown>).schemaVersion !== BUSINESS_SCHEMA_VERSION) {
+ ws.close(1008, "Unsupported community contract")
+ return
+ }
if (state.type === "user" && await handleUserAgentInterrupt(context, state, parsed)) return
if (state.type === "user") {
const typingStart = handleClientTypingStart(context, state, parsed)
@@ -455,22 +465,29 @@ function broadcast(
return sent
}
-function broadcastCommunity(context: WsDurableContext, event: import("@alook/shared").CommunityWsEvent, targetUserId: string, sourceContract: CommunityContract = 2) {
+function broadcastCommunity(context: WsDurableContext, event: import("@alook/shared").CommunityWsEvent, targetUserId: string, sourceContract: CommunityContract = BUSINESS_SCHEMA_VERSION) {
+ const encoded = encodeCommunityBrowserEvent(event, sourceContract)
+ if (!encoded.ok) return 0
let sent = 0
for (const ws of context.ctx.getWebSockets()) {
const state = ws.deserializeAttachment() as ConnectionState
if (state?.type !== "user" || !state.authenticated || state.userId !== targetUserId) continue
- const contract = state.communityContract ?? 1
- if (contract !== 1 && contract !== 2 && contract !== 3) continue
- const projected = projectCommunityEventForContract(event, contract, sourceContract)
- if (!projected) continue
- const encoded = encodeCommunityBrowserEvent(projected, contract)
- if (!encoded.ok) continue
+ if (!isCurrentBusinessSocket(ws, state)) continue
try { ws.send(encoded.body); sent++ } catch { }
}
return sent
}
+function isCurrentBusinessSocket(ws: WebSocket, state: Extract<ConnectionState, { type: "user" }>): boolean {
+ if (state.communityContract === BUSINESS_SCHEMA_VERSION) return true
+ ws.serializeAttachment({ ...state, authenticated: false })
+ try {
+ ws.send(JSON.stringify({ type: "auth.error", error: "Unsupported community contract", communityContract: BUSINESS_SCHEMA_VERSION }))
+ ws.close(1008, "Unsupported community contract")
+ } catch { }
+ return false
+}
+
type ValidCommunityBundle = Extract<
Awaited<ReturnType<typeof readCommunityBrowserEventBundleRequest>>,
{ ok: true }
@@ -529,10 +546,9 @@ async function deliverCommunityBundle(
bundle: ValidCommunityBundle,
targetUserId: string,
): Promise<Response> {
- const formats = await Promise.all(([1, 2, 3] as const).map((contract) => encodeCommunityBrowserEventBatchForContract({
- operationId: bundle.operationId, prepared: bundle.prepared, contract,
- })))
- const encodedBatch = formats[bundle.prepared.contract === 3 ? 2 : 1]!
+ const encodedBatch = await encodeCommunityBrowserEventBatchForContract({
+ operationId: bundle.operationId, prepared: bundle.prepared, contract: BUSINESS_SCHEMA_VERSION,
+ })
const targetSockets: Array<{
ws: WebSocket
state: Extract<ConnectionState, { type: "user" }>
@@ -546,14 +562,12 @@ async function deliverCommunityBundle(
}
continue
}
- targetSockets.push({ ws, state })
+ if (isCurrentBusinessSocket(ws, state)) targetSockets.push({ ws, state })
}
- const plans: DeliveryPlan[] = targetSockets.map(({ ws, state }, socketIndex) => {
- const contract = state.communityContract ?? 1
- const encoded = contract === 1 || contract === 2 || contract === 3 ? formats[contract - 1] : undefined
- return { socketIndex, ws, state, frames: encoded?.ok ? [encoded.body] : [], progress: null }
- })
+ const plans: DeliveryPlan[] = targetSockets.map(({ ws, state }, socketIndex) => ({
+ socketIndex, ws, state, frames: encodedBatch.ok ? [encodedBatch.body] : [], progress: null,
+ }))
if (!encodedBatch.ok) {
context.log.error("community_delivery_batch_encoder_invariant_failed", {
diff --git a/tests/utils/src/auth.test.ts b/tests/utils/src/auth.test.ts
index 34f1d0ea6..0e8c6344f 100644
--- a/tests/utils/src/auth.test.ts
+++ b/tests/utils/src/auth.test.ts
@@ -27,3 +27,28 @@ describe("signIn", () => {
.rejects.toThrow("no session cookie")
})
})
+
+describe("current human community session requests", () => {
+ it.each(["/api/community/users/me/profile", "/api/community/channels/current/messages"])("qualifies JSON session %s without changing caller headers", async path => {
+ const { sessionRequest } = await import("./auth")
+ const { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION } = await import("@alook/shared")
+ const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({}))
+ await sessionRequest(path, "session=unit", { headers: [["X-Caller", "kept"]] })
+ const headers = new Headers(fetch.mock.calls[0]![1]!.headers)
+ expect(headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(COMMUNITY_CONTRACT_VERSION))
+ expect(headers.get("X-Caller")).toBe("kept")
+ expect(headers.get("Cookie")).toBe("session=unit")
+ })
+ it("preserves explicit negative versions and independent credential wire protocols", async () => {
+ const { sessionRequest, tokenRequest } = await import("./auth")
+ const { COMMUNITY_CONTRACT_HEADER } = await import("@alook/shared")
+ const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({}))
+ await sessionRequest("/api/community/users/me/profile", "session=unit", { headers: { [COMMUNITY_CONTRACT_HEADER]: "wrong" } })
+ await sessionRequest("/api/auth/device/approve", "session=unit")
+ await tokenRequest("/api/daemon/status", "unit-credential")
+ expect(new Headers(fetch.mock.calls[0]![1]!.headers).get(COMMUNITY_CONTRACT_HEADER)).toBe("wrong")
+ expect(new Headers(fetch.mock.calls[1]![1]!.headers).has(COMMUNITY_CONTRACT_HEADER)).toBe(false)
+ expect(new Headers(fetch.mock.calls[2]![1]!.headers).has(COMMUNITY_CONTRACT_HEADER)).toBe(false)
+ expect(new Headers(fetch.mock.calls[2]![1]!.headers).get("Authorization")).toBe("Bearer unit-credential")
+ })
+})
diff --git a/tests/utils/src/auth.ts b/tests/utils/src/auth.ts
index 95a756ec9..d453f2a62 100644
--- a/tests/utils/src/auth.ts
+++ b/tests/utils/src/auth.ts
@@ -1,4 +1,4 @@
-import { DEV_WEB_URL } from "@alook/shared"
+import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, DEV_WEB_URL } from "@alook/shared"
import { fetchWithRetry } from "./fetch"
const APP_URL = process.env.APP_URL ?? DEV_WEB_URL
@@ -40,13 +40,10 @@ export async function sessionRequest(
cookie: string,
opts: RequestInit = {},
): Promise<Response> {
- return fetchWithRetry(`${APP_URL}${path}`, {
- ...opts,
- headers: {
- ...(opts.headers ?? {}),
- Cookie: cookie,
- },
- })
+ const headers = new Headers(opts.headers)
+ headers.set("Cookie", cookie)
+ if (path.startsWith("/api/community/") && !headers.has(COMMUNITY_CONTRACT_HEADER)) headers.set(COMMUNITY_CONTRACT_HEADER, String(COMMUNITY_CONTRACT_VERSION))
+ return fetchWithRetry(`${APP_URL}${path}`, { ...opts, headers })
}
export async function tokenRequest(