Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): message-list anchor pagination + DM read-state + persistence + hardening (#348)
Generf909c7bc7d28
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b4a7b8ffd..d3e6ddb71 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -321,9 +321,15 @@ importers:'@streamdown/mermaid':specifier: ^1.0.2version: 1.0.2([email protected])+ '@tanstack/query-async-storage-persister':+ specifier: ^5.101.2+ version: 5.101.2'@tanstack/react-query':specifier: ^5.101.2version: 5.101.2([email protected])+ '@tanstack/react-query-persist-client':+ specifier: ^5.101.2'@tanstack/react-virtual':specifier: ^3.10.9@@ -384,6 +390,9 @@ importers:idb:specifier: ^8.0.3version: 8.0.3+ idb-keyval:+ specifier: ^6.3.0+ version: 6.3.0input-otp:specifier: ^1.4.2@@ -3250,18 +3259,30 @@ packages:'@tailwindcss/[email protected]':resolution: {integrity: sha512-dNJuNbdEJT/SWRuXTYP1WSamelsz3ztkUsdtWQPjrexysrTpaEPM40P/71knXiXLYEojqPOEGitVLLpPMS5T6A==}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-jf7zvVKZ5q2j/xuhbTIBUpw5xt6cw/ioOFQquxK7fRY0AmMQP8A0JVMOgYoeQLA4PKdeT7RxsuLAF0Lft9oJ8Q==}+'@tanstack/[email protected]':resolution: {integrity: sha512-hH5MLoJhF7KaIGd7q3xTXGXvslI+GYlM1Z/35aSHHWaCJWB7XvTSHYuV3eM7tw+aE0mT/xMro4M4Q9rCGHT0lw==}'@tanstack/[email protected]':resolution: {integrity: sha512-o+wHcqgN7Pp0s8v1i0UGq/ZrrEKrxdIiMQmKRdYb2w7NPtylYSJ4+wg/tIn71m9DLstwUwdEGAvROdly6HXP6w==}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-rgMsbvBVpSPDUsprC9FYxojdG0Q1LH6yq1i3DXz2aps4VEqv2l4Msj3YDqIifU3xkl/DrYe9YWntZAJLrM6xTg==}+'@tanstack/[email protected]':resolution: {integrity: sha512-eU7HctdA9gDjqoERoEdzLbw9DiqnBDfh5+Hu0u26gjqoHJezOpQAuiesDL2VvkU+2cPV76zgv0tMZsOrI4LjnQ==}peerDependencies:'@tanstack/react-query': ^5.101.2react: ^18 || ^19+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-19UpaRtf0lvB2QAJ2MoixxtGf3osMOd508g99EsttUj4+3eLs+ulnNgYjB7AkQMHrRlcbVXqpVNqWkB4a7g8Zw==}+ peerDependencies:+ '@tanstack/react-query': ^5.101.2+ react: ^18 || ^19+'@tanstack/[email protected]':resolution: {integrity: sha512-seDkr6kzGzX1okaaTtZPtgA688CDPlXUz1C6xSg0ESqn04Vuc8tlrYms1s3de+znBqhPVxFRfpAfUf+6XvfPWg==}peerDependencies:@@ -5968,6 +5989,9 @@ packages:resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-um+2dgAWmYsu615EXpWVwSmapJhON0G43t3Ka/EVaohzPQXSMqKEqeDK/oIW3Ow+BXaF2PvSc+oBTFp793A5Ow==}+resolution: {integrity: sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==}@@ -11485,16 +11509,31 @@ snapshots:postcss: 8.5.15tailwindcss: 4.3.1+ '@tanstack/[email protected]':+ dependencies:+ '@tanstack/query-core': 5.101.2+ '@tanstack/query-persist-client-core': 5.101.2+'@tanstack/[email protected]': {}'@tanstack/[email protected]': {}+ '@tanstack/[email protected]':+ dependencies:+ '@tanstack/query-core': 5.101.2+dependencies:'@tanstack/query-devtools': 5.101.2'@tanstack/react-query': 5.101.2([email protected])react: 19.2.7+ dependencies:+ '@tanstack/query-persist-client-core': 5.101.2+ '@tanstack/react-query': 5.101.2([email protected])+ react: 19.2.7+'@tanstack/[email protected]([email protected])':dependencies:'@tanstack/query-core': 5.101.2@@ -14671,6 +14710,8 @@ snapshots:dependencies:safer-buffer: 2.1.2+ [email protected]: {}+diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex fcfe133a9..c1b4529fa 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -694,6 +694,14 @@ export function parseRef(ref: ChannelRef): ParsedRef {const tail = chSeg.slice(lastHash + 1);const isBareHandle = firstHash === lastHash && /^\d{4}$/.test(tail);if (isBareHandle) return { server, channel: chSeg };+ // A non-numeric tail after the last `#` isn't a valid seq — rather+ // than throwing (which crashes every caller not wrapped in+ // try/catch), fall back to treating the whole segment as the+ // channel/handle. The resolution layer (`parseNameAndTag` in+ // `resolve-ref.ts`) still rejects the shape cleanly with a 400,+ // instead of a 500 from a raw throw.+ const tailNum = Number(tail.startsWith("#") ? tail.slice(1) : tail);+ if (!Number.isFinite(tailNum)) return { server, channel: chSeg };seq = parseSeq(tail);return { server, channel: chSeg.slice(0, lastHash), seq };}diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex 92e115043..1bbc77566 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -1,4 +1,4 @@-import { eq, and, or, isNull } from "drizzle-orm";+import { eq, and, or, isNull, inArray } from "drizzle-orm";import { communityFriendship } from "../../community-schema";import { user } from "../../schema";import type { Database } from "../../index";@@ -361,7 +361,25 @@ export async function getFriendUserIds(db: Database, userId: string): Promise<stconst selfBotIds = selfBotRows.map((r) => (r.id === userId ? r.ownerUserId : r.id)).filter((id): id is string => !!id);- return [...new Set([...friendIds, ...selfBotIds])];++ // Filter out any side of the implicit friendship whose OWNER is+ // soft-deleted. The `selfBotRows` query already skips soft-deleted+ // BOT rows via `isNull(user.deletedAt)`, but a bot's owner may be+ // soft-deleted while the bot itself lives on. Without this second+ // filter, `getPresenceAudience(botId)` would keep including the+ // tombstoned owner's id forever — every presence flip would fire a+ // DO fetch to a dead account for the life of the binding.+ const otherSideIds = selfBotIds.filter((id) => id !== userId);+ if (otherSideIds.length === 0) {+ return [...new Set([...friendIds, ...selfBotIds])];+ }+ const liveOthers = await db+ .select({ id: user.id })+ .from(user)+ .where(and(inArray(user.id, otherSideIds), isNull(user.deletedAt)));+ const liveOtherSet = new Set(liveOthers.map((r) => r.id));+ const liveSelfBotIds = selfBotIds.filter((id) => liveOtherSet.has(id));+ return [...new Set([...friendIds, ...liveSelfBotIds])];}/**diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.tsindex fcafb096e..ba70c52cf 100644--- a/src/shared/src/db/queries/community/inbox.ts+++ b/src/shared/src/db/queries/community/inbox.ts@@ -1,10 +1,12 @@-import { and, eq, isNotNull, isNull } from "drizzle-orm";+import { and, eq, isNotNull, isNull, or } from "drizzle-orm";import {communityChannel,+ communityDmConversation,communityReadState,communityServer,communityServerMember,} from "../../community-schema";+import { user } from "../../schema";import type { Database } from "../../index";export interface UnreadChannelRow {@@ -109,3 +111,106 @@ export async function listUnreadChannels(lastReadAt: r.lastReadAt,}));}++// ──────────────────────────────────────────────────────────────────────────────+// DM unreads+// ──────────────────────────────────────────────────────────────────────────────++export interface UnreadDmRow {+ dmConversationId: string;+ otherUserId: string;+ otherUserName: string;+ otherUserImage: string | null;+ lastMessageAt: string;+ lastReadAt: string | null;+}++/**+ * Mirrors `isChannelUnread` for DMs.+ *+ * - No `lastMessageAt` (empty conversation) → not unread.+ * - Has read-state row → strict `lastMessageAt > lastReadAt`. `createMessage`+ * writes both timestamps equal in the same batch for the author, so this+ * naturally excludes the author's own send (same invariant as channels).+ * - No read-state row → unread as long as there IS a message. DMs have no+ * "joinedAt" analog — the conversation only exists because one of the two+ * participants opened it, and any message means the counterparty hasn't+ * looked yet.+ */+export function isDmUnread(row: {+ lastMessageAt: string | null;+ lastReadAt: string | null;+}): boolean {+ if (!row.lastMessageAt) return false;+ if (row.lastReadAt) return row.lastMessageAt > row.lastReadAt;+ return true;+}++export async function listUnreadDms(+ db: Database,+ userId: string+): Promise<UnreadDmRow[]> {+ // Every DM the viewer participates in (user1 OR user2), joined to the+ // counterpart user row (name/avatar for rendering) and the viewer's DM+ // read-state row. Filtering happens in JS via `isDmUnread` — the shape+ // mirrors `listUnreadChannels`.+ const rows = await db+ .select({+ dmConversationId: communityDmConversation.id,+ user1Id: communityDmConversation.user1Id,+ user2Id: communityDmConversation.user2Id,+ lastMessageAt: communityDmConversation.lastMessageAt,+ lastReadAt: communityReadState.lastReadAt,+ otherUserId: user.id,+ otherUserName: user.name,+ otherUserImage: user.image,+ })+ .from(communityDmConversation)+ .innerJoin(+ user,+ // The counterpart is whichever side isn't the viewer. `or(eq(user.id,+ // user1Id), eq(user.id, user2Id))` alone would double-join; instead we+ // pick the opposite side per row via two eq'd cases that only one of+ // which is true for a given viewer.+ or(+ and(+ eq(communityDmConversation.user1Id, userId),+ eq(user.id, communityDmConversation.user2Id)+ ),+ and(+ eq(communityDmConversation.user2Id, userId),+ eq(user.id, communityDmConversation.user1Id)+ )+ )+ )+ .leftJoin(+ communityReadState,+ and(+ eq(communityReadState.dmConversationId, communityDmConversation.id),+ eq(communityReadState.userId, userId)+ )+ )+ .where(+ and(+ or(+ eq(communityDmConversation.user1Id, userId),+ eq(communityDmConversation.user2Id, userId)+ ),+ isNotNull(communityDmConversation.lastMessageAt),+ isNull(user.deletedAt)+ )+ );++ return rows+ .filter((r) =>+ isDmUnread({ lastMessageAt: r.lastMessageAt, lastReadAt: r.lastReadAt })+ )+ .map((r) => ({+ dmConversationId: r.dmConversationId,+ otherUserId: r.otherUserId,+ otherUserName: r.otherUserName,+ otherUserImage: r.otherUserImage,+ lastMessageAt: r.lastMessageAt!,+ lastReadAt: r.lastReadAt,+ }));+}diff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.tsindex 6b4a9d2bc..77715407f 100644--- a/src/shared/src/db/queries/community/invite.ts+++ b/src/shared/src/db/queries/community/invite.ts@@ -76,13 +76,11 @@ export async function useInvite(return null;}- // Atomic increment uses- await db- .update(communityServerInvite)- .set({ uses: sql`${communityServerInvite.uses} + 1` })- .where(eq(communityServerInvite.id, invite.id));-- // Insert new server member+ // Insert new server member FIRST — the `(serverId, userId)` UNIQUE+ // constraint may reject this ("already a member") or D1 may transiently+ // fail. Incrementing `uses` before the insert would burn an invite slot+ // on every rejected attempt (bots retrying a failed join can exhaust+ // `maxUses` without a single successful join).const memberRows = await db.insert(communityServerMember).values({@@ -93,6 +91,12 @@ export async function useInvite(.returning();const insertedMember = memberRows[0]!;+ // Atomic increment uses — only after the insert has committed.+ await db+ .update(communityServerInvite)+ .set({ uses: sql`${communityServerInvite.uses} + 1` })+ .where(eq(communityServerInvite.id, invite.id));+// Join the joined-user row so WS listeners can render name/avatar without// waiting for the next /members refetch.const userRows = await dbdiff --git a/src/shared/src/db/queries/community/machine.ts b/src/shared/src/db/queries/community/machine.tsindex 847c97def..dfba43f5c 100644--- a/src/shared/src/db/queries/community/machine.ts+++ b/src/shared/src/db/queries/community/machine.ts@@ -910,9 +910,21 @@ export async function isBotOnline(db: Database, botUserId: string): Promise<bool.from(communityBotBinding).innerJoin(communityMachine, eq(communityMachine.id, communityBotBinding.machineId)).innerJoin(user, eq(user.id, communityBotBinding.userId))- // Mirrors `listBotsForMachine`'s soft-delete guard: a tombstoned bot must- // never read back as online, even if its machine binding row is still live.- .where(and(eq(communityBotBinding.userId, botUserId), isNull(user.deletedAt)))+ // Mirrors `listBotsForMachine`'s guards: a tombstoned or non-bot user+ // must never read back as online even if the binding row is still live.+ // The `isBot=true` check is defense-in-depth against a data-integrity+ // slip (nanoid re-issue, migration bug) putting a human user id into+ // `communityBotBinding` — the binding rows are supposed to be+ // bot-only, and this predicate should fail-closed if that invariant+ // ever slips rather than silently misattributing machine presence to+ // a human.+ .where(+ and(+ eq(communityBotBinding.userId, botUserId),+ isNull(user.deletedAt),+ eq(user.isBot, true),+ ),+ ).limit(1);return rows.length > 0 && rows[0]!.status === "online";}diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.tsindex 6984cad8b..3e11f1ca9 100644--- a/src/shared/src/db/queries/community/message.ts+++ b/src/shared/src/db/queries/community/message.ts@@ -1,4 +1,4 @@-import { eq, and, desc, lt, or, sql, inArray } from "drizzle-orm";+import { eq, and, asc, desc, gt, lt, or, sql, inArray } from "drizzle-orm";import {communityMessage,communityChannel,@@ -76,7 +76,9 @@ export async function createMessage(// the counter has a harmless gap — no duplicate seq is ever possible since// this claim is independently atomic under D1's single-writer serialization.// Do NOT wrap these two statements in a transaction to "fix" this — D1- // doesn't support one that could express it.+ // doesn't support one that could express it. Kept outside the batch below+ // because D1 `batch()` cannot feed one statement's `.returning()` into a+ // later statement's values.const scopeKey = scopeKeyForTarget(data);const seq = await claimNextSeq(db, scopeKey);@@ -86,7 +88,7 @@ export async function createMessage(// `$defaultFn` fires a microsecond later and the timestamps diverge — the// inbox predicate `lastMessageAt > lastReadAt` would then wrongly fire for// the author's own send on a cold read.- const rows = await db+ const insertMsg = db.insert(communityMessage).values({authorId: data.authorId,@@ -102,72 +104,69 @@ export async function createMessage(}).returning();- const msg = rows[0]!;-- if (data.channelId) {- await db- .update(communityChannel)- .set({- lastMessageAt: now,- messageCount: sql`${communityChannel.messageCount} + 1`,- })- .where(eq(communityChannel.id, data.channelId));-- // Author read-watermark: advance the sender's own read-state to this- // message so `listUnreadChannels` (predicate: lastMessageAt > lastReadAt)- // never surfaces the channel the author just sent in. Keep this inline —- // future readers should see the invariant next to the `lastMessageAt`- // bump. Upsert against the `idx_read_state_user_channel` partial-unique- // index (same shape as `markReadToMessageBuilder`). `lastReadSeq` is- // extended here too (design §4) — required for wake-filter correctness:- // every author (bot or human) must have its own `lastReadSeq` stay in- // lockstep with its sends, or `enqueueBotWakes` sees a stale watermark.- await db- .insert(communityReadState)- .values({- userId: data.authorId,- channelId: data.channelId,- dmConversationId: null,- lastReadAt: now,- lastReadMessageId: msg.id,- lastReadSeq: seq,- })- .onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.channelId],- targetWhere: sql`${communityReadState.channelId} IS NOT NULL`,- set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },- setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,- });- }-- if (data.dmConversationId) {- await db- .update(communityDmConversation)- .set({ lastMessageAt: now })- .where(eq(communityDmConversation.id, data.dmConversationId));-- // Author read-watermark (DM path). Upsert against the- // `idx_read_state_user_dm` partial-unique index. Same invariant as the- // channel branch: keep the sender's watermark equal to the message they- // just sent so their inbox does not flag it as unread. `lastReadSeq`- // extended per design §4 — see the channel branch comment above.- await db- .insert(communityReadState)- .values({- userId: data.authorId,- channelId: null,- dmConversationId: data.dmConversationId,- lastReadAt: now,- lastReadMessageId: msg.id,- lastReadSeq: seq,- })- .onConflictDoUpdate({- target: [communityReadState.userId, communityReadState.dmConversationId],- targetWhere: sql`${communityReadState.dmConversationId} IS NOT NULL`,- set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },- setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,- });- }+ // Message insert + scope counter/timestamp bump commit atomically via+ // `db.batch(...)`. Table CHECK guarantees exactly one of channelId /+ // dmConversationId is set, so the branch is mutually exclusive.+ const scopeUpdate = data.channelId+ ? db+ .update(communityChannel)+ .set({+ lastMessageAt: now,+ messageCount: sql`${communityChannel.messageCount} + 1`,+ })+ .where(eq(communityChannel.id, data.channelId))+ : db+ .update(communityDmConversation)+ .set({ lastMessageAt: now })+ .where(eq(communityDmConversation.id, data.dmConversationId!));++ type InsertedMessage = Awaited<typeof insertMsg>[number];+ const results = (await db.batch([insertMsg, scopeUpdate] as any)) as any[];+ const msg = (results[0] as InsertedMessage[])[0]!;++ // Author read-watermark: advance the sender's own read-state to this+ // message so `listUnreadChannels` (predicate: lastMessageAt > lastReadAt)+ // never surfaces the channel/DM the author just sent in. Kept inline+ // (NOT folded into `markReadToMessageBuilder`, which is deliberately+ // "humans only" — see its comment) because this path must write+ // `lastReadSeq` per design §4 — every author (bot or human) must have+ // its own `lastReadSeq` stay in lockstep with its sends, or+ // `enqueueBotWakes` sees a stale watermark. Runs as a separate await+ // because it needs `msg.id` from the batch result.+ const readStateStmt = data.channelId+ ? db+ .insert(communityReadState)+ .values({+ userId: data.authorId,+ channelId: data.channelId,+ dmConversationId: null,+ lastReadAt: now,+ lastReadMessageId: msg.id,+ lastReadSeq: seq,+ })+ .onConflictDoUpdate({+ target: [communityReadState.userId, communityReadState.channelId],+ targetWhere: sql`${communityReadState.channelId} IS NOT NULL`,+ set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },+ setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,+ })+ : db+ .insert(communityReadState)+ .values({+ userId: data.authorId,+ channelId: null,+ dmConversationId: data.dmConversationId!,+ lastReadAt: now,+ lastReadMessageId: msg.id,+ lastReadSeq: seq,+ })+ .onConflictDoUpdate({+ target: [communityReadState.userId, communityReadState.dmConversationId],+ targetWhere: sql`${communityReadState.dmConversationId} IS NOT NULL`,+ set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },+ setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,+ });+ await readStateStmt;return msg;}@@ -182,6 +181,47 @@ export async function hardDeleteMessage(db: Database, messageId: string) {await db.delete(communityMessage).where(eq(communityMessage.id, messageId));}+// Shared select projection for the three list-messages paths (`listMessages`,+// `listMessagesAround`, `listMessagesSince`). Keeps their row shape identical+// so downstream mappers (`mapMessageForApi`) don't have to branch on source.+const listedMessageProjection = {+ id: communityMessage.id,+ authorId: communityMessage.authorId,+ content: communityMessage.content,+ type: communityMessage.type,+ mentionType: communityMessage.mentionType,+ replyToId: communityMessage.replyToId,+ embeds: communityMessage.embeds,+ flags: communityMessage.flags,+ createdAt: communityMessage.createdAt,+ channelId: communityMessage.channelId,+ dmConversationId: communityMessage.dmConversationId,+ authorName: user.name,+ authorEmail: user.email,+ authorImage: user.image,+} as const;++export type ListedMessageRow = {+ id: string;+ authorId: string;+ content: string;+ type: string;+ mentionType: string | null;+ replyToId: string | null;+ embeds: unknown | undefined;+ flags: number | null;+ createdAt: string;+ channelId: string | null;+ dmConversationId: string | null;+ authorName: string;+ authorEmail: string;+ authorImage: string | null;+};++function parseEmbeds(r: { id: string; embeds: string | null } & Record<string, unknown>): ListedMessageRow {+ return { ...(r as unknown as ListedMessageRow), embeds: safeParseEmbeds(r.embeds, r.id) };+}+export async function listMessages(db: Database,opts: {@@ -215,29 +255,171 @@ export async function listMessages(}const rows = await db- .select({- id: communityMessage.id,- authorId: communityMessage.authorId,- content: communityMessage.content,- type: communityMessage.type,- mentionType: communityMessage.mentionType,- replyToId: communityMessage.replyToId,- embeds: communityMessage.embeds,- flags: communityMessage.flags,- createdAt: communityMessage.createdAt,- channelId: communityMessage.channelId,- dmConversationId: communityMessage.dmConversationId,- authorName: user.name,- authorEmail: user.email,- authorImage: user.image,- })+ .select(listedMessageProjection).from(communityMessage).innerJoin(user, eq(communityMessage.authorId, user.id)).where(and(...conditions)).orderBy(desc(communityMessage.createdAt), desc(communityMessage.id)).limit(limit);- return rows.map((r) => ({ ...r, embeds: safeParseEmbeds(r.embeds, r.id) }));+ return rows.map(parseEmbeds);+}++/**+ * Windowed page centered on `anchor` — used by the client's "jump to unread"+ * and "jump to reply" flows. Returns the older half (strictly before the+ * anchor, DESC) and the newer half (INCLUSIVE of the anchor, ASC) separately+ * so the caller can encode `hasMoreOlder` / `hasMoreNewer` without re-deriving+ * boundary math. See plans/community-message-scroll-v2.md §A1.+ *+ * The two halves are fetched in parallel (`Promise.all`) — they share no state+ * beyond the anchor tuple. Each half fetches one extra row past the requested+ * window size to detect a "more available" boundary.+ */+export async function listMessagesAround(+ db: Database,+ opts: {+ channelId?: string;+ dmConversationId?: string;+ anchor: { createdAt: string; id: string };+ limit?: number;+ }+): Promise<{+ older: ListedMessageRow[];+ newer: ListedMessageRow[];+ hasMoreOlder: boolean;+ hasMoreNewer: boolean;+}> {+ const limit = opts.limit ?? DEFAULT_LIMIT;+ const olderHalf = Math.ceil(limit / 2);+ const newerHalf = Math.floor(limit / 2);++ const scopeConds: ReturnType<typeof eq>[] = [];+ if (opts.channelId) scopeConds.push(eq(communityMessage.channelId, opts.channelId));+ if (opts.dmConversationId) scopeConds.push(eq(communityMessage.dmConversationId, opts.dmConversationId));++ // Older half: strictly older than the anchor tuple, DESC. Fetch one extra+ // row to distinguish "exactly N older" from "N older with more available".+ const olderCond = or(+ lt(communityMessage.createdAt, opts.anchor.createdAt),+ and(+ eq(communityMessage.createdAt, opts.anchor.createdAt),+ lt(communityMessage.id, opts.anchor.id)+ )+ )! as ReturnType<typeof eq>;++ // Newer half INCLUDES the anchor (id >= anchor.id at the same createdAt) so+ // the returned window renders the anchor row itself.+ const newerCond = or(+ gt(communityMessage.createdAt, opts.anchor.createdAt),+ and(+ eq(communityMessage.createdAt, opts.anchor.createdAt),+ // gte via (id > anchor.id OR id = anchor.id) — no ORM `gte` combinator on+ // text; expressing it as two comparisons is the shortest Drizzle-only path.+ or(+ gt(communityMessage.id, opts.anchor.id),+ eq(communityMessage.id, opts.anchor.id)+ )!+ )+ )! as ReturnType<typeof eq>;++ const [olderRows, newerRows] = await Promise.all([+ db+ .select(listedMessageProjection)+ .from(communityMessage)+ .innerJoin(user, eq(communityMessage.authorId, user.id))+ .where(and(...scopeConds, olderCond))+ .orderBy(desc(communityMessage.createdAt), desc(communityMessage.id))+ .limit(olderHalf + 1),+ db+ .select(listedMessageProjection)+ .from(communityMessage)+ .innerJoin(user, eq(communityMessage.authorId, user.id))+ .where(and(...scopeConds, newerCond))+ // Anchor + newerHalf newer rows + 1 extra probe.+ .orderBy(asc(communityMessage.createdAt), asc(communityMessage.id))+ .limit(newerHalf + 1 + 1),+ ]);++ const hasMoreOlder = olderRows.length > olderHalf;+ const older = (hasMoreOlder ? olderRows.slice(0, olderHalf) : olderRows).map(parseEmbeds);++ // The newer window's target size is (anchor + newerHalf). Anything beyond+ // means more newer rows exist server-side.+ const newerBudget = newerHalf + 1;+ const hasMoreNewer = newerRows.length > newerBudget;+ const newer = (hasMoreNewer ? newerRows.slice(0, newerBudget) : newerRows).map(parseEmbeds);++ return { older, newer, hasMoreOlder, hasMoreNewer };+}++/**+ * Rows strictly newer than `since`, in chronological ASC order. Used by the+ * client's cache-hydration and WS-reconnect catch-up flows to top-off a stale+ * cache without re-fetching everything. See plans/community-message-scroll-v2.md §A1.+ *+ * Returns `limit + 1` rows when more exist; the caller trims to `limit` and+ * sets `hasMoreNewer`.+ */+export async function listMessagesSince(+ db: Database,+ opts: {+ channelId?: string;+ dmConversationId?: string;+ since: { createdAt: string; id: string };+ limit?: number;+ }+): Promise<ListedMessageRow[]> {+ const limit = opts.limit ?? DEFAULT_LIMIT;+ const conditions: ReturnType<typeof eq>[] = [];+ if (opts.channelId) conditions.push(eq(communityMessage.channelId, opts.channelId));+ if (opts.dmConversationId) conditions.push(eq(communityMessage.dmConversationId, opts.dmConversationId));++ conditions.push(+ or(+ gt(communityMessage.createdAt, opts.since.createdAt),+ and(+ eq(communityMessage.createdAt, opts.since.createdAt),+ gt(communityMessage.id, opts.since.id)+ )+ )! as ReturnType<typeof eq>+ );++ const rows = await db+ .select(listedMessageProjection)+ .from(communityMessage)+ .innerJoin(user, eq(communityMessage.authorId, user.id))+ .where(and(...conditions))+ .orderBy(asc(communityMessage.createdAt), asc(communityMessage.id))+ .limit(limit + 1);++ return rows.map(parseEmbeds);+}++/**+ * The largest `seq` value in a channel or DM scope, or `0` for an empty+ * scope. Consumed by the message-list envelope so the client can compute+ * `↓ N` (unread count vs. `latestSeq`) and drive `?since` catch-up without a+ * second round-trip. See plans/community-message-scroll-v2.md §A1.+ */+export async function getLatestMessageSeq(+ db: Database,+ target: { channelId: string } | { dmConversationId: string }+): Promise<number> {+ const cond =+ "channelId" in target+ ? eq(communityMessage.channelId, target.channelId)+ : eq(communityMessage.dmConversationId, target.dmConversationId);++ // `MAX()` returns NULL when the scope is empty; coalesce to 0 to keep the+ // shape of `latestSeq` scalar rather than optional. No ORM aggregator for+ // MAX in Drizzle — same `sql\`MAX(...)\`` idiom as `getLatestMessagesByChannelIds`.+ const rows = await db+ .select({ maxSeq: sql<number | null>`MAX(${communityMessage.seq})` })+ .from(communityMessage)+ .where(cond);++ return rows[0]?.maxSeq ?? 0;}/**diff --git a/src/shared/src/db/queries/user.ts b/src/shared/src/db/queries/user.tsindex 796d2e2eb..b7ada2b14 100644--- a/src/shared/src/db/queries/user.ts+++ b/src/shared/src/db/queries/user.ts@@ -1,4 +1,4 @@-import { eq, inArray, like, sql, and, ne, isNull } from "drizzle-orm";+import { eq, inArray, sql, and, ne, isNull } from "drizzle-orm";import { nanoid } from "nanoid";import { user } from "../schema";import type { Database } from "../index";@@ -149,10 +149,11 @@ export async function getUserByNameCaseInsensitive(db: Database,name: string): Promise<PublicUser | null> {+ const pattern = escapeLikePattern(name);const rows = await db.select(publicUserColumns).from(user)- .where(and(like(user.name, name), isNull(user.deletedAt)));+ .where(and(sql`${user.name} LIKE ${pattern} ESCAPE '\\'`, isNull(user.deletedAt)));return (rows[0] as PublicUser | undefined) ?? null;}@@ -199,11 +200,16 @@ export async function getUserByNameAndDiscriminator(name: string,discriminator: string): Promise<PublicUser | null> {+ const pattern = escapeLikePattern(name);const rows = await db.select(publicUserColumns).from(user).where(- and(like(user.name, name), eq(user.discriminator, discriminator), isNull(user.deletedAt))+ and(+ sql`${user.name} LIKE ${pattern} ESCAPE '\\'`,+ eq(user.discriminator, discriminator),+ isNull(user.deletedAt)+ )).limit(1);return (rows[0] as PublicUser | undefined) ?? null;@@ -267,10 +273,12 @@ export async function probeAvailableDiscriminator(const existing = await getUserByNameAndDiscriminator(db, input.name, discriminator);if (!existing) return discriminator;}- // Ceiling exhausted — hand back the last candidate anyway; the partial- // unique index (not this function) is what makes a true double-collision- // impossible to persist.- return computeDiscriminator(`${input.id}:${MAX_DISCRIMINATOR_ATTEMPTS - 1}`);+ // Ceiling exhausted — hand back a salt PAST the ones the loop just+ // probed, not the last-tried value. `id:${MAX-1}` would be guaranteed+ // to collide (the loop just saw it taken); `id:${MAX}` has NOT been+ // probed, so the caller's INSERT still has a chance. The partial unique+ // index is the real backstop for a true concurrent double-collision.+ return computeDiscriminator(`${input.id}:${MAX_DISCRIMINATOR_ATTEMPTS}`);}export async function createUser(diff --git a/src/shared/test/community-cli-contract.test.ts b/src/shared/test/community-cli-contract.test.tsindex 302901b52..706abc5e0 100644--- a/src/shared/test/community-cli-contract.test.ts+++ b/src/shared/test/community-cli-contract.test.ts@@ -58,6 +58,17 @@ describe("parseRef", () => {it("throws when the ref has fewer than 2 segments", () => {expect(() => parseRef("/studio")).toThrow();});++ it('falls back to a plain-channel result for a DM ref with a non-numeric tail after "#" — does NOT throw', () => {+ // Regression guard: previously `parseRef("/.dm/foo#bar")` fell into+ // the `parseSeq(tail)` path and threw `bad seq: bar`, crashing any+ // caller not wrapped in try/catch (`mockServer.ts` in tests,+ // future callers in production). Now the whole segment is treated+ // as the channel/handle and the resolution layer+ // (`parseNameAndTag`) rejects the shape cleanly at its own boundary.+ expect(() => parseRef("/.dm/foo#bar")).not.toThrow();+ expect(parseRef("/.dm/foo#bar")).toEqual({ server: DM_SERVER, channel: "foo#bar" });+ });});describe("formatRef", () => {diff --git a/src/shared/test/community-message-createMessage.test.ts b/src/shared/test/community-message-createMessage.test.tsnew file mode 100644index 000000000..1fd4ac6eb--- /dev/null+++ b/src/shared/test/community-message-createMessage.test.ts@@ -0,0 +1,167 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { getTableName } from "drizzle-orm";+import { queries } from "../src/index";+import type { Database } from "../src/index";++/**+ * Unit tests for `createMessage` batch composition.+ *+ * `createMessage` was refactored from 4 sequential awaits to:+ * (1) claimNextSeq — separate await+ * (2) db.batch([insertMsg.returning(), scopeUpdate]) — atomic pair+ * (3) author read-state upsert — separate await (needs msg.id from step 2)+ *+ * These tests mock the Database builder chain and assert the batch's+ * contents, without needing a real D1 backend.+ */++type BuilderTag =+ | { kind: "insert-msg" }+ | { kind: "update-channel" }+ | { kind: "update-dm" }+ | { kind: "insert-readstate"; values: Record<string, unknown> };++interface MockDb {+ batchCalls: Array<BuilderTag[]>;+ awaitedStatements: BuilderTag[];+ seqReturned: number;+}++function makeMockDb(seq: number): { db: Database; state: MockDb } {+ const state: MockDb = { batchCalls: [], awaitedStatements: [], seqReturned: seq };++ // Every builder is thenable so `await` on it resolves; also tagged so+ // the batch inspector can identify it after composition.+ const makeReturningBuilder = (tag: BuilderTag, resolveValue: unknown) => {+ const b: any = { __tag: tag };+ b.values = () => b;+ b.set = () => b;+ b.where = () => b;+ b.onConflictDoUpdate = () => b;+ b.returning = () => b;+ // Awaiting the builder outside a batch resolves like a real query.+ b.then = (resolve: (v: unknown) => void) => {+ state.awaitedStatements.push(tag);+ resolve(resolveValue);+ };+ return b;+ };++ const db: any = {+ insert: (table: any) => {+ const name = getTableName(table);+ if (name.includes("read_state")) {+ // Read-state upsert captures its `values(...)` payload for assertions.+ const b: any = { __tag: { kind: "insert-readstate", values: {} } };+ b.values = (v: Record<string, unknown>) => {+ b.__tag.values = v;+ return b;+ };+ b.onConflictDoUpdate = () => b;+ b.then = (resolve: (v: unknown) => void) => {+ state.awaitedStatements.push(b.__tag);+ resolve(undefined);+ };+ return b;+ }+ // Assume message insert — resolves to a row array carrying the seq we+ // stored so callers can pick out msg.id/seq.+ const row = { id: "msg_test", seq: state.seqReturned, createdAt: "2026-01-01T00:00:00.000Z" };+ return makeReturningBuilder({ kind: "insert-msg" }, [row]);+ },+ update: (table: any) => {+ const name = getTableName(table);+ const tag: BuilderTag = name.includes("dm_conversation")+ ? { kind: "update-dm" }+ : { kind: "update-channel" };+ return makeReturningBuilder(tag, undefined);+ },+ batch: (stmts: any[]) => {+ const tags = stmts.map((s) => s.__tag as BuilderTag);+ state.batchCalls.push(tags);+ // Resolve like a real batch: first stmt's `.returning()` is the msg+ // rows array, others resolve to `undefined`.+ return Promise.resolve(+ tags.map((t) =>+ t.kind === "insert-msg"+ ? [{ id: "msg_test", seq: state.seqReturned, createdAt: "2026-01-01T00:00:00.000Z" }]+ : undefined+ )+ );+ },+ };++ // Override insert so the message-seq table returns the shape claimNextSeq expects.+ const originalInsert = db.insert.bind(db);+ db.insert = (table: any) => {+ const name = getTableName(table);+ if (name.includes("message_seq")) {+ const b: any = { __tag: { kind: "insert-seq" } };+ b.values = () => b;+ b.onConflictDoUpdate = () => b;+ b.returning = () => Promise.resolve([{ nextSeq: state.seqReturned }]);+ return b;+ }+ return originalInsert(table);+ };++ return { db: db as Database, state };+}++describe("createMessage — batch composition", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("channel send: batches (insert msg, update channel) and separately upserts author read-state with lastReadSeq", async () => {+ const { db, state } = makeMockDb(42);+ const msg = await queries.communityMessage.createMessage(db, {+ authorId: "user_1",+ content: "hello",+ channelId: "chan_1",+ });++ expect(state.batchCalls).toHaveLength(1);+ const batchTags = state.batchCalls[0]!.map((t) => t.kind);+ expect(batchTags).toEqual(["insert-msg", "update-channel"]);++ // Author read-state runs after the batch as its own await, and must+ // carry `lastReadSeq: seq` (design §4 — bot-as-author wake filter reads it).+ const readState = state.awaitedStatements.find((s) => s.kind === "insert-readstate");+ expect(readState).toBeDefined();+ const values = (readState as { kind: "insert-readstate"; values: Record<string, unknown> })+ .values;+ expect(values.lastReadSeq).toBe(42);+ expect(values.lastReadMessageId).toBe("msg_test");+ expect(values.channelId).toBe("chan_1");+ expect(values.dmConversationId).toBeNull();++ expect(msg.id).toBe("msg_test");+ expect(msg.seq).toBe(42);+ });++ it("DM send: batches (insert msg, update dmConversation) and separately upserts author read-state with lastReadSeq", async () => {+ const { db, state } = makeMockDb(7);+ const msg = await queries.communityMessage.createMessage(db, {+ authorId: "user_1",+ content: "hi",+ dmConversationId: "dm_1",+ });++ expect(state.batchCalls).toHaveLength(1);+ const batchTags = state.batchCalls[0]!.map((t) => t.kind);+ expect(batchTags).toEqual(["insert-msg", "update-dm"]);++ const readState = state.awaitedStatements.find((s) => s.kind === "insert-readstate");+ expect(readState).toBeDefined();+ const values = (readState as { kind: "insert-readstate"; values: Record<string, unknown> })+ .values;+ expect(values.lastReadSeq).toBe(7);+ expect(values.lastReadMessageId).toBe("msg_test");+ expect(values.channelId).toBeNull();+ expect(values.dmConversationId).toBe("dm_1");++ expect(msg.id).toBe("msg_test");+ expect(msg.seq).toBe(7);+ });+});diff --git a/src/shared/test/queries/community-friendship.test.ts b/src/shared/test/queries/community-friendship.test.tsindex 19fe53fcd..984d8d123 100644--- a/src/shared/test/queries/community-friendship.test.ts+++ b/src/shared/test/queries/community-friendship.test.ts@@ -9,11 +9,21 @@ import { user } from "../../src/db/schema";* `.from(table)` to its own canned rows so the two queries don't bleed into* each other.*/-function createDb(opts: { friendshipRows?: unknown[]; selfBotRows?: unknown[] } = {}) {+function createDb(opts: {+ friendshipRows?: unknown[];+ selfBotRows?: unknown[];+ /** Live-owner filter query: which of the resolved "other-side" ids+ * survive the `isNull(user.deletedAt)` guard. If omitted, defaults+ * to "all ids returned by the selfBot query are live" (i.e., the+ * filter is a no-op — historical behavior). */+ liveOtherIds?: string[];+} = {}) {const friendshipRows = opts.friendshipRows ?? [];const selfBotRows = opts.selfBotRows ?? [];+ const liveOtherIds = opts.liveOtherIds;const selectCalls: unknown[] = [];const whereCalls: unknown[] = [];+ let userSelectCount = 0;const db: any = {select: vi.fn((cols: unknown) => {selectCalls.push(cols);@@ -21,7 +31,21 @@ function createDb(opts: { friendshipRows?: unknown[]; selfBotRows?: unknown[] }chain.from = vi.fn((table: unknown) => {chain.where = vi.fn((cond: unknown) => {whereCalls.push(cond);- return Promise.resolve(table === user ? selfBotRows : friendshipRows);+ if (table !== user) return Promise.resolve(friendshipRows);+ // Two possible `user`-table queries:+ // 1. selfBotRows (isBot=true, either self or owner match)+ // 2. live-owner filter (inArray + isNull(deletedAt))+ // They fire in that order.+ userSelectCount += 1;+ if (userSelectCount === 1) return Promise.resolve(selfBotRows);+ // Live-owner filter — default is "all live" (return each other-side id).+ if (liveOtherIds === undefined) {+ const allOtherIds = (selfBotRows as Array<{ id: string; ownerUserId: string | null }>)+ .flatMap((r) => [r.id, r.ownerUserId])+ .filter((id): id is string => !!id);+ return Promise.resolve(allOtherIds.map((id) => ({ id })));+ }+ return Promise.resolve(liveOtherIds.map((id) => ({ id })));});return chain;});@@ -63,13 +87,36 @@ describe("getFriendUserIds", () => {expect(result).toEqual([]);});- it("issues exactly one `where` per sub-query (real friendships + self-bot), no extra unfiltered fetch", async () => {+ it("issues exactly one `where` per sub-query (real friendships + self-bot), no extra unfiltered fetch — no self-bot pair means no 3rd query", async () => {const db = createDb();await q.getFriendUserIds(db, "u_me");expect(db.__whereCalls).toHaveLength(2);expect(db.select).toHaveBeenCalledTimes(2);});+ it("adds a THIRD query (live-owner filter) when a self-bot pair exists — needed to filter tombstoned owners", async () => {+ const db = createDb({ selfBotRows: [{ id: "bot-1", ownerUserId: "owner-1" }] });+ await q.getFriendUserIds(db, "bot-1");+ expect(db.__whereCalls).toHaveLength(3);+ expect(db.select).toHaveBeenCalledTimes(3);+ });++ it("filters out a soft-deleted OWNER from the returned audience (regression guard)", async () => {+ // Bot binding still points at a live bot row; the owner has been+ // soft-deleted. The bot query above (`selfBotRows`) filters+ // `isNull(user.deletedAt)` on the BOT row only. Without the added+ // live-owner filter, the tombstoned owner id stays in the returned+ // audience forever, and every presence flip fires a DO fetch to a+ // dead account.+ const db = createDb({+ selfBotRows: [{ id: "bot-1", ownerUserId: "owner-1" }],+ liveOtherIds: [], // owner-1 does NOT come back from the live filter+ });+ const result = await q.getFriendUserIds(db, "bot-1");+ expect(result).not.toContain("owner-1");+ expect(result).toEqual([]);+ });+// Owner↔own-bot implicit friendship — see `areFriends`/`listFriends`: no// real `communityFriendship` row exists for the pair, but `getFriendUserIds`// must surface it too, since its only two real callers (WS presencediff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.tsindex 1ad344d3b..fd5a63bf7 100644--- a/src/shared/test/queries/community-inbox.test.ts+++ b/src/shared/test/queries/community-inbox.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, vi } from "vitest";import * as inboxQueries from "../../src/db/queries/community/inbox";-import { isChannelUnread } from "../../src/db/queries/community/inbox";+import { isChannelUnread, isDmUnread } from "../../src/db/queries/community/inbox";// These tests pin the shape of the public API; SQL behavior is covered by// integration runs against D1. The fact that this file imports cleanly@@ -13,6 +13,12 @@ describe("community/inbox exports", () => {it("exports isChannelUnread", () => {expect(typeof inboxQueries.isChannelUnread).toBe("function");});+ it("exports listUnreadDms", () => {+ expect(typeof inboxQueries.listUnreadDms).toBe("function");+ });+ it("exports isDmUnread", () => {+ expect(typeof inboxQueries.isDmUnread).toBe("function");+ });});describe("isChannelUnread — two-branch predicate", () => {@@ -229,3 +235,126 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {expect(result).toEqual([]);});});++describe("isDmUnread — predicate", () => {+ it("no lastMessageAt → false (empty conversation)", () => {+ expect(isDmUnread({ lastMessageAt: null, lastReadAt: null })).toBe(false);+ });++ it("no read-state, has message → true (counterparty never opened)", () => {+ expect(+ isDmUnread({ lastMessageAt: "2026-07-06T00:00:00.000Z", lastReadAt: null })+ ).toBe(true);+ });++ it("lastMessageAt === lastReadAt → false (author's own send)", () => {+ const t = "2026-07-06T00:00:00.000Z";+ expect(isDmUnread({ lastMessageAt: t, lastReadAt: t })).toBe(false);+ });++ it("lastMessageAt > lastReadAt → true", () => {+ expect(+ isDmUnread({+ lastMessageAt: "2026-07-06T00:00:05.000Z",+ lastReadAt: "2026-07-06T00:00:00.000Z",+ })+ ).toBe(true);+ });++ it("lastMessageAt < lastReadAt → false", () => {+ expect(+ isDmUnread({+ lastMessageAt: "2026-07-06T00:00:00.000Z",+ lastReadAt: "2026-07-06T00:00:05.000Z",+ })+ ).toBe(false);+ });+});++describe("listUnreadDms — read-watermark behaviour", () => {+ function createUnreadDmRowMock(rows: any[]) {+ // select → from → innerJoin → leftJoin → where+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.leftJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve(rows));+ return chain;+ }++ it("returns DMs where lastMessageAt > lastReadAt", async () => {+ const db = createUnreadDmRowMock([+ {+ dmConversationId: "dm_1",+ user1Id: "u_viewer",+ user2Id: "u_alice",+ lastMessageAt: "2026-07-06T00:00:05.000Z",+ lastReadAt: "2026-07-06T00:00:00.000Z",+ otherUserId: "u_alice",+ otherUserName: "Alice",+ otherUserImage: null,+ },+ ]);+ const result = await inboxQueries.listUnreadDms(db, "u_viewer");+ expect(result).toHaveLength(1);+ expect(result[0]!.dmConversationId).toBe("dm_1");+ expect(result[0]!.otherUserId).toBe("u_alice");+ });++ it("filters out DMs where author's watermark equals lastMessageAt", async () => {+ const ts = "2026-07-06T00:00:00.000Z";+ const db = createUnreadDmRowMock([+ {+ dmConversationId: "dm_1",+ user1Id: "u_viewer",+ user2Id: "u_alice",+ lastMessageAt: ts,+ lastReadAt: ts, // viewer sent last, watermark aligned+ otherUserId: "u_alice",+ otherUserName: "Alice",+ otherUserImage: null,+ },+ ]);+ const result = await inboxQueries.listUnreadDms(db, "u_viewer");+ expect(result).toEqual([]);+ });++ it("returns DM the viewer has never opened (lastReadAt null, lastMessageAt set)", async () => {+ const db = createUnreadDmRowMock([+ {+ dmConversationId: "dm_1",+ user1Id: "u_alice",+ user2Id: "u_viewer",+ lastMessageAt: "2026-07-06T00:00:00.000Z",+ lastReadAt: null,+ otherUserId: "u_alice",+ otherUserName: "Alice",+ otherUserImage: "https://cdn/a.png",+ },+ ]);+ const result = await inboxQueries.listUnreadDms(db, "u_viewer");+ expect(result).toHaveLength(1);+ expect(result[0]!.otherUserImage).toBe("https://cdn/a.png");+ });++ it("skips empty conversations (lastMessageAt null)", async () => {+ // The WHERE clause filters this on the DB side (`isNotNull(lastMessageAt)`),+ // but the JS predicate is defensive — pinning both layers together lets us+ // catch a regression where either drops the guard.+ const db = createUnreadDmRowMock([+ {+ dmConversationId: "dm_1",+ user1Id: "u_viewer",+ user2Id: "u_alice",+ lastMessageAt: null,+ lastReadAt: null,+ otherUserId: "u_alice",+ otherUserName: "Alice",+ otherUserImage: null,+ },+ ]);+ const result = await inboxQueries.listUnreadDms(db, "u_viewer");+ expect(result).toEqual([]);+ });+});diff --git a/src/shared/test/queries/community-invite.test.ts b/src/shared/test/queries/community-invite.test.tsnew file mode 100644index 000000000..b4337ec59--- /dev/null+++ b/src/shared/test/queries/community-invite.test.ts@@ -0,0 +1,119 @@+import { describe, it, expect, vi } from "vitest";+import * as invite from "../../src/db/queries/community/invite";++/**+ * Build a mock db chain that records the order of high-level operations+ * (`select`, `update`, `insert`) into `ops`. Each terminal method+ * (`.where(...)` on selects, `.returning()` on updates/inserts) resolves+ * with the next queued row set from `rowsQueue`.+ */+function createOrderTrackingDb(rowsQueue: any[][]) {+ const ops: string[] = [];+ const chain: any = {};+ const takeRows = () => Promise.resolve(rowsQueue.shift() ?? []);++ chain.select = vi.fn(() => {+ ops.push("select");+ return chain;+ });+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => takeRows());+ chain.limit = vi.fn(() => takeRows());++ chain.insert = vi.fn(() => {+ ops.push("insert");+ return chain;+ });+ chain.values = vi.fn(() => chain);+ chain.returning = vi.fn(() => takeRows());++ chain.update = vi.fn(() => {+ ops.push("update");+ return chain;+ });+ chain.set = vi.fn(() => chain);++ // For update() the terminal method is `.where(...)` — Drizzle's update+ // builder awaits at `.where()`. Handle both shapes by returning a+ // then-able chain that also is awaitable.+ return { chain, ops };+}++describe("useInvite — counter does not increment until member insert succeeds", () => {+ it("runs member INSERT before invite UPDATE (uses ← uses+1)", async () => {+ // Sequence of `.where()`/`.returning()` results, in call order:+ // 1. select invite by token → the invite row+ // 2. insert communityServerMember → returning the inserted row+ // 3. update communityServerInvite (increment uses) — resolves as+ // Drizzle's update-chain terminal+ // 4. select user (hydration) → user row+ const inviteRow = {+ id: "inv_1",+ token: "tok",+ serverId: "srv_1",+ maxUses: null,+ uses: 0,+ expiresAt: null,+ };+ const memberRow = { id: "mem_1", serverId: "srv_1", userId: "u_1", role: "member" };+ const userRow = { name: "Alice", image: null, discriminator: "0001" };++ const { chain, ops } = createOrderTrackingDb([+ [inviteRow],+ [memberRow],+ [], // update .where(...) result — no rows returned needed+ [userRow],+ ]);++ const result = await invite.useInvite(chain, "tok", "u_1");+ expect(result).not.toBeNull();+ // The load-bearing ordering assertion: insert must come before update.+ const insertIdx = ops.indexOf("insert");+ const updateIdx = ops.indexOf("update");+ expect(insertIdx).toBeGreaterThanOrEqual(0);+ expect(updateIdx).toBeGreaterThan(insertIdx);+ });++ it("does NOT run the invite UPDATE if the member INSERT throws (UNIQUE 'already a member')", async () => {+ const inviteRow = {+ id: "inv_1",+ token: "tok",+ serverId: "srv_1",+ maxUses: 3,+ uses: 0,+ expiresAt: null,+ };++ const ops: string[] = [];+ const chain: any = {};+ const rowsQueue: any[][] = [[inviteRow]];+ chain.select = vi.fn(() => {+ ops.push("select");+ return chain;+ });+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve(rowsQueue.shift() ?? []));+ chain.limit = vi.fn(() => Promise.resolve(rowsQueue.shift() ?? []));+ chain.insert = vi.fn(() => {+ ops.push("insert");+ return chain;+ });+ chain.values = vi.fn(() => chain);+ chain.returning = vi.fn(() =>+ Promise.reject(+ Object.assign(new Error("UNIQUE constraint failed"), { code: "SQLITE_CONSTRAINT_UNIQUE" }),+ ),+ );+ chain.update = vi.fn(() => {+ ops.push("update");+ return chain;+ });+ chain.set = vi.fn(() => chain);++ await expect(invite.useInvite(chain, "tok", "u_dup")).rejects.toThrow(/UNIQUE/);+ expect(ops).toContain("insert");+ // The critical invariant: no UPDATE happened, so `uses` was not+ // incremented on the failed join attempt.+ expect(ops).not.toContain("update");+ });+});diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.tsindex 26823cc3b..343ac6091 100644--- a/src/shared/test/queries/community-machine.test.ts+++ b/src/shared/test/queries/community-machine.test.ts@@ -249,6 +249,31 @@ describe("isBotOnline", () => {await q.isBotOnline(chain, "bot_1");expect(chain.innerJoin).toHaveBeenCalledTimes(2);});++ it("filters on `user.isBot` in the WHERE — defense-in-depth against a human user id sneaking into `communityBotBinding`", async () => {+ // Walk the where-condition graph looking for a drizzle column whose+ // name is `isBot`. Uses the same seen-set traversal+ // `user.test.ts::conditionReferencesColumn` uses.+ function referencesColumn(node: unknown, columnName: string, seen = new Set<unknown>()): boolean {+ if (node === null || typeof node !== "object") return false;+ if (seen.has(node)) return false;+ seen.add(node);+ if ((node as { name?: unknown }).name === columnName) return true;+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {+ if (key === "table") continue;+ if (Array.isArray(value)) {+ if (value.some((v) => referencesColumn(v, columnName, seen))) return true;+ } else if (referencesColumn(value, columnName, seen)) {+ return true;+ }+ }+ return false;+ }+ const chain = makeJoinChain([{ status: "online" }]);+ await q.isBotOnline(chain, "bot_1");+ expect(referencesColumn(chain.where.mock.calls[0][0], "isBot")).toBe(true);+ expect(referencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);+ });});describe("findActiveToken", () => {diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.tsindex a601526e2..b086f1d33 100644--- a/src/shared/test/queries/community-message.test.ts+++ b/src/shared/test/queries/community-message.test.ts@@ -222,6 +222,11 @@ function createCreateMessageDbMock(opts?: { messageId?: string }) {}),};}),+ // `createMessage` now composes (insert msg, update scope) into a single+ // `db.batch(...)` for atomicity. The mock's `.returning()` / `.where()`+ // above already resolve to Promises, so we just await each one and+ // collect the per-statement result.+ batch: vi.fn(async (stmts: unknown[]) => Promise.all(stmts as Promise<unknown>[])),__inserts: inserts,__updates: updates,};@@ -569,6 +574,201 @@ describe("getLatestMessage", () => {});});+// ── listMessagesAround / listMessagesSince / getLatestMessageSeq ─────────+//+// New envelope-critical queries for the anchor-scroll refactor+// (plans/community-message-scroll-v2.md §A1). The three feed the message-list+// route's three URL modes: `?anchor`, `?since`, and the always-present+// `latestSeq` field.++/**+ * Terminal-limit mock that returns different rowsets for successive `.limit()`+ * calls. Needed because `listMessagesAround` issues two queries in parallel+ * (older + newer halves) — the caller has to look at both to compute+ * `hasMoreOlder`/`hasMoreNewer`.+ */+function createDualLimitMock(sequences: any[][]) {+ let idx = 0;+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.innerJoin = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ chain.orderBy = vi.fn(() => chain);+ chain.limit = vi.fn(() => Promise.resolve(sequences[idx++] ?? []));+ return chain;+}++function listedRow(id: string, createdAt: string) {+ return {+ id,+ authorId: `u_${id}`,+ content: id,+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ flags: 0,+ createdAt,+ channelId: "c_1",+ dmConversationId: null,+ authorName: `User ${id}`,+ authorEmail: `${id}@x.com`,+ authorImage: null,+ };+}++describe("listMessagesAround", () => {+ it("splits limit in half, fetches one extra probe on each side, and reports no `hasMore` when the probe rows don't come back", async () => {+ // limit=6 → olderHalf=3, newerBudget=4 (3 newer + 1 anchor). Probes:+ // older `.limit(4)`, newer `.limit(5)`. DB returns exactly the budget.+ const older = [+ listedRow("m_o3", "2026-01-01T00:00:03.000Z"),+ listedRow("m_o2", "2026-01-01T00:00:02.000Z"),+ listedRow("m_o1", "2026-01-01T00:00:01.000Z"),+ ];+ const newer = [+ listedRow("m_anchor", "2026-01-01T00:00:04.000Z"),+ listedRow("m_n1", "2026-01-01T00:00:05.000Z"),+ listedRow("m_n2", "2026-01-01T00:00:06.000Z"),+ listedRow("m_n3", "2026-01-01T00:00:07.000Z"),+ ];+ const db = createDualLimitMock([older, newer]);+ const result = await messageQueries.listMessagesAround(db, {+ channelId: "c_1",+ anchor: { createdAt: "2026-01-01T00:00:04.000Z", id: "m_anchor" },+ limit: 6,+ });+ expect(db.limit).toHaveBeenNthCalledWith(1, 4); // older half + probe+ expect(db.limit).toHaveBeenNthCalledWith(2, 5); // newer budget + probe+ expect(result.hasMoreOlder).toBe(false);+ expect(result.hasMoreNewer).toBe(false);+ expect(result.older.map((r: { id: string }) => r.id)).toEqual(["m_o3", "m_o2", "m_o1"]);+ expect(result.newer.map((r: { id: string }) => r.id)).toEqual(["m_anchor", "m_n1", "m_n2", "m_n3"]);+ });++ it("detects a full older side by seeing the probe row and trims it off", async () => {+ // olderHalf=3, DB returns 4 (probe fired) → hasMoreOlder true, only 3 rows returned.+ const older = [+ listedRow("m_o4", "2026-01-01T00:00:04.000Z"),+ listedRow("m_o3", "2026-01-01T00:00:03.000Z"),+ listedRow("m_o2", "2026-01-01T00:00:02.000Z"),+ listedRow("m_o1", "2026-01-01T00:00:01.000Z"),+ ];+ const newer = [listedRow("m_anchor", "2026-01-01T00:00:05.000Z")];+ const db = createDualLimitMock([older, newer]);+ const result = await messageQueries.listMessagesAround(db, {+ channelId: "c_1",+ anchor: { createdAt: "2026-01-01T00:00:05.000Z", id: "m_anchor" },+ limit: 6,+ });+ expect(result.hasMoreOlder).toBe(true);+ expect(result.hasMoreNewer).toBe(false);+ expect(result.older).toHaveLength(3);+ });++ it("returns an empty older side (with hasMoreOlder=false) when the anchor is at the head", async () => {+ // Anchor is the very oldest — no older rows at all.+ const older: any[] = [];+ const newer = [+ listedRow("m_anchor", "2026-01-01T00:00:01.000Z"),+ listedRow("m_n1", "2026-01-01T00:00:02.000Z"),+ listedRow("m_n2", "2026-01-01T00:00:03.000Z"),+ ];+ const db = createDualLimitMock([older, newer]);+ const result = await messageQueries.listMessagesAround(db, {+ channelId: "c_1",+ anchor: { createdAt: "2026-01-01T00:00:01.000Z", id: "m_anchor" },+ limit: 6,+ });+ expect(result.hasMoreOlder).toBe(false);+ expect(result.older).toEqual([]);+ expect(result.newer[0]?.id).toBe("m_anchor");+ });++ it("accepts dmConversationId scope", async () => {+ const db = createDualLimitMock([[], [listedRow("m_anchor", "2026-01-01T00:00:01.000Z")]]);+ const result = await messageQueries.listMessagesAround(db, {+ dmConversationId: "dm_1",+ anchor: { createdAt: "2026-01-01T00:00:01.000Z", id: "m_anchor" },+ limit: 6,+ });+ expect(result.newer[0]?.id).toBe("m_anchor");+ });+});++describe("listMessagesSince", () => {+ it("returns rows in ASC order, trimmed to `limit`, with the probe row driving hasMore in the caller", async () => {+ // Query fetches `limit + 1` — caller (route) trims. The query itself+ // returns whatever the DB gives; test that the passed limit is `limit+1`.+ const rows = [+ listedRow("m_1", "2026-01-01T00:00:01.000Z"),+ listedRow("m_2", "2026-01-01T00:00:02.000Z"),+ listedRow("m_3", "2026-01-01T00:00:03.000Z"),+ ];+ const db = createDualLimitMock([rows]);+ const result = await messageQueries.listMessagesSince(db, {+ channelId: "c_1",+ since: { createdAt: "2026-01-01T00:00:00.000Z", id: "m_0" },+ limit: 50,+ });+ expect(db.limit).toHaveBeenCalledWith(51);+ expect(result.map((r: { id: string }) => r.id)).toEqual(["m_1", "m_2", "m_3"]);+ });++ it("returns empty when no rows are newer than `since`", async () => {+ const db = createDualLimitMock([[]]);+ const result = await messageQueries.listMessagesSince(db, {+ channelId: "c_1",+ since: { createdAt: "2026-01-01T00:00:00.000Z", id: "m_0" },+ });+ expect(result).toEqual([]);+ });++ it("accepts dmConversationId scope", async () => {+ const db = createDualLimitMock([[listedRow("m_1", "2026-01-01T00:00:01.000Z")]]);+ const result = await messageQueries.listMessagesSince(db, {+ dmConversationId: "dm_1",+ since: { createdAt: "2026-01-01T00:00:00.000Z", id: "m_0" },+ });+ expect(result).toHaveLength(1);+ });+});++describe("getLatestMessageSeq", () => {+ function createSeqMock(rows: any[]) {+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => Promise.resolve(rows));+ return chain;+ }+ it("returns 0 when the scope is empty (MAX() over 0 rows yields NULL)", async () => {+ const db = createSeqMock([{ maxSeq: null }]);+ const result = await messageQueries.getLatestMessageSeq(db, { channelId: "c_empty" });+ expect(result).toBe(0);+ });++ it("returns the MAX(seq) value for a non-empty scope", async () => {+ const db = createSeqMock([{ maxSeq: 42 }]);+ const result = await messageQueries.getLatestMessageSeq(db, { channelId: "c_1" });+ expect(result).toBe(42);+ });++ it("also accepts dmConversationId scope", async () => {+ const db = createSeqMock([{ maxSeq: 7 }]);+ const result = await messageQueries.getLatestMessageSeq(db, { dmConversationId: "dm_1" });+ expect(result).toBe(7);+ });++ it("returns 0 when the driver returns an empty rowset", async () => {+ // Defensive: some D1 aggregate paths may return `[]` rather than `[{ maxSeq: null }]`.+ const db = createSeqMock([]);+ const result = await messageQueries.getLatestMessageSeq(db, { channelId: "c_1" });+ expect(result).toBe(0);+ });+});+describe("getLatestMessagesByChannelIds", () => {function createInnerJoinMock(rows: any[]) {const chain: any = {};@@ -707,6 +907,10 @@ describe("read-state invariant property — every write path", () => {chain.where = vi.fn(() => Promise.resolve([]));return chain;}),+ // `createMessage` composes (insert msg, update scope) into a single+ // `db.batch(...)` — insert/update chains above already resolve to+ // Promises, so await each and collect per-statement results.+ batch: vi.fn(async (stmts: unknown[]) => Promise.all(stmts as Promise<unknown>[])),};return db;}diff --git a/src/shared/test/queries/user.test.ts b/src/shared/test/queries/user.test.tsindex 3a5e6cc05..ee0adf2a1 100644--- a/src/shared/test/queries/user.test.ts+++ b/src/shared/test/queries/user.test.ts@@ -49,6 +49,22 @@ function conditionReferencesColumn(node: unknown, columnName: string, seen = newreturn false;}+function conditionContainsString(node: unknown, needle: string, seen = new Set<unknown>()): boolean {+ if (typeof node === "string") return node.includes(needle);+ if (node === null || typeof node !== "object") return false;+ if (seen.has(node)) return false;+ seen.add(node);+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {+ if (key === "table") continue;+ if (Array.isArray(value)) {+ if (value.some((v) => conditionContainsString(v, needle, seen))) return true;+ } else if (conditionContainsString(value, needle, seen)) {+ return true;+ }+ }+ return false;+}+describe("user exports", () => {it("exports getUserPublic", () => { expect(typeof userQueries.getUserPublic).toBe("function"); });it("exports getUserSelf", () => { expect(typeof userQueries.getUserSelf).toBe("function"); });@@ -126,6 +142,18 @@ describe("getUserByNameAndDiscriminator", () => {await userQueries.getUserByNameAndDiscriminator(chain, "alice", "1234");expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);});++ it("escapes SQL LIKE metacharacters in name — `_` in input is a literal, not a wildcard", async () => {+ const chain = createSelectLimitMock([]);+ await userQueries.getUserByNameAndDiscriminator(chain, "A_ex", "0001");+ const where = chain.where.mock.calls[0][0];+ // Fragment must include an ESCAPE clause so the `\_` produced by+ // escapeLikePattern is honored (without it, SQLite ignores the+ // backslash and `_` remains a wildcard).+ expect(conditionContainsString(where, "ESCAPE")).toBe(true);+ // Escaped pattern (`A\_ex`) must be a parameter of the fragment.+ expect(conditionContainsString(where, "A\\_ex")).toBe(true);+ });});describe("getUserByNameCaseInsensitive", () => {@@ -146,6 +174,14 @@ describe("getUserByNameCaseInsensitive", () => {await userQueries.getUserByNameCaseInsensitive(chain, "alice");expect(conditionReferencesColumn(chain.where.mock.calls[0][0], "deletedAt")).toBe(true);});++ it("escapes SQL LIKE metacharacters in name — `%` in input is a literal, not a wildcard", async () => {+ const chain = createSelectMock([]);+ await userQueries.getUserByNameCaseInsensitive(chain, "admin%");+ const where = chain.where.mock.calls[0][0];+ expect(conditionContainsString(where, "ESCAPE")).toBe(true);+ expect(conditionContainsString(where, "admin\\%")).toBe(true);+ });});describe("searchUsersByName", () => {@@ -245,6 +281,61 @@ describe("withUniqueDiscriminator", () => {});});+describe("probeAvailableDiscriminator", () => {+ it("returns a NON-collision fallback when all salted probes come back taken", async () => {+ // Every SELECT resolves to a non-null row → the loop sees every salt+ // (`id`, `id:1`, `id:2`, `id:3`, `id:4`) taken. The final returned+ // discriminator MUST correspond to a salt the loop did NOT probe —+ // otherwise Better Auth's INSERT is guaranteed to collide the very+ // same instant.+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ // Every probe returns a "taken" row.+ chain.limit = vi.fn(() => Promise.resolve([{ id: "u_other" }]));++ const returned = await userQueries.probeAvailableDiscriminator(chain, {+ id: "u_collide",+ name: "Alice",+ });++ // Collect the salts the loop probed — computeDiscriminator("u_collide"),+ // "u_collide:1", …, "u_collide:4". The returned value must not equal+ // any of them; specifically, it should match the "one salt past the+ // ceiling" (`:5`).+ const probed = [+ computeDiscriminator("u_collide"),+ computeDiscriminator("u_collide:1"),+ computeDiscriminator("u_collide:2"),+ computeDiscriminator("u_collide:3"),+ computeDiscriminator("u_collide:4"),+ ];+ expect(probed).not.toContain(returned);+ expect(returned).toBe(computeDiscriminator("u_collide:5"));+ });++ it("returns the first free salt on the happy path", async () => {+ // First probe returns "taken", second probe returns "free" → the+ // second salt's discriminator is what the caller gets.+ const chain: any = {};+ chain.select = vi.fn(() => chain);+ chain.from = vi.fn(() => chain);+ chain.where = vi.fn(() => chain);+ let calls = 0;+ chain.limit = vi.fn(() => {+ calls += 1;+ return Promise.resolve(calls === 1 ? [{ id: "u_other" }] : []);+ });++ const returned = await userQueries.probeAvailableDiscriminator(chain, {+ id: "u_ok",+ name: "Alice",+ });+ expect(returned).toBe(computeDiscriminator("u_ok:1"));+ });+});+describe("updateUser", () => {function createUpdateMock(rows: any[]) {const chain: any = {};diff --git a/src/web/package.json b/src/web/package.jsonindex 1ec6d153a..667c656fd 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -40,7 +40,9 @@"@streamdown/cjk": "^1.0.3","@streamdown/math": "^1.0.2","@streamdown/mermaid": "^1.0.2",+ "@tanstack/query-async-storage-persister": "^5.101.2","@tanstack/react-query": "^5.101.2",+ "@tanstack/react-query-persist-client": "^5.101.2","@tanstack/react-virtual": "^3.10.9","@tiptap/extension-image": "^3.27.1","@tiptap/extension-link": "^3.27.1",@@ -61,6 +63,7 @@"emoji-mart": "^5.6.0","gsap": "^3.15.0","idb": "^8.0.3",+ "idb-keyval": "^6.3.0","input-otp": "^1.4.2","katex": "^0.17.0","lucide-react": "^1.23.0",diff --git a/src/web/src/app/api/community/agent/joinServer/route.test.ts b/src/web/src/app/api/community/agent/joinServer/route.test.tsindex ef0a04d24..b86eca01f 100644--- a/src/web/src/app/api/community/agent/joinServer/route.test.ts+++ b/src/web/src/app/api/community/agent/joinServer/route.test.ts@@ -13,6 +13,7 @@ const mockGetInviteByToken = vi.fn()const mockUseInvite = vi.fn()const mockGetServer = vi.fn()const mockFanOutToServerMembers = vi.fn()+const mockBroadcastToUserSafe = vi.fn()const mockLogAudit = vi.fn()vi.mock("@alook/shared", async () => {@@ -35,6 +36,7 @@ vi.mock("@alook/shared", async () => {vi.mock("@/lib/community/fanout", () => ({fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),}))vi.mock("@/lib/community/audit", async () => {const actual = await vi.importActual<typeof import("@/lib/community/audit")>("@/lib/community/audit")@@ -122,6 +124,14 @@ describe("POST /api/community/agent/joinServer", () => {expect.objectContaining({ serverId: "srv_1" }),{ excludeUserId: "bot_1" },)+ // The bot's owner isn't necessarily a server member, so the fan-out+ // above can't reach them. The route must ALSO notify the owner+ // directly so their bot-list / server-rail updates without a hard+ // refresh — regression guard for review finding #7.+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith(+ "owner_1",+ expect.objectContaining({ serverId: "srv_1" }),+ )expect(mockLogAudit).toHaveBeenCalledWith(expect.anything(),expect.objectContaining({diff --git a/src/web/src/app/api/community/agent/joinServer/route.ts b/src/web/src/app/api/community/agent/joinServer/route.tsindex 11c7c49d0..87ebc510e 100644--- a/src/web/src/app/api/community/agent/joinServer/route.ts+++ b/src/web/src/app/api/community/agent/joinServer/route.ts@@ -3,7 +3,7 @@ import { queries, ROLES, WS_EVENTS, isUniqueConstraintError, CommunityAgentJoinSimport type { CommunityMemberJoin } from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"-import { fanOutToServerMembers } from "@/lib/community/fanout"+import { fanOutToServerMembers, broadcastToUserSafe } from "@/lib/community/fanout"import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"/**@@ -88,6 +88,15 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {fanOutToServerMembers(result.invite.serverId, memberEvent, { excludeUserId: ctx.botUserId })+ // The bot's OWNER isn't necessarily a member of the server the bot just+ // joined, so `fanOutToServerMembers` (scoped to existing members) will+ // never reach them. Send the same event directly to the owner so their+ // bot-list / server-rail reflects the join without a hard refresh. If+ // the owner IS also a member, `patchCacheJoin` in+ // `use-server-members.ts` dedupes by userId (`total` bump is a no-op on+ // re-delivery), so double-delivery is safe.+ broadcastToUserSafe(ctx.ownerUserId, memberEvent)+const server = await queries.communityServer.getServer(db, result.invite.serverId)return NextResponse.json({ server: { id: server!.id, name: server!.name } })})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.tsindex 1a4e44ded..0c1573423 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@@ -9,6 +9,7 @@ const mockGetChannelForMember = vi.fn()const mockGetChannel = vi.fn()const mockCreateMessage = vi.fn()const mockGetMessage = vi.fn()+const mockGetMessageInScope = vi.fn()const mockGetMessagesByIdsInScope = vi.fn()const mockListMembers = vi.fn()const mockListMemberUserIds = vi.fn()@@ -16,6 +17,9 @@ const mockCreateMentions = vi.fn()const mockCreateAttachment = vi.fn()const mockListChildChannels = vi.fn()const mockListMessages = vi.fn()+const mockListMessagesAround = vi.fn()+const mockListMessagesSince = vi.fn()+const mockGetLatestMessageSeq = vi.fn()const mockListByMessageIds = vi.fn()const mockListReactionsByMessageIds = vi.fn()const mockGetUserInternal = vi.fn()@@ -43,8 +47,12 @@ vi.mock("@alook/shared", async () => {communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),getMessage: (...a: unknown[]) => mockGetMessage(...a),+ getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),listMessages: (...a: unknown[]) => mockListMessages(...a),+ listMessagesAround: (...a: unknown[]) => mockListMessagesAround(...a),+ listMessagesSince: (...a: unknown[]) => mockListMessagesSince(...a),+ getLatestMessageSeq: (...a: unknown[]) => mockGetLatestMessageSeq(...a),},communityMember: {listMembers: (...a: unknown[]) => mockListMembers(...a),@@ -306,6 +314,9 @@ describe("GET /api/community/channels/[id]/messages", () => {mockListChildChannels.mockResolvedValue([])mockListByMessageIds.mockResolvedValue([])mockListReactionsByMessageIds.mockResolvedValue([])+ // Every route branch calls `getLatestMessageSeq` — default to a small+ // sentinel so each test doesn't have to wire it individually.+ mockGetLatestMessageSeq.mockResolvedValue(0)})it("resolves reply previews via one scoped getMessagesByIdsInScope call (never per-item getMessage)", async () => {@@ -377,11 +388,10 @@ describe("GET /api/community/channels/[id]/messages", () => {expect(body.messages[0]?.authorAvatar).toBe("A")})- it("runs attachment, reaction, reply-target, and child-channel fetches in parallel", async () => {- // The 4 follow-up fetches have no cross-dependency; they must run+ it("runs attachment, reaction, reply-target, child-channel, and latest-seq fetches in parallel", async () => {+ // The 5 follow-up fetches have no cross-dependency; they must run// concurrently (Promise.all), not sequentially. We prove concurrency by- // observing the in-flight count of the mocked queries: if any two are- // running at the same time, the max concurrency is >= 2.+ // 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" },])@@ -399,17 +409,18 @@ describe("GET /api/community/channels/[id]/messages", () => {mockListReactionsByMessageIds.mockImplementation(() => tracked([]))mockGetMessagesByIdsInScope.mockImplementation(() => tracked([]))mockListChildChannels.mockImplementation(() => tracked([]))+ mockGetLatestMessageSeq.mockImplementation(() => tracked(0))const res = await GET(getReq(), ctx)expect(res.status).toBe(200)- // All 4 fetches must have been kicked off before any resolves — proving- // Promise.all, not sequential await.- expect(maxInFlight).toBe(4)+ // All 5 fetches must have been kicked off before any resolves.+ expect(maxInFlight).toBe(5)expect(mockListByMessageIds).toHaveBeenCalledTimes(1)expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)expect(mockListChildChannels).toHaveBeenCalledTimes(1)+ expect(mockGetLatestMessageSeq).toHaveBeenCalledTimes(1)})it("passes parsed embeds through to the response body verbatim", async () => {@@ -428,4 +439,99 @@ describe("GET /api/community/channels/[id]/messages", () => {expect(byId.get("m-1")?.embeds).toEqual(parsed)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.+ 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)+ expect(mockGetLatestMessageSeq).toHaveBeenCalledWith(expect.anything(), { channelId: "c1" })+ })++ describe("?anchor mode", () => {+ it("returns a centered window with the anchor row present, plus latestSeq + cursors", async () => {+ mockGetMessageInScope.mockResolvedValue({+ id: "m_anchor",+ createdAt: "2026-06-30T00:00:03.000Z",+ })+ 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" },+ ],+ 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" },+ ],+ hasMoreOlder: true,+ hasMoreNewer: false,+ })+ mockGetLatestMessageSeq.mockResolvedValue(9)++ const url = "http://localhost/api/community/channels/c1/messages?anchor=m_anchor"+ const req = new NextRequest(url, { method: "GET" })+ 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+ }+ // 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)+ // 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)+ // Scope-first resolve: anchor lookup passes the channel scope.+ expect(mockGetMessageInScope).toHaveBeenCalledWith(expect.anything(), "m_anchor", { channelId: "c1" })+ })++ it("returns 404 when the anchor is not visible in this channel", async () => {+ mockGetMessageInScope.mockResolvedValue(null)+ const req = new NextRequest("http://localhost/api/community/channels/c1/messages?anchor=m_missing", {+ method: "GET",+ })+ const res = await GET(req, ctx)+ expect(res.status).toBe(404)+ expect(mockListMessagesAround).not.toHaveBeenCalled()+ })+ })++ 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" },+ ])+ 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" },+ )+ 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+ latestSeq: number+ }+ expect(body.messages.map((m) => m.id)).toEqual(["m_1", "m_2"])+ expect(body.hasMoreNewer).toBe(false)+ expect(body.latestSeq).toBe(2)+ // Anchor-mode paths must not fire.+ expect(mockGetMessageInScope).not.toHaveBeenCalled()+ expect(mockListMessagesAround).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.tsindex f4f03cdb9..5990fce70 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@@ -3,7 +3,16 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"-import { parseCursor, parsePageSize, buildPaginatedResponse, groupAttachments, groupReactions } from "@/lib/community/messages"+import {+ parseCursor,+ parseAnchor,+ parsePageSize,+ buildPaginatedResponse,+ buildAnchorResponse,+ buildSinceResponse,+ groupAttachments,+ groupReactions,+} from "@/lib/community/messages"import { requireChannelMember } from "@/lib/community/permissions"import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage } from "@/lib/community/message-handler"@@ -18,9 +27,50 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const auth = await requireChannelMember(db, channelId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const cursor = parseCursor(req.nextUrl.searchParams.get("cursor"))- const pageSize = parsePageSize(req.nextUrl.searchParams.get("limit"))+ const params = req.nextUrl.searchParams+ const anchorId = parseAnchor(params.get("anchor"))+ const since = parseCursor(params.get("since"))+ const cursor = parseCursor(params.get("cursor"))+ const pageSize = parsePageSize(params.get("limit"))++ // Anchor branch: resolve the target message inside the channel scope first+ // (a scope-first lookup — see AGENTS.md "scope the queries before"), then+ // fetch the centered window and enrich.+ if (anchorId) {+ const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { channelId })+ if (!anchor) return writeError("anchor not found", 404)++ const around = await queries.communityMessage.listMessagesAround(db, {+ channelId,+ anchor: { createdAt: anchor.createdAt, id: anchor.id },+ limit: pageSize,+ })++ const { items, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor } = buildAnchorResponse(+ around.older,+ around.newer,+ { hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },+ )++ const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, channelId, items)+ return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })+ }++ // Since branch: strictly-newer diff for cache hydration & WS-reconnect+ // catch-up. Rows arrive ASC directly from the query; no reverse pass here.+ if (since) {+ const rows = await queries.communityMessage.listMessagesSince(db, {+ channelId,+ since,+ limit: pageSize,+ })+ const { items, hasMoreNewer, newerCursor } = buildSinceResponse(rows, pageSize)+ const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, channelId, items)+ return writeJSON({ messages, hasMoreNewer, newerCursor, latestSeq })+ }+ // Legacy branch (unchanged behavior beyond `latestSeq` addition): newest page+ // via DESC + one-extra-row probe, response items reversed to ASC.const rows = await queries.communityMessage.listMessages(db, {channelId,cursor,@@ -28,35 +78,42 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {})const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)+ const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, channelId, items.slice().reverse())+ return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })+})- // All four follow-up fetches depend only on `items` / `channelId` — no- // cross-dependency — so run them concurrently to collapse 4 sequential D1- // round-trips into one wall-clock hop.+// Enrichment shared by all three GET branches — attachments, reactions,+// reply-target previews, child-channel thread indicators, and `latestSeq`.+// `items` is expected in chronological ASC (the wire order). Kept in this+// file (not extracted) so the branching above stays a five-line switch.+async function enrichAndFinalize(+ db: ReturnType<typeof getDb>,+ userId: string,+ channelId: string,+ items: Array<{ id: string; replyToId: string | null } & Record<string, unknown>>,+): Promise<{ messages: unknown[]; latestSeq: number }> {const messageIds = items.map((m) => m.id)const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]- const [allAttachments, allReactions, replyMessages, childChannels] = await Promise.all([+ const [allAttachments, allReactions, replyMessages, childChannels, latestSeq] = await Promise.all([messageIds.length > 0? queries.communityAttachment.listByMessageIds(db, messageIds): Promise.resolve([]),messageIds.length > 0- ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, ctx.userId)+ ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId): Promise.resolve([]),replyToIds.length > 0? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId }): Promise.resolve([]),queries.communityChannel.listChildChannels(db, channelId),+ queries.communityMessage.getLatestMessageSeq(db, { channelId }),])const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, ctx.userId)+ const reactionsByMessage = groupReactions(allReactions, userId)- // Reply targets are already scoped to this channel by the query above — a- // client can't leak previews of messages from other channels/DMs just by- // referencing their id.const replyMap = new Map(replyMessages.map((m) => [m.id, m]))- // Resolve threads (child channels with parentMessageId matching these messages)const threadByMessageId = new Map(childChannels.filter((c) => c.parentMessageId)@@ -64,11 +121,10 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {)const messages = items.map((r) =>- mapMessageForApi(r, { replyMap, attachmentsByMessage, reactionsByMessage, threadByMessageId }),+ mapMessageForApi(r as never, { replyMap, attachmentsByMessage, reactionsByMessage, threadByMessageId }),)-- return writeJSON({ messages: messages.reverse(), hasMore, cursor: nextCursor })-})+ return { messages, latestSeq }+}export const POST = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.iddiff --git a/src/web/src/app/api/community/channels/[id]/read-state/route.test.ts b/src/web/src/app/api/community/channels/[id]/read-state/route.test.tsindex 4d9f27e29..e5057d207 100644--- a/src/web/src/app/api/community/channels/[id]/read-state/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/read-state/route.test.ts@@ -67,7 +67,7 @@ describe("GET /api/community/channels/[id]/read-state", () => {const res = await GET(getReq(), { params: { id: "c1" } } as any)expect(res.status).toBe(200)const body = await res.json()- expect(body).toEqual({ lastReadMessageId: null, lastReadAt: null })+ expect(body).toEqual({ lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 })// Args to getReadState should scope by (userId, channelId).expect(mockGetReadState).toHaveBeenCalledWith(expect.anything(), {userId: "u1",@@ -75,12 +75,13 @@ describe("GET /api/community/channels/[id]/read-state", () => {})})- it("returns the actual (lastReadMessageId, lastReadAt) pair when a row exists", async () => {+ it("returns the actual (lastReadMessageId, lastReadAt, lastReadSeq) tuple when a row exists", async () => {mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })mockGetReadState.mockResolvedValue({lastReadMessageId: "m_42",lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 42,})const res = await GET(getReq(), { params: { id: "c1" } } as any)@@ -89,6 +90,7 @@ describe("GET /api/community/channels/[id]/read-state", () => {expect(body).toEqual({lastReadMessageId: "m_42",lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 42,})})diff --git a/src/web/src/app/api/community/channels/[id]/read-state/route.ts b/src/web/src/app/api/community/channels/[id]/read-state/route.tsindex 0bf7f7230..75fcbf4d5 100644--- a/src/web/src/app/api/community/channels/[id]/read-state/route.ts+++ b/src/web/src/app/api/community/channels/[id]/read-state/route.ts@@ -38,5 +38,11 @@ export const GET = withAuth(async (_req: NextRequest, ctx) => {return writeJSON({lastReadMessageId: row?.lastReadMessageId ?? null,lastReadAt: row?.lastReadAt ?? null,+ // Seq is the numeric equivalent of the (createdAt, id) pointer — used+ // client-side to compute the `↓ N` unread count without walking the+ // loaded rows (`latestSeq - lastReadSeq`). Falls back to 0 when the+ // viewer has never visited: `latestSeq - 0` = all-messages-are-new,+ // matching what the divider anchor implies.+ lastReadSeq: row?.lastReadSeq ?? 0,})})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.tsindex cc8e2bdad..01d1a7354 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@@ -171,8 +171,8 @@ describe("PUT /api/community/channels/[id]/read", () => {expect(mockBatch).not.toHaveBeenCalled()})- // ── #3: PUT body carries `lastMessageId` ─────────────────────────────────- describe("PUT with { lastMessageId } body — progressive watermark", () => {+ // ── #3: PUT body carries `lastReadMessageId` ─────────────────────────────────+ describe("PUT with { lastReadMessageId } body — progressive watermark", () => {it("writes the message's createdAt/id via markReadToMessageBuilder when the message belongs to the channel", async () => {mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })@@ -182,7 +182,7 @@ describe("PUT /api/community/channels/[id]/read", () => {createdAt: "2026-07-01T12:00:00.000Z",})- const res = await PUT(putReq({ lastMessageId: "m_42" }), { params: { id: "c1" } } as any)+ const res = await PUT(putReq({ lastReadMessageId: "m_42" }), { params: { id: "c1" } } as any)expect(res.status).toBe(200)expect(mockGetMessage).toHaveBeenCalledWith(expect.anything(), "m_42")// The builder must receive the message's own timestamp + id — that's@@ -206,7 +206,7 @@ describe("PUT /api/community/channels/[id]/read", () => {createdAt: "2026-07-01T12:00:00.000Z",})- const res = await PUT(putReq({ lastMessageId: "m_42" }), { params: { id: "c1" } } as any)+ const res = await PUT(putReq({ lastReadMessageId: "m_42" }), { params: { id: "c1" } } as any)expect(res.status).toBe(400)expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()expect(mockBatch).not.toHaveBeenCalled()@@ -217,7 +217,7 @@ describe("PUT /api/community/channels/[id]/read", () => {mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })mockGetMessage.mockResolvedValue(null)- const res = await PUT(putReq({ lastMessageId: "m_ghost" }), { params: { id: "c1" } } as any)+ const res = await PUT(putReq({ lastReadMessageId: "m_ghost" }), { params: { id: "c1" } } as any)expect(res.status).toBe(404)expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()expect(mockBatch).not.toHaveBeenCalled()@@ -231,7 +231,7 @@ describe("PUT /api/community/channels/[id]/read", () => {createdAt: "2026-07-05T10:00:00.000Z",})- // Empty string body — treated as no lastMessageId.+ // Empty string body — treated as no lastReadMessageId.const res = await PUT(putReq(""), { params: { id: "c1" } } as any)expect(res.status).toBe(200)// getMessage never fetched because there's no id to check.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.tsindex ced3d81e9..638df5e39 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@@ -14,12 +14,15 @@ import { requireChannelMember } from "@/lib/community/permissions"* `lastReadMessageId = msg.id`. Empty channels are a no-op — no row* written — because the read-state invariant forbids* `lastReadMessageId = null` rows.- * - Body `{ lastMessageId }` → Slack-style progressive mark-read. Verifies- * the message exists AND belongs to this channel, then writes the- * message's `createdAt` + `id` as the new pointer. Rejects when the+ * - Body `{ lastReadMessageId }` → Slack-style progressive mark-read.+ * Verifies the message exists AND belongs to this channel, then writes+ * the message's `createdAt` + `id` as the new pointer. Rejects when the* message belongs to another channel (400) — protects against confused-* deputy watermark advances.*+ * The body key matches DM (`PUT /dm/:id/read`) and thread+ * (`PUT /threads/:id/read`) — all three routes accept `lastReadMessageId`.+ ** Mention clear still fires in one D1 batch on non-empty channels. On an* empty channel we short-circuit before writing anything — there are no* mentions to clear on a channel with no messages.@@ -40,26 +43,26 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {if (!auth.ok) return writeError(auth.error, auth.status)// Parse the body — best-effort. An empty body is legal (mass mark-read).- let lastMessageId: string | undefined+ let lastReadMessageId: string | undefinedtry {// A truly empty body throws in `req.json()`; catch and treat as `{}`.const raw = await req.text()if (raw.trim().length > 0) {- const body = JSON.parse(raw) as { lastMessageId?: unknown }- if (typeof body?.lastMessageId === "string" && body.lastMessageId.length > 0) {- lastMessageId = body.lastMessageId+ const body = JSON.parse(raw) as { lastReadMessageId?: unknown }+ if (typeof body?.lastReadMessageId === "string" && body.lastReadMessageId.length > 0) {+ lastReadMessageId = body.lastReadMessageId}}} catch {- // Malformed JSON — fall through with `lastMessageId` unset. The mass+ // Malformed JSON — fall through with `lastReadMessageId` unset. The mass// mark-read semantics are the safe fallback.}// Resolve the target message. Both branches align (lastReadAt, lastReadMessageId)// to a real message — that's the read-state invariant.let target: { id: string; createdAt: string } | null- if (lastMessageId) {- const msg = await queries.communityMessage.getMessage(db, lastMessageId)+ if (lastReadMessageId) {+ const msg = await queries.communityMessage.getMessage(db, lastReadMessageId)if (!msg) return writeError("message not found", 404)// Scope check — a message from another channel MUST NOT advance THIS// channel's watermark.diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts b/src/web/src/app/api/community/dm/[id]/messages/route.test.tsindex d5a1d784e..ffa4df0fd 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.test.ts@@ -9,8 +9,12 @@ const mockGetDM = vi.fn()const mockIsBlocked = vi.fn()const mockCreateMessage = vi.fn()const mockGetMessage = vi.fn()+const mockGetMessageInScope = vi.fn()const mockGetMessagesByIdsInScope = vi.fn()const mockListMessages = vi.fn()+const mockListMessagesAround = vi.fn()+const mockListMessagesSince = vi.fn()+const mockGetLatestMessageSeq = vi.fn()const mockListByMessageIds = vi.fn()const mockListReactionsByMessageIds = vi.fn()const mockListMembers = vi.fn()@@ -42,8 +46,12 @@ vi.mock("@alook/shared", async () => {communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),getMessage: (...a: unknown[]) => mockGetMessage(...a),+ getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),listMessages: (...a: unknown[]) => mockListMessages(...a),+ listMessagesAround: (...a: unknown[]) => mockListMessagesAround(...a),+ listMessagesSince: (...a: unknown[]) => mockListMessagesSince(...a),+ getLatestMessageSeq: (...a: unknown[]) => mockGetLatestMessageSeq(...a),},communityMember: {listMembers: (...a: unknown[]) => mockListMembers(...a),@@ -185,6 +193,9 @@ describe("GET /api/community/dm/[id]/messages", () => {lastMessageAt: null,createdAt: "2026-06-30T00:00:00.000Z",})+ // Every route branch calls `getLatestMessageSeq` — default to 0 so tests+ // don't have to wire it individually.+ mockGetLatestMessageSeq.mockResolvedValue(0)})it("returns 403 and never reads messages when the counterpart is blocked", async () => {@@ -243,10 +254,10 @@ describe("GET /api/community/dm/[id]/messages", () => {expect(scope).toEqual({ dmConversationId: "d1" })})- it("runs attachment, reaction, and reply-target fetches in parallel", async () => {- // The 3 follow-up fetches have no cross-dependency; they must run+ it("runs attachment, reaction, reply-target, and latest-seq fetches in parallel", async () => {+ // The 4 follow-up fetches have no cross-dependency; they must run// concurrently (Promise.all), not sequentially. Prove it by observing- // in-flight count — all 3 must be dispatched before any resolves.+ // in-flight count — all 4 must be dispatched before any resolves.mockIsBlocked.mockResolvedValue(false)mockListMessages.mockResolvedValue([{ id: "m-1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "hi", type: "default", mentionType: null, replyToId: "r-1", dmConversationId: "d1", embeds: null, createdAt: "t1" },@@ -264,13 +275,115 @@ describe("GET /api/community/dm/[id]/messages", () => {mockListByMessageIds.mockImplementation(() => tracked([]))mockListReactionsByMessageIds.mockImplementation(() => tracked([]))mockGetMessagesByIdsInScope.mockImplementation(() => tracked([]))+ mockGetLatestMessageSeq.mockImplementation(() => tracked(0))const res = await GET(getReq(), ctx)expect(res.status).toBe(200)- expect(maxInFlight).toBe(3)+ expect(maxInFlight).toBe(4)expect(mockListByMessageIds).toHaveBeenCalledTimes(1)expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)+ expect(mockGetLatestMessageSeq).toHaveBeenCalledTimes(1)+ })++ it("always includes latestSeq in the legacy-mode envelope", async () => {+ mockIsBlocked.mockResolvedValue(false)+ mockListMessages.mockResolvedValue([])+ mockListByMessageIds.mockResolvedValue([])+ mockListReactionsByMessageIds.mockResolvedValue([])+ mockGetLatestMessageSeq.mockResolvedValue(23)+ const res = await GET(getReq(), ctx)+ expect(res.status).toBe(200)+ const body = (await res.json()) as { latestSeq: number }+ expect(body.latestSeq).toBe(23)+ expect(mockGetLatestMessageSeq).toHaveBeenCalledWith(expect.anything(), { dmConversationId: "d1" })+ })++ describe("?anchor mode", () => {+ it("returns a centered window with the anchor row present, plus latestSeq + cursors", async () => {+ mockIsBlocked.mockResolvedValue(false)+ mockGetMessageInScope.mockResolvedValue({+ id: "m_anchor",+ createdAt: "2026-06-30T00:00:03.000Z",+ })+ mockListMessagesAround.mockResolvedValue({+ older: [+ { id: "m_o1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "o1", type: "default", mentionType: null, replyToId: null, dmConversationId: "d1", 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, dmConversationId: "d1", 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, dmConversationId: "d1", embeds: null, createdAt: "2026-06-30T00:00:04.000Z" },+ ],+ hasMoreOlder: false,+ hasMoreNewer: true,+ })+ mockListByMessageIds.mockResolvedValue([])+ mockListReactionsByMessageIds.mockResolvedValue([])+ mockGetLatestMessageSeq.mockResolvedValue(11)++ const req = new NextRequest("http://localhost/api/community/dm/d1/messages?anchor=m_anchor", {+ method: "GET",+ })+ 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+ }+ expect(body.messages.map((m) => m.id)).toEqual(["m_o1", "m_anchor", "m_n1"])+ expect(body.hasMoreOlder).toBe(false)+ expect(body.hasMoreNewer).toBe(true)+ expect(body.olderCursor).toBeUndefined()+ expect(body.newerCursor).toBe(`2026-06-30T00:00:04.000Z|m_n1`)+ expect(body.latestSeq).toBe(11)+ // Scope-first resolve: anchor lookup passes the DM scope.+ expect(mockGetMessageInScope).toHaveBeenCalledWith(expect.anything(), "m_anchor", { dmConversationId: "d1" })+ })++ it("returns 404 when the anchor is not visible in this DM", async () => {+ mockIsBlocked.mockResolvedValue(false)+ mockGetMessageInScope.mockResolvedValue(null)+ const req = new NextRequest("http://localhost/api/community/dm/d1/messages?anchor=m_missing", {+ method: "GET",+ })+ const res = await GET(req, ctx)+ expect(res.status).toBe(404)+ expect(mockListMessagesAround).not.toHaveBeenCalled()+ })+ })++ describe("?since mode", () => {+ it("returns rows strictly newer than the cursor with hasMoreNewer + newerCursor + latestSeq", async () => {+ mockIsBlocked.mockResolvedValue(false)+ mockListMessagesSince.mockResolvedValue([+ { id: "m_1", authorId: "u1", authorName: "A", authorEmail: "[email protected]", authorImage: null, content: "1", type: "default", mentionType: null, replyToId: null, dmConversationId: "d1", embeds: null, createdAt: "2026-06-30T00:00:01.000Z" },+ ])+ mockListByMessageIds.mockResolvedValue([])+ mockListReactionsByMessageIds.mockResolvedValue([])+ mockGetLatestMessageSeq.mockResolvedValue(1)++ const req = new NextRequest(+ "http://localhost/api/community/dm/d1/messages?since=2026-06-30T00:00:00.000Z%7Cm_0",+ { method: "GET" },+ )+ 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+ latestSeq: number+ }+ expect(body.messages.map((m) => m.id)).toEqual(["m_1"])+ expect(body.hasMoreNewer).toBe(false)+ expect(body.latestSeq).toBe(1)+ expect(mockGetMessageInScope).not.toHaveBeenCalled()+ expect(mockListMessagesAround).not.toHaveBeenCalled()+ })})})diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.ts b/src/web/src/app/api/community/dm/[id]/messages/route.tsindex 661c1c9c4..45dbc6cda 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.ts@@ -3,7 +3,16 @@ import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"import { getDb } from "@/lib/db"import { queries } from "@alook/shared"-import { parseCursor, parsePageSize, buildPaginatedResponse, groupAttachments, groupReactions } from "@/lib/community/messages"+import {+ parseCursor,+ parseAnchor,+ parsePageSize,+ buildPaginatedResponse,+ buildAnchorResponse,+ buildSinceResponse,+ groupAttachments,+ groupReactions,+} from "@/lib/community/messages"import { requireDMParticipant } from "@/lib/community/permissions"import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage } from "@/lib/community/message-handler"@@ -17,8 +26,42 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const auth = await requireDMParticipant(db, dmId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)- const cursor = parseCursor(req.nextUrl.searchParams.get("cursor"))- const pageSize = parsePageSize(req.nextUrl.searchParams.get("limit"))+ const params = req.nextUrl.searchParams+ const anchorId = parseAnchor(params.get("anchor"))+ const since = parseCursor(params.get("since"))+ const cursor = parseCursor(params.get("cursor"))+ const pageSize = parsePageSize(params.get("limit"))++ if (anchorId) {+ const anchor = await queries.communityMessage.getMessageInScope(db, anchorId, { dmConversationId: dmId })+ if (!anchor) return writeError("anchor not found", 404)++ const around = await queries.communityMessage.listMessagesAround(db, {+ dmConversationId: dmId,+ anchor: { createdAt: anchor.createdAt, id: anchor.id },+ limit: pageSize,+ })++ const { items, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor } = buildAnchorResponse(+ around.older,+ around.newer,+ { hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },+ )++ const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, dmId, items)+ return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })+ }++ if (since) {+ const rows = await queries.communityMessage.listMessagesSince(db, {+ dmConversationId: dmId,+ since,+ limit: pageSize,+ })+ const { items, hasMoreNewer, newerCursor } = buildSinceResponse(rows, pageSize)+ const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, dmId, items)+ return writeJSON({ messages, hasMoreNewer, newerCursor, latestSeq })+ }const rows = await queries.communityMessage.listMessages(db, {dmConversationId: dmId,@@ -27,39 +70,44 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {})const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)+ const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, dmId, items.slice().reverse())+ return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })+})- // All three follow-up fetches depend only on `items` — no cross-dependency —- // so run them concurrently to collapse 3 sequential D1 round-trips into one- // wall-clock hop.+// DM sibling of the channel route's helper — no thread-indicator enrichment+// (DMs can't parent threads), everything else is symmetric.+async function enrichAndFinalize(+ db: ReturnType<typeof getDb>,+ userId: string,+ dmId: string,+ items: Array<{ id: string; replyToId: string | null } & Record<string, unknown>>,+): Promise<{ messages: unknown[]; latestSeq: number }> {const messageIds = items.map((m) => m.id)const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]- const [allAttachments, allReactions, replyMessages] = await Promise.all([+ const [allAttachments, allReactions, replyMessages, latestSeq] = await Promise.all([messageIds.length > 0? queries.communityAttachment.listByMessageIds(db, messageIds): Promise.resolve([]),messageIds.length > 0- ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, ctx.userId)+ ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId): Promise.resolve([]),replyToIds.length > 0? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { dmConversationId: dmId }): Promise.resolve([]),+ queries.communityMessage.getLatestMessageSeq(db, { dmConversationId: dmId }),])const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, ctx.userId)+ const reactionsByMessage = groupReactions(allReactions, userId)- // Reply targets are already scoped to this DM by the query above — a- // client can't leak previews of messages from other DMs/channels just by- // referencing their id.const replyMap = new Map(replyMessages.map((m) => [m.id, m]))const messages = items.map((r) =>- mapMessageForApi(r, { replyMap, attachmentsByMessage, reactionsByMessage }),+ mapMessageForApi(r as never, { replyMap, attachmentsByMessage, reactionsByMessage }),)-- return writeJSON({ messages: messages.reverse(), hasMore, cursor: nextCursor })-})+ return { messages, latestSeq }+}export const POST = withAuth(async (req: NextRequest, ctx) => {const dmId = ctx.params?.iddiff --git a/src/web/src/app/api/community/dm/[id]/read-state/route.test.ts b/src/web/src/app/api/community/dm/[id]/read-state/route.test.tsnew file mode 100644index 000000000..0414ac1e5--- /dev/null+++ b/src/web/src/app/api/community/dm/[id]/read-state/route.test.ts@@ -0,0 +1,111 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}))++const mockGetReadState = vi.fn()+const mockRequireDMParticipant = vi.fn()++vi.mock("@/lib/db", () => ({+ getDb: vi.fn(() => ({})),+}))++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityReadState: {+ getReadState: (...a: unknown[]) => mockGetReadState(...a),+ },+ },+ }+})++vi.mock("@/lib/community/permissions", () => ({+ requireDMParticipant: (...a: unknown[]) => mockRequireDMParticipant(...a),+}))++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+ return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })+ }),+}))++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) =>+ NextResponse.json({ error: message }, { status }),+ }+})++import { GET } from "./route"++function getReq() {+ return new NextRequest(+ "http://localhost/api/community/dm/dm1/read-state",+ { method: "GET" },+ )+}++describe("GET /api/community/dm/[id]/read-state", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockRequireDMParticipant.mockResolvedValue({ ok: true })+ })++ it("returns { null, null, 0 } when no read-state row exists (never-opened dm)", async () => {+ mockGetReadState.mockResolvedValue(null)++ const res = await GET(getReq(), { params: { id: "dm1" } } as any)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({ lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 })+ // Args to getReadState should scope by (userId, dmConversationId).+ expect(mockGetReadState).toHaveBeenCalledWith(expect.anything(), {+ userId: "u1",+ dmConversationId: "dm1",+ })+ })++ it("returns the actual (lastReadMessageId, lastReadAt, lastReadSeq) tuple when a row exists", async () => {+ mockGetReadState.mockResolvedValue({+ lastReadMessageId: "m_42",+ lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 42,+ })++ const res = await GET(getReq(), { params: { id: "dm1" } } as any)+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({+ lastReadMessageId: "m_42",+ lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 42,+ })+ })++ it("returns 400 when the dm id is missing", async () => {+ const res = await GET(getReq(), { params: {} } as any)+ expect(res.status).toBe(400)+ expect(mockRequireDMParticipant).not.toHaveBeenCalled()+ expect(mockGetReadState).not.toHaveBeenCalled()+ })++ it("returns 403 when the caller is not a participant", async () => {+ mockRequireDMParticipant.mockResolvedValue({+ ok: false,+ error: "not a participant",+ status: 403,+ })++ const res = await GET(getReq(), { params: { id: "dm1" } } as any)+ expect(res.status).toBe(403)+ expect(mockGetReadState).not.toHaveBeenCalled()+ })+})diff --git a/src/web/src/app/api/community/dm/[id]/read-state/route.ts b/src/web/src/app/api/community/dm/[id]/read-state/route.tsnew file mode 100644index 000000000..c9faf4bc6--- /dev/null+++ b/src/web/src/app/api/community/dm/[id]/read-state/route.ts@@ -0,0 +1,45 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries } from "@alook/shared"+import { requireDMParticipant } from "@/lib/community/permissions"++/**+ * GET /api/community/dm/:id/read-state+ *+ * DM twin of `GET /channels/:id/read-state`. Snapshot of the viewer's read+ * pointer for a single DM. Consumed once per DM mount to compute the "New"+ * divider anchor and initial scroll position. Returns `{ null, null, 0 }`+ * when the viewer has never opened the DM — the caller treats that as+ * "everything is new, but no divider (start at the bottom)", matching common+ * chat-app first-visit UX.+ *+ * `requireDMParticipant` handles both unknown-DM and non-participant cases+ * (returns 403 for either — the DM permission helper deliberately collapses+ * them, unlike the channel route which surfaces a 404 for unknown ids).+ */+export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const dmId = ctx.params?.id+ if (!dmId) return writeError("missing dm id", 400)++ const db = getDb(ctx.env.DB)+ const auth = await requireDMParticipant(db, dmId, ctx.userId)+ if (!auth.ok) return writeError(auth.error, auth.status)++ const row = await queries.communityReadState.getReadState(db, {+ userId: ctx.userId,+ dmConversationId: dmId,+ })++ return writeJSON({+ lastReadMessageId: row?.lastReadMessageId ?? null,+ lastReadAt: row?.lastReadAt ?? null,+ // Seq is the numeric equivalent of the (createdAt, id) pointer — used+ // client-side to compute the `↓ N` unread count without walking the+ // loaded rows (`latestSeq - lastReadSeq`). Falls back to 0 when the+ // viewer has never visited: `latestSeq - 0` = all-messages-are-new,+ // matching what the divider anchor implies.+ lastReadSeq: row?.lastReadSeq ?? 0,+ })+})diff --git a/src/web/src/app/api/community/inbox/unreads/route.test.ts b/src/web/src/app/api/community/inbox/unreads/route.test.tsindex 4463aec0c..be0d48889 100644--- a/src/web/src/app/api/community/inbox/unreads/route.test.ts+++ b/src/web/src/app/api/community/inbox/unreads/route.test.ts@@ -4,6 +4,7 @@ import { NextRequest } from "next/server"const mockListUnreadChannels = vi.fn()const mockGetSettings = vi.fn()const mockListUnreadMentions = vi.fn()+const mockListUnreadDms = vi.fn()vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),@@ -18,6 +19,7 @@ vi.mock("@alook/shared", async () => {queries: {communityInbox: {listUnreadChannels: (...args: unknown[]) => mockListUnreadChannels(...args),+ listUnreadDms: (...args: unknown[]) => mockListUnreadDms(...args),},communityNotificationSetting: {getSettings: (...args: unknown[]) => mockGetSettings(...args),@@ -63,6 +65,7 @@ describe("GET /api/community/inbox/unreads", () => {vi.clearAllMocks()mockGetSettings.mockResolvedValue([])mockListUnreadMentions.mockResolvedValue([])+ mockListUnreadDms.mockResolvedValue([])})it("groups channels by server", async () => {@@ -144,4 +147,43 @@ describe("GET /api/community/inbox/unreads", () => {const body = await res.json()expect(body.truncated).toBe(false)})++ it("returns unread DMs sorted most-recent first", async () => {+ mockListUnreadChannels.mockResolvedValue([])+ mockListUnreadDms.mockResolvedValue([+ { dmConversationId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T09:00:00Z" },+ { dmConversationId: "dm_2", otherUserId: "u3", otherUserName: "Bob", otherUserImage: "https://cdn/b.png", lastMessageAt: "2026-06-25T11:00:00Z" },+ ])++ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const body = await res.json()++ expect(res.status).toBe(200)+ expect(body.dms).toHaveLength(2)+ expect(body.dms[0].dmConversationId).toBe("dm_2")+ expect(body.dms[0].otherUserAvatar).toBe("https://cdn/b.png")+ expect(body.dms[1].dmConversationId).toBe("dm_1")+ // No cdn image → avatar falls back to the initial letter.+ expect(body.dms[1].otherUserAvatar).toBe("A")+ })++ it("returns empty dms array when only channels are unread", async () => {+ mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])+ mockListUnreadDms.mockResolvedValue([])+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const body = await res.json()+ expect(body.dms).toEqual([])+ expect(body.servers).toHaveLength(1)+ })++ it("returns dms alongside servers when both have unreads", async () => {+ mockListUnreadChannels.mockResolvedValue([row({ channelId: "c1" })])+ mockListUnreadDms.mockResolvedValue([+ { dmConversationId: "dm_1", otherUserId: "u2", otherUserName: "Alice", otherUserImage: null, lastMessageAt: "2026-06-25T12:00:00Z" },+ ])+ const res = await GET(new NextRequest("http://localhost/api/community/inbox/unreads"))+ const body = await res.json()+ expect(body.servers).toHaveLength(1)+ expect(body.dms).toHaveLength(1)+ })})diff --git a/src/web/src/app/api/community/inbox/unreads/route.ts b/src/web/src/app/api/community/inbox/unreads/route.tsindex 8e9767566..d445e4a5f 100644--- a/src/web/src/app/api/community/inbox/unreads/route.ts+++ b/src/web/src/app/api/community/inbox/unreads/route.ts@@ -7,6 +7,7 @@ import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"import { writeJSON } from "@/lib/middleware/helpers"import { parseBoundedInt } from "@/lib/community/messages"+import { avatarInitial } from "@/lib/community/avatar"export const GET = withAuth(async (req, ctx) => {const db = getDb(ctx.env.DB)@@ -17,10 +18,11 @@ export const GET = withAuth(async (req, ctx) => {MAX_INBOX_PAGE_SIZE,)- const [unread, settings, mentions] = await Promise.all([+ const [unread, settings, mentions, unreadDms] = await Promise.all([queries.communityInbox.listUnreadChannels(db, ctx.userId),queries.communityNotificationSetting.getSettings(db, ctx.userId),queries.communityMention.listUnreadMentions(db, ctx.userId),+ queries.communityInbox.listUnreadDms(db, ctx.userId),])const mutedServers = new Set<string>()@@ -88,5 +90,21 @@ export const GET = withAuth(async (req, ctx) => {}const truncated = total < allServers.reduce((n, s) => n + s.channels.length, 0)- return writeJSON({ servers, limit, truncated })+ // DMs are a flat list sorted most-recent first. DM notification settings+ // don't exist today (`communityNotificationSetting` scopes are server/channel+ // only), so no muting pass — every unread DM the viewer participates in+ // surfaces. Blocked-user filtering intentionally stays off: DM messages+ // route gates on `requireDMParticipant`; an unread from a blocked user is+ // still the viewer's DM and should appear here.+ const dms = unreadDms+ .map((d) => ({+ dmConversationId: d.dmConversationId,+ otherUserId: d.otherUserId,+ otherUserName: d.otherUserName,+ otherUserAvatar: d.otherUserImage ?? avatarInitial(d.otherUserName),+ lastMessageAt: d.lastMessageAt,+ }))+ .sort((a, b) => (a.lastMessageAt < b.lastMessageAt ? 1 : -1))++ return writeJSON({ servers, dms, limit, truncated })})diff --git a/src/web/src/app/community/QueryProvider.tsx b/src/web/src/app/community/QueryProvider.tsxindex 4c67b9b60..df36462bc 100644--- a/src/web/src/app/community/QueryProvider.tsx+++ b/src/web/src/app/community/QueryProvider.tsx@@ -1,9 +1,15 @@"use client"import { useState, type ReactNode } from "react"-import { QueryClientProvider } from "@tanstack/react-query"import { ReactQueryDevtools } from "@tanstack/react-query-devtools"+import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"import { createQueryClient } from "@/lib/query-client"+import {+ createIdbPersister,+ PERSIST_BUSTER,+ PERSIST_MAX_AGE_MS,+ shouldPersistQuery,+} from "@/lib/query-persister"/*** Owns the TanStack QueryClient for the community subtree.@@ -14,15 +20,51 @@ import { createQueryClient } from "@/lib/query-client"* module-scoped singleton across users. Coexists with `<CommunityProvider>`* during the God-context migration — later steps move state into TanStack* Query and Zustand, then delete the old provider.+ *+ * `userId` scopes the IndexedDB namespace so account switches never surface+ * the previous session's cached message list. Passing `null` (pre-auth) hits+ * an "anon" namespace that never carries real content.*/-export function QueryProvider({ children }: { children: ReactNode }) {+export function QueryProvider({+ children,+ userId,+}: {+ children: ReactNode+ userId: string | null+}) {const [queryClient] = useState(() => createQueryClient())+ // Persister is bound to the userId at construction; on account switch the+ // whole community subtree unmounts and the shell re-renders with the new+ // id, so we don't need to reactively rebuild the persister mid-session.+ const [persister] = useState(() => createIdbPersister(userId))const isDev = process.env.NODE_ENV !== "production"return (- <QueryClientProvider client={queryClient}>+ <PersistQueryClientProvider+ client={queryClient}+ persistOptions={{+ persister,+ maxAge: PERSIST_MAX_AGE_MS,+ buster: PERSIST_BUSTER,+ dehydrateOptions: {+ shouldDehydrateQuery: (query) => {+ // Two-stage filter:+ // 1. Key must be in the persisted allowlist (only message queries+ // are persisted — presence/servers/etc. refetch on mount).+ // 2. For message queries, `pages[0]` must be a trusted+ // newest-tail shape. A since-mode or older-only envelope has+ // no `hasMore` flag on page 0 → the next mount reads+ // `hasMoreOlder ?? hasMore ?? false` as false and silently+ // loses history. Filter these out at write time so the+ // self-healing invariant holds across sessions.+ if (query.state.status !== "success") return false+ return shouldPersistQuery(query.queryKey, query.state.data)+ },+ },+ }}+ >{children}{isDev ? <ReactQueryDevtools initialIsOpen={false} /> : null}- </QueryClientProvider>+ </PersistQueryClientProvider>)}diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsxindex ecdb994a5..154206846 100644--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx@@ -45,6 +45,7 @@ import {useKickMember,useSetChannelNotif,useUploadFile,+ type SendMessageResult,} from "@/hooks/community/mutations"import {communityWsSubscribe,@@ -121,16 +122,35 @@ function ChannelView() {serverName: currentServer?.name ?? "",}))}, [currentServer, serverId])-- const messagesQuery = useMessages(channelId)- const { messages, isLoading: messagesLoading } = messagesQuery-// Frozen-once snapshot of the viewer's read pointer for this channel — the// anchor for the "New" divider AND the mount-time initial scroll target.// The value NEVER changes during the mount even as the watermark advances.const { snapshot: readSnapshot, isFetching: readSnapshotFetching } =useChannelReadStateSnapshot(channelId)+ // Anchor the initial page on the read pointer so an unread-heavy channel+ // opens with a centered window instead of the newest 50. Pass `undefined`+ // while the snapshot is still resolving — the hook stays disabled until+ // the value settles (a bare `null` would fall back to newest-mode too+ // early).+ const messagesQuery = useMessages(channelId, {+ lastReadMessageId: readSnapshotFetching+ ? undefined+ : (readSnapshot?.lastReadMessageId ?? null),+ })+ const {+ messages,+ isLoading: messagesLoading,+ hasMoreOlder: hasMoreMessages,+ hasMoreNewer: hasMoreNewerMessages,+ isFetchingOlder: isFetchingOlderMessages,+ isFetchingNewer: isFetchingNewerMessages,+ fetchOlder: fetchOlderMessages,+ fetchNewer: fetchNewerMessages,+ jumpToPresent,+ latestSeq,+ } = messagesQuery+// The message immediately after the viewer's `lastReadMessageId` inside the// current window. id-first: the invariant guarantees// `getMessage(lastReadMessageId).createdAt === lastReadAt`, so we only need@@ -144,8 +164,18 @@ function ChannelView() {// walk, the divider anchors above the viewer's OWN just-sent message,// which is never "unread" from the sender's perspective.const newDividerBefore = useMemo(() => {- const lastId = readSnapshot?.lastReadMessageId- if (!lastId) return undefined+ if (!readSnapshot) return undefined+ const lastId = readSnapshot.lastReadMessageId+ // First-visit case (viewer never read this channel): anchor the+ // divider on the first non-self message so users landing from+ // inbox / rail see "here's what you missed" instead of the bottom.+ // Mirrors the DM view for parity.+ if (!lastId) {+ for (const m of messages) {+ if (m.authorId !== currentUser.id) return m.id+ }+ return undefined+ }const idx = messages.findIndex((m) => m.id === lastId)if (idx === -1) return undefinedfor (let i = idx + 1; i < messages.length; i++) {@@ -161,6 +191,16 @@ function ChannelView() {const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)useChannelWatermark({ channelId, messages, scrollRootEl })+ // `↓ N` unread count for the anchor-window path — server truth+ // (`latestSeq - viewerLastReadSeq`). Clamped to 0 in case the read+ // pointer somehow overshot latestSeq (e.g. a bot updated latestSeq+ // between the two fetches).+ const unreadCount = useMemo(() => {+ const seenSeq = readSnapshot?.lastReadSeq ?? 0+ const diff = latestSeq - seenSeq+ return diff > 0 ? diff : 0+ }, [latestSeq, readSnapshot])+const { threads, isLoading: threadsLoading } = useThreads(channelId)const { posts: forumPosts, isLoading: forumPostsLoading } = useForumPosts(channelId, isForum)const { pins: pinned, isLoading: pinnedLoading } = usePins(channelId)@@ -278,20 +318,32 @@ function ChannelView() {}// ── Message actions ─────────────────────────────────────────────────────+ //+ // Swallow send failures at the caller boundary. `useSendMessage`'s `onError`+ // already marks the optimistic row `failed: true` AND fires the rate-limit+ // toast; we don't need the raw rejection to propagate any further. Letting+ // it escape via `mutateAsync` would surface a bare `ApiError` in the Next.js+ // error overlay (rate-limit path was the reproducer). Returning `null`+ // instead lets thread-create + retry callers detect failure without a+ // try/catch each.const doSend = useCallback(- (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: { url: string; filename: string; contentType: string; size: number }[] }) => {- return sendMessageMut.mutateAsync({- channelId,- content,- replyToId: opts?.replyToId,- mentionType: opts?.mentionType,- attachments: opts?.attachments,- author: {- id: currentUser.id,- name: currentUser.name,- avatar: currentUser.avatar,- },- })+ async (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: { url: string; filename: string; contentType: string; size: number }[] }): Promise<SendMessageResult | null> => {+ try {+ return await sendMessageMut.mutateAsync({+ channelId,+ content,+ replyToId: opts?.replyToId,+ mentionType: opts?.mentionType,+ attachments: opts?.attachments,+ author: {+ id: currentUser.id,+ name: currentUser.name,+ avatar: currentUser.avatar,+ },+ })+ } catch {+ return null+ }},[sendMessageMut, channelId, currentUser.id, currentUser.name, currentUser.avatar],)@@ -533,6 +585,14 @@ function ChannelView() {scrollToMessageId={scrollToMessageId}hero={opener}viewerUserId={currentUser.id}+ hasMore={hasMoreMessages}+ isFetchingOlder={isFetchingOlderMessages}+ onLoadOlder={fetchOlderMessages}+ hasMoreNewer={hasMoreNewerMessages}+ isFetchingNewer={isFetchingNewerMessages}+ onLoadNewer={fetchNewerMessages}+ onJumpToPresent={jumpToPresent}+ unreadCount={unreadCount}/><Composerchannel={channelName}@@ -644,6 +704,14 @@ function ChannelView() {// otherwise the effect fires with newDividerBefore still stale// and snaps to bottom before the anchor is known.initialScrollReady={!readSnapshotFetching}+ hasMore={hasMoreMessages}+ isFetchingOlder={isFetchingOlderMessages}+ onLoadOlder={fetchOlderMessages}+ hasMoreNewer={hasMoreNewerMessages}+ isFetchingNewer={isFetchingNewerMessages}+ onLoadNewer={fetchNewerMessages}+ onJumpToPresent={jumpToPresent}+ unreadCount={unreadCount}/><Composerchannel={channelName}diff --git a/src/web/src/app/community/channels/layout.tsx b/src/web/src/app/community/channels/layout.tsxindex 2ab2ddffd..79075ccf8 100644--- a/src/web/src/app/community/channels/layout.tsx+++ b/src/web/src/app/community/channels/layout.tsx@@ -119,21 +119,25 @@ export default function ServerLayout({ children }: { children: ReactNode }) {// 4. Viewer pasted a URL for a server they were never in (list// finishes loading, id is missing from the start).//- // Wait for the servers query to finish its first fetch — otherwise the- // pre-fetch render bounces every legitimate URL. Also gate on the- // `!ejectedRef` to prevent a re-fire while the redirect is in flight.+ // Gate on `isFetched && !isFetching`, not on `isLoading`. TanStack v5+ // `isLoading` is only true on the very first fetch — after any WS+ // invalidate, reconnect, or IDB rehydrate, `isLoading=false` even while+ // `servers=[]` between refetches. Using `isLoading` alone false-triggered+ // this eject on every reload (see the "You're no longer in this server"+ // toast on refresh regression). Also gate on the `!ejectedRef` to prevent+ // a re-fire while the redirect is in flight.const serversList = useServers()const ejectedRef = useRef(false)useEffect(() => {if (ejectedRef.current) return- if (serversList.isLoading) return+ if (!serversList.isFetched || serversList.isFetching) returnconst inRail = serversList.servers.some((s) => s.id === serverId)if (inRail) returnejectedRef.current = trueconst voluntary = consumeVoluntaryLeave(serverId)if (!voluntary) toast("You're no longer in this server")router.replace(pickPostEjectDestination(serversList.servers, serverId))- }, [serverId, serversList.isLoading, serversList.servers, router])+ }, [serverId, serversList.isFetched, serversList.isFetching, serversList.servers, router])// Reset the guard when the URL changes to a NEW server id — otherwise// navigating server → dangling-server → server would leave the ref// latched and skip the eject.diff --git a/src/web/src/app/community/community-shell.tsx b/src/web/src/app/community/community-shell.tsxindex 000c83bb0..073b7b5a5 100644--- a/src/web/src/app/community/community-shell.tsx+++ b/src/web/src/app/community/community-shell.tsx@@ -31,7 +31,7 @@ export function CommunityShell({children: ReactNode}) {return (- <QueryProvider>+ <QueryProvider userId={currentUser.id}><CurrentUserProvider initialUser={currentUser}><CommunityBootstrap>{children}</CommunityBootstrap></CurrentUserProvider>diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsxindex 252547f92..fb0c81fd6 100644--- a/src/web/src/app/community/me/[dmId]/page.tsx+++ b/src/web/src/app/community/me/[dmId]/page.tsx@@ -18,6 +18,8 @@ import { useOnlineUserIds } from "@/stores/community/ws"import { useDms } from "@/hooks/community/use-dms"import { useFriends } from "@/hooks/community/use-friends"import { useDmMessages } from "@/hooks/community/use-messages"+import { useDmReadStateSnapshot } from "@/hooks/community/use-dm-read-state"+import { useDmWatermark } from "@/hooks/community/use-dm-watermark"import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"import {useSendDmMessage,@@ -63,10 +65,32 @@ function DmView() {})),[rawFriends, onlineUserIds],)+ // Frozen-once snapshot of the viewer's DM read pointer — the anchor for+ // the "New" divider AND the initial-page mode. Mirrors the channel-view+ // wiring so both surfaces open with the same anchor-window UX.+ const { snapshot: readSnapshot, isFetching: readSnapshotFetching } =+ useDmReadStateSnapshot(dmId)++ // Anchor the initial page on the viewer's read pointer. Pass `undefined`+ // (not `null`) while the snapshot resolves — the hook's initialPageParam+ // gate treats `undefined` as "not-yet-decided" and stays disabled, so we+ // don't fire a newest-mode fetch that would immediately be superseded.const {messages,isLoading: messagesLoading,- } = useDmMessages(dmId)+ hasMoreOlder: hasMoreMessages,+ hasMoreNewer: hasMoreNewerMessages,+ isFetchingOlder: isFetchingOlderMessages,+ isFetchingNewer: isFetchingNewerMessages,+ fetchOlder: fetchOlderMessages,+ fetchNewer: fetchNewerMessages,+ jumpToPresent,+ latestSeq,+ } = useDmMessages(dmId, {+ lastReadMessageId: readSnapshotFetching+ ? undefined+ : (readSnapshot?.lastReadMessageId ?? null),+ })// DM composer has no "current server" — flatten every member server's// channels into one cross-server candidate list so a `/`-ref can be// dropped into a DM (see plan community-channel-ref.md §6).@@ -78,6 +102,51 @@ function DmView() {),[channelRefDirectory],)+ // Anchor of the "New" divider: the first non-self message after+ // `lastReadMessageId` inside the currently-loaded window. Mirrors the+ // channel-view logic exactly — see channel page for why we skip past+ // runs of viewer-authored messages (the server advances the sender's+ // own watermark on POST, so anchoring above the viewer's own row would+ // never be "unread" from the sender's perspective).+ const newDividerBefore = useMemo(() => {+ if (!readSnapshot) return undefined+ const lastId = readSnapshot.lastReadMessageId+ // First-visit case: viewer never opened this DM (no read-state row+ // yet). The inbox surfaces the DM as unread, so the whole loaded+ // window is unread from the viewer's perspective — anchor the+ // divider on the first non-self message so the user lands centered+ // on "here's what you missed" instead of the bottom.+ if (!lastId) {+ for (const m of messages) {+ if (m.authorId !== currentUser.id) return m.id+ }+ return undefined+ }+ const idx = messages.findIndex((m) => m.id === lastId)+ if (idx === -1) return undefined+ for (let i = idx + 1; i < messages.length; i++) {+ if (messages[i].authorId !== currentUser.id) return messages[i].id+ }+ return undefined+ }, [messages, readSnapshot, currentUser.id])++ // Scroll root of the message list — needed so `useDmWatermark`'s+ // IntersectionObserver measures against the correct viewport rather+ // than the page viewport. Set once by `MessageList` via `onScrollRoot`.+ const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)+ useDmWatermark({ dmId, messages, scrollRootEl })++ // `↓ N` unread count. Same math as channel: server truth is+ // `latestSeq - viewerLastReadSeq`. Clamp to 0 in case the read pointer+ // overshoots (e.g. a race between the read-state snapshot and a fresh+ // `latestSeq` fetch).+ const unreadCount = useMemo(() => {+ const seenSeq = readSnapshot?.lastReadSeq ?? 0+ const diff = latestSeq - seenSeq+ return diff > 0 ? diff : 0+ }, [latestSeq, readSnapshot])++const typingUsers = useCommunityStore((s) => s.typingUsers)const sendDmMessage = useSendDmMessage()const toggleReaction = useToggleReactionApi()@@ -125,6 +194,10 @@ function DmView() {toggleReaction({ dmId, messageId: id, emoji, userId: currentUser.id }),onReact: (id: string, emoji: string) =>toggleReaction({ dmId, messageId: id, emoji, userId: currentUser.id }),+ onReply: (id: string) => {+ const m = messages.find((x) => x.id === id)+ if (m) setReplyTo({ id: m.id, authorName: m.authorName ?? "", text: m.content ?? "" })+ },onCopy: (id: string) => {const m = messages.find((x) => x.id === id)if (m?.content) { navigator.clipboard?.writeText(m.content); toast("Copied to clipboard") }@@ -143,7 +216,16 @@ function DmView() {})}},- }), [toggleReaction, dmId, currentUser.id, currentUser.name, currentUser.avatar, messages, sendDmMessage])+ onPreviewImage: (url: string) => {+ uiHandlers.previewImage?.(url)+ },+ onDownloadFile: (url: string) => {+ const a = document.createElement("a")+ a.href = url+ a.download = url.split("/").pop() ?? "file"+ a.click()+ },+ }), [toggleReaction, dmId, currentUser.id, currentUser.name, currentUser.avatar, messages, sendDmMessage, uiHandlers])// DM endpoint ignores mentionType. Replies are supported — the backend// persists replyToId for DMs too.@@ -215,15 +297,39 @@ function DmView() {channel={dm.name}messages={messages}loading={messagesLoading}- typingUsers={typingUsers.map((id) => friends.find((f) => f.userId === id)?.name ?? id)}+ newDividerBefore={newDividerBefore}+ typingUsers={typingUsers.map((id) => {+ // In a DM there are only two participants — if the typing id+ // matches the DM's counterpart, use their DM display name.+ // Fall back to friends list (adds names for friend-typers in+ // group DMs when we add them) and finally to the raw id.+ if (dm && id === dm.userId) return dm.name+ return friends.find((f) => f.userId === id)?.name ?? id+ })}onOpenThread={() => {}}onToggleReaction={dmBlocked ? undefined : messageActions.onToggleReaction}onReact={dmBlocked ? undefined : messageActions.onReact}+ onReply={dmBlocked ? undefined : messageActions.onReply}onCopy={messageActions.onCopy}onRetry={dmBlocked ? undefined : messageActions.onRetry}+ onPreviewImage={messageActions.onPreviewImage}+ onDownloadFile={messageActions.onDownloadFile}onOpenProfile={openProfile}resolveUserName={resolveUserName}+ onScrollRoot={setScrollRootEl}viewerUserId={currentUser.id}+ // Delay initial scroll until the read-state snapshot resolves —+ // otherwise the effect fires with `newDividerBefore` still+ // undefined and snaps to bottom before the anchor is known.+ initialScrollReady={!readSnapshotFetching}+ hasMore={hasMoreMessages}+ isFetchingOlder={isFetchingOlderMessages}+ onLoadOlder={fetchOlderMessages}+ hasMoreNewer={hasMoreNewerMessages}+ isFetchingNewer={isFetchingNewerMessages}+ onLoadNewer={fetchNewerMessages}+ onJumpToPresent={jumpToPresent}+ unreadCount={unreadCount}hero={<><div className="relative mb-3 w-fit"><Avatar label={dm.avatar} size={64} /></div>diff --git a/src/web/src/app/community/me/layout.tsx b/src/web/src/app/community/me/layout.tsxindex 73d5bb9ac..a515f4043 100644--- a/src/web/src/app/community/me/layout.tsx+++ b/src/web/src/app/community/me/layout.tsx@@ -1,6 +1,7 @@"use client"import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"+import { useQueryClient } from "@tanstack/react-query"import { usePathname, useRouter, useParams } from "next/navigation"import { useBreakpoint } from "@/hooks/use-mobile"import { ShellFrame } from "@/components/community/shell-frame"@@ -9,7 +10,7 @@ import type { MobileZone } from "@/components/community/_types"import { useCommunityStore, useCurrentChannelId } from "@/stores/community"import { useDms } from "@/hooks/community/use-dms"import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"-import { useMarkDmRead } from "@/hooks/community/mutations"+import { communityKeys } from "@/lib/query-keys"import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"// DM-side layout. The DM subtree has no server settings, no channel sidebar,@@ -33,7 +34,7 @@ export default function MeLayout({ children }: { children: ReactNode }) {)const { blocked } = useFriends()const currentChannelId = useCurrentChannelId()- const markDmRead = useMarkDmRead()+ const queryClient = useQueryClient()// Clear the active server when entering the DM home. `currentServerId ===// null` is the canonical "no server focused" state — no need for a "@me"@@ -61,11 +62,30 @@ export default function MeLayout({ children }: { children: ReactNode }) {const [mobileZone, setMobileZone] = useState<MobileZone>(() => (hasDm ? "messages" : "nav"))+ // Mirror channel sidebar-click behavior (channels/layout.tsx:226-236): do+ // NOT eagerly mark the DM read on click. That fires a bodyless+ // `PUT /dm/:id/read` which the server aligns to the DM's tail (see+ // api/community/dm/[id]/read/route.ts) — the read-state snapshot then+ // resolves at the tail on mount and `newDividerBefore` computes to+ // `undefined`, so unread DMs open at the bottom with no NEW divider.+ //+ // Instead: client-only optimistic tint on the DM sidebar row so the badge+ // fades on click (matches the pre-fix UX). The IntersectionObserver in+ // `useDmWatermark` is authoritative — it advances the server pointer as the+ // viewer actually looks at messages. If the user opens then leaves without+ // scrolling to the new messages, the server watermark stays put and the+ // badge re-appears on the next refetch, which is the correct behavior.const enterDm = useCallback((id: string) => {- markDmRead.mutate({ dmId: id })+ queryClient.setQueryData(+ communityKeys.dms(),+ (prev: { conversations: { id: string; unread?: boolean }[] } | undefined) =>+ prev+ ? { ...prev, conversations: prev.conversations.map((d) => (d.id === id ? { ...d, unread: false } : d)) }+ : prev,+ )router.push(`/community/me/${id}`)if (bp === "mobile") setMobileZone("messages")- }, [markDmRead, router, bp])+ }, [queryClient, router, bp])const onShowFriends = useCallback(() => {useCommunityStore.getState().setCurrentChannelId(null)diff --git a/src/web/src/app/community/preview/page.tsx b/src/web/src/app/community/preview/page.tsxindex c3f0d1572..44743f8f3 100644--- a/src/web/src/app/community/preview/page.tsx+++ b/src/web/src/app/community/preview/page.tsx@@ -115,6 +115,7 @@ export default function CommunityPreview() {inbox: (<InboxPopoverunreads={unreadFeed}+ unreadDms={[]}mentions={MENTIONS}onOpenChannel={openServerChannel}onMarkAllRead={() => {}}@@ -523,7 +524,7 @@ export default function CommunityPreview() {<NewThreadDialog channel={activeChannel} open={creatingThread} onClose={() => setCreatingThread(false)} onCreate={(name, firstMessage) => createThread(name, { firstMessage })} /><Dialog open={editingProfile} onOpenChange={(o) => { if (!o) setEditingProfile(false) }}><DialogContent className="flex h-[calc(100vh-4rem)] w-[calc(100vw-4rem)] sm:max-w-none flex-col gap-0 overflow-hidden rounded-xl p-0" showCloseButton={false}>- <UserSettings onClose={() => setEditingProfile(false)} userName="Preview User" aboutMe={myAboutMe} onSave={(data) => { if (data.aboutMe !== undefined) setMyAboutMe(data.aboutMe) }} onLogout={() => toast("Logged out")} />+ <UserSettings onClose={() => setEditingProfile(false)} userId={null} userName="Preview User" aboutMe={myAboutMe} onSave={(data) => { if (data.aboutMe !== undefined) setMyAboutMe(data.aboutMe) }} onLogout={() => toast("Logged out")} /></DialogContent></Dialog><Dialog open={view === "settings"} onOpenChange={(o) => { if (!o) goServer() }}>diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.tsindex 1f00ec090..c9a0a0551 100644--- a/src/web/src/components/community/_types.ts+++ b/src/web/src/components/community/_types.ts@@ -243,6 +243,16 @@ export type UnreadServer = {}>}+// "Unreads" — DMs with unread messages, rendered as a flat sibling section+// under the same Unreads tab as channels.+export type UnreadDm = {+ dmConversationId: string+ otherUserId: string+ otherUserName: string+ otherUserAvatar: string+ lastMessageAt: string+}+// Shared callback signature for opening a user's profile card at a click point.// `discriminator` is only ever passed for a mention pill that carried a// disambiguating `#0042` tag (see message-markdown.tsx) — it lets the lookupdiff --git a/src/web/src/components/community/community-inbox-popover.tsx b/src/web/src/components/community/community-inbox-popover.tsxindex 3245b0328..778cd8afb 100644--- a/src/web/src/components/community/community-inbox-popover.tsx+++ b/src/web/src/components/community/community-inbox-popover.tsx@@ -4,17 +4,36 @@ import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuIteimport { Skeleton } from "@/components/ui/skeleton"import { Avatar } from "./avatar"import { EmptyState } from "./empty-state"-import type { Mention, UnreadServer } from "./_types"+import type { Mention, UnreadDm, UnreadServer } from "./_types"-function UnreadsTab({ servers, loading, onOpenChannel }: {+function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenDm }: {servers: UnreadServer[]+ dms: UnreadDm[]loading?: booleanonOpenChannel?: (serverId: string, channelId: string) => void+ onOpenDm?: (dmId: string) => void}) {+ const nothingUnread = servers.length === 0 && dms.length === 0return (<div className="h-full overflow-y-auto thin-scrollbar p-3">- {loading && servers.length === 0 && <InboxUnreadsSkeleton />}- {!loading && servers.length === 0 && <EmptyState icon={Inbox} label="Caught up" />}+ {loading && nothingUnread && <InboxUnreadsSkeleton />}+ {!loading && nothingUnread && <EmptyState icon={Inbox} label="Caught up" />}+ {dms.length > 0 && (+ <div className="mb-3">+ <div className="px-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">Direct Messages</div>+ {dms.map((d) => (+ <button+ key={d.dmConversationId}+ onClick={() => onOpenDm?.(d.dmConversationId)}+ className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"+ >+ <Avatar label={d.otherUserAvatar} size={24} />+ <span className="min-w-0 flex-1 truncate">{d.otherUserName}</span>+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" />+ </button>+ ))}+ </div>+ )}{servers.map((s) => (<div key={s.serverId} className="mb-3"><div className="px-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">{s.serverName}</div>@@ -81,22 +100,27 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention }: {export function InboxPopover({unreads,+ unreadDms,mentions,loading,onOpenChannel,+ onOpenDm,onOpenMention,onDeleteMention,onMarkAllRead,}: {unreads: UnreadServer[]+ unreadDms: UnreadDm[]mentions: Mention[]loading?: booleanonOpenChannel?: (serverId: string, channelId: string) => void+ onOpenDm?: (dmId: string) => voidonOpenMention?: (m: Mention) => voidonDeleteMention?: (id: string) => voidonMarkAllRead?: () => void}) {- const hasAnything = unreads.length > 0 || mentions.length > 0+ const hasUnreads = unreads.length > 0 || unreadDms.length > 0+ const hasAnything = hasUnreads || mentions.length > 0return (<Tabs defaultValue="unreads" className="flex h-112 flex-col"><div className="flex items-center gap-2 px-3 pt-4">@@ -116,7 +140,7 @@ export function InboxPopover({<TabsTrigger value="unreads"><span className="inline-flex items-center gap-2">Unreads- {unreads.length > 0 && <span className="size-1.5 rounded-full bg-primary" />}+ {hasUnreads && <span className="size-1.5 rounded-full bg-primary" />}</span></TabsTrigger><TabsTrigger value="mentions">@@ -127,7 +151,7 @@ export function InboxPopover({</TabsTrigger></TabsList><TabsContent value="unreads" className="min-h-0 flex-1">- <UnreadsTab servers={unreads} loading={loading} onOpenChannel={onOpenChannel} />+ <UnreadsTab servers={unreads} dms={unreadDms} loading={loading} onOpenChannel={onOpenChannel} onOpenDm={onOpenDm} /></TabsContent><TabsContent value="mentions" className="min-h-0 flex-1"><MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} />diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex 41331856a..58753ced6 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -9,6 +9,7 @@ import Placeholder from "@tiptap/extension-placeholder"import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"import { Skeleton } from "@/components/ui/skeleton"import { useFileAttachments } from "@/hooks/use-file-attachments"+import { ALLOWED_ATTACHMENT_MIME_PREFIXES, MAX_ATTACHMENT_SIZE_BYTES } from "@alook/shared"import { Avatar } from "./avatar"import { ChannelIcon } from "./channel-icon"import { EmojiPickerPopover } from "./emoji-picker"@@ -71,7 +72,13 @@ export function Composer({ channel, context, members, onSearchMembers, channelRehandleDragLeave,handleDragOver,handleDrop: handleDropRaw,- } = useFileAttachments()+ } = useFileAttachments({+ // Community server enforces both. Passing them here rejects oversized /+ // wrong-mime files at the drag-drop OR file-picker boundary so users+ // see a scoped toast instead of a generic 400 on send.+ maxFileSize: MAX_ATTACHMENT_SIZE_BYTES,+ allowedMimePrefixes: ALLOWED_ATTACHMENT_MIME_PREFIXES,+ })const typingTimer = useRef<NodeJS.Timeout | null>(null)const [mentionPopup, setMentionPopup] = useState<MentionPopupState>(EMPTY_MENTION_STATE)@@ -301,7 +308,13 @@ export function Composer({ channel, context, members, onSearchMembers, channelReref={fileInputRef}type="file"multiple- accept="image/*,video/*,audio/*,.pdf,.txt,.zip"+ // Mirror `ALLOWED_ATTACHMENT_MIME_PREFIXES` — the server-side+ // allowlist. Keep this list a superset of what the server takes:+ // browsers filter aggressively by extension, so `text/*` alone+ // won't offer `.md`/`.log`/`.json` in the picker. The MIME check+ // in `useFileAttachments` is authoritative; `accept` just biases+ // the picker.+ accept="image/*,video/*,audio/*,application/pdf,text/*,.md,.log,.json,.csv,.yaml,.yml,.ts,.tsx,.js,.jsx"onChange={handleFileSelect}className="hidden"/>diff --git a/src/web/src/components/community/edit-profile-dialog.tsx b/src/web/src/components/community/edit-profile-dialog.tsxindex 95ccdf059..a2c9e8675 100644--- a/src/web/src/components/community/edit-profile-dialog.tsx+++ b/src/web/src/components/community/edit-profile-dialog.tsx@@ -1,13 +1,16 @@"use client"import { useCallback, useEffect, useRef, useState } from "react"-import { User, LogOut, X, Palette, Sun, Moon, Monitor } from "lucide-react"+import { toast } from "sonner"+import { User, LogOut, X, Palette, Sun, Moon, Monitor, Database } from "lucide-react"import { useTheme } from "next-themes"import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { Textarea } from "@/components/ui/textarea"import { Separator } from "@/components/ui/separator"import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"+import { ConfirmDialog } from "@/components/ui/confirm-dialog"+import { clearPersistedCache } from "@/lib/query-persister"import { Field } from "./field"const THEME_OPTIONS = [@@ -51,8 +54,63 @@ function AppearanceSettings() {)}-export function UserSettings({ onClose, userName, aboutMe, onSave, onLogout }: {+// Advanced settings — currently just a "Clear local cache" affordance. Local+// cache = the IndexedDB-persisted TanStack Query blob (message pages ++// read-state snapshots). Rare to need in normal use; useful when a bad build+// leaves the persisted state inconsistent (see 2026-07-09 fetchOlder pollution).+function AdvancedSettings({ userId }: { userId: string | null }) {+ const [confirmOpen, setConfirmOpen] = useState(false)+ const [clearing, setClearing] = useState(false)+ return (+ <>+ <ConfirmDialog+ open={confirmOpen}+ onOpenChange={(o) => { if (!o) setConfirmOpen(false) }}+ title="Clear local cache?"+ description="This removes the locally persisted messages and read-state for your account. The next channel or DM you open will refetch from the server. Your unread state on the server is unaffected."+ confirmLabel="Clear cache"+ loadingLabel="Clearing..."+ loading={clearing}+ onConfirm={async () => {+ setClearing(true)+ try {+ await clearPersistedCache(userId)+ toast("Local cache cleared — reloading")+ // Hard reload so the QueryClient starts fresh without racing an+ // in-flight persister write.+ window.location.reload()+ } catch {+ toast("Failed to clear cache")+ setClearing(false)+ setConfirmOpen(false)+ }+ }}+ />+ <div className="max-w-xl space-y-6">+ <div>+ <div className="text-sm font-medium">Clear local cache</div>+ <p className="mt-1 text-xs text-muted-foreground">+ Removes the locally persisted message history and read-state stored+ in this browser. The next channel or DM you open will refetch from+ the server. Nothing on the server is deleted.+ </p>+ <Button+ variant="destructive"+ size="sm"+ className="mt-3"+ onClick={() => setConfirmOpen(true)}+ >+ Clear local cache+ </Button>+ </div>+ </div>+ </>+ )+}++export function UserSettings({ onClose, userId, userName, aboutMe, onSave, onLogout }: {onClose: () => void+ userId: string | nulluserName: stringaboutMe: stringonSave: (data: { name?: string; aboutMe?: string }) => void@@ -105,6 +163,9 @@ export function UserSettings({ onClose, userName, aboutMe, onSave, onLogout }: {<TabsTrigger value="appearance" className="h-8 w-full justify-start gap-2"><Palette className="size-4" /> Appearance</TabsTrigger>+ <TabsTrigger value="advanced" className="h-8 w-full justify-start gap-2">+ <Database className="size-4" /> Advanced+ </TabsTrigger></TabsList><Separator className="my-1" /><Button variant="ghost" className="justify-start text-destructive hover:text-destructive" size="sm" onClick={onLogout}>@@ -114,7 +175,9 @@ export function UserSettings({ onClose, userName, aboutMe, onSave, onLogout }: {<div className="flex min-w-0 flex-1 flex-col bg-background"><header className="flex h-12 shrink-0 items-center border-b border-border px-4">- <h1 className="flex-1 text-lg font-semibold">{tab === "appearance" ? "Appearance" : "My Profile"}</h1>+ <h1 className="flex-1 text-lg font-semibold">+ {tab === "appearance" ? "Appearance" : tab === "advanced" ? "Advanced" : "My Profile"}+ </h1><button onClick={onClose} className="flex flex-col items-center text-muted-foreground hover:text-foreground" aria-label="Close settings"><span className="grid size-8 place-items-center rounded-full border border-current"><X className="size-4" /></span></button>@@ -133,6 +196,9 @@ export function UserSettings({ onClose, userName, aboutMe, onSave, onLogout }: {<TabsContent value="appearance"><AppearanceSettings /></TabsContent>+ <TabsContent value="advanced">+ <AdvancedSettings userId={userId} />+ </TabsContent></div></div></Tabs>diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxindex 2e73048fe..5ff97a401 100644--- a/src/web/src/components/community/message-list.tsx+++ b/src/web/src/components/community/message-list.tsx@@ -18,6 +18,8 @@ export function MessageList({onToggleReaction, onReact,onReply, onPin, onCreateThread, onCopy, onRetry, onPreviewImage, onDownloadFile,resolveUserName, scrollToMessageId, hero, onScrollRoot, viewerUserId, initialScrollReady = true,+ hasMore, isFetchingOlder, onLoadOlder,+ hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount,}: {channel: stringmessages: Msg[]@@ -56,6 +58,30 @@ export function MessageList({// stale `newDividerBefore = undefined` and snaps to bottom before the// anchor is known.initialScrollReady?: boolean+ // Reverse-infinite scroll. When `hasMore` is true a top sentinel is+ // rendered; when it enters the viewport (via IntersectionObserver on the+ // scroll root) `onLoadOlder()` fires. The prepended rows are scroll-+ // anchored below (see the useLayoutEffect on head-id changes) so the+ // user's visual position stays fixed.+ hasMore?: boolean+ isFetchingOlder?: boolean+ onLoadOlder?: () => void+ // Forward-infinite scroll (bi-directional pagination — A2). When the+ // initial page is an anchor window in the middle of history, the tail is+ // NOT the newest message; a bottom sentinel is rendered until the user+ // scrolls into it to request newer rows. Legacy newest-attached mode+ // leaves `hasMoreNewer` undefined/false — no bottom sentinel.+ hasMoreNewer?: boolean+ isFetchingNewer?: boolean+ onLoadNewer?: () => void+ // `↓ N` pill — when there are messages further ahead than the loaded+ // window, clicking jumps back to the present. Falls back to the DOM+ // `belowCount` scroll-to-bottom when we're already tail-attached.+ onJumpToPresent?: () => void+ // Server-derived unread count (`latestSeq - viewerLastReadSeq`). Drives+ // the `↓ N` badge when `hasMoreNewer` is true — DOM math can't see rows+ // that haven't been fetched yet.+ unreadCount?: number}) {const [jumped, setJumped] = useState<string | null>(null)const scrollRef = useRef<HTMLDivElement>(null)@@ -115,10 +141,23 @@ export function MessageList({`[data-msg-id="${cssEscape(newDividerBefore)}"]`,)if (target) {+ // Compute scrollTop manually rather than use `scrollIntoView({+ // block: "center" })`. The scroll root's content lives inside a+ // `flex justify-end min-h-full` wrapper; some engines interpret+ // `block: "center"` against that wrapper's flex flow rather than+ // the scroll root's viewport, and the row lands at the top of+ // the viewport instead of the middle. Bounding-rect delta works+ // regardless of offsetParent since it's viewport-space math.// Instant, not smooth — same reason as the self-send effect// below: smooth animations race the RO re-pins on some engines// and can snap back to the pre-image target.- action = () => target.scrollIntoView({ block: "center" })+ action = () => {+ const targetRect = target.getBoundingClientRect()+ const scrollRect = el.getBoundingClientRect()+ const targetTopInScroller = targetRect.top - scrollRect.top + el.scrollTop+ const desired = targetTopInScroller - (el.clientHeight - target.offsetHeight) / 2+ el.scrollTop = Math.max(0, desired)+ }} else {action = () => el.scrollTo({ top: el.scrollHeight })}@@ -158,7 +197,34 @@ export function MessageList({if (prev === null) returnif (prev === tail.id) returnif (!viewerUserId) return- if (tail.authorId !== viewerUserId) return++ // Self-send: viewer authored the new tail → always follow. Handles the+ // composer path across image/mermaid/invite-card async growth via the+ // RO re-pin below.+ const isSelfSend = tail.authorId === viewerUserId++ // Peer follow: someone else sent a message AND the viewer is already at+ // (or near) the bottom → snap to the new tail. If the viewer has+ // scrolled up, we leave the "↓ N" pill to prompt them back down.+ //+ // Gated on `hasMoreNewer === false` (i.e. the loaded window is+ // tail-attached to the present) so a peer message WS-inserted while+ // the viewer is browsing history doesn't yank the view to a message+ // that isn't actually "now". The pill's jump-to-present covers that+ // case.+ let isPeerFollow = false+ if (!isSelfSend) {+ if (hasMoreNewer) return+ const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight+ // 100px window matches the pill's "near bottom" intuition — noise+ // (anti-aliasing, sub-pixel layout) is well below one line height,+ // and a scrolled-up reader is typically many lines above.+ if (distanceFromBottom >= 100) return+ isPeerFollow = true+ }++ if (!isSelfSend && !isPeerFollow) return+// Instant, not smooth. `behavior: 'smooth'` conflicts with the RO// re-pins below — the browser's ongoing smooth animation and our// subsequent instant scrollTo race, and on some engines the smooth@@ -167,7 +233,128 @@ export function MessageList({const action = () => el.scrollTo({ top: el.scrollHeight })action()return watchAsyncGrowth(el, action)- }, [messages, viewerUserId])+ }, [messages, viewerUserId, hasMoreNewer])++ // Reverse-infinite scroll anchor. When older messages prepend (head id+ // changes but tail id stays put), the browser's default is to keep+ // `scrollTop` constant, which visually shoves the user's current row down+ // by the height of the newly-inserted content. We snapshot the pre-commit+ // `scrollHeight` before the messages array updates and, once the DOM+ // reflects the new rows, add the height delta to `scrollTop` so the+ // user's current view stays fixed.+ //+ // Also handles the `hasMore` transition true → false: when a fetchOlder+ // reaches start-of-history the ~32px top sentinel is replaced by the+ // ~120px hero card. `messages` may not have grown at all (start-of-+ // history sometimes returns 0 rows), but the top block gained ~90px and+ // every row below it visibly shifts down. Snapshotting `scrollHeight`+ // across the flip and adding the positive delta pins the viewer's row.+ //+ // Only fires after the mount-time initial scroll has landed+ // (`didInitialScrollRef.current === true`) — otherwise we'd fight the+ // one-shot snap on first mount. Skipped when the tail id changed (that's+ // a self-send or a peer send, handled elsewhere) or when `messages`+ // shrank (channel switch, handled by the length===0 reset above).+ const prevHeadIdRef = useRef<string | null>(null)+ const prevTailIdRef = useRef<string | null>(null)+ const prevScrollHeightRef = useRef<number>(0)+ const prevMessagesLenRef = useRef<number>(0)+ const prevHasMoreRef = useRef<boolean | undefined>(hasMore)+ useLayoutEffect(() => {+ const el = scrollRef.current+ if (!el) {+ prevHeadIdRef.current = messages[0]?.id ?? null+ prevTailIdRef.current = messages[messages.length - 1]?.id ?? null+ prevMessagesLenRef.current = messages.length+ prevScrollHeightRef.current = 0+ prevHasMoreRef.current = hasMore+ return+ }+ const prevHead = prevHeadIdRef.current+ const prevTail = prevTailIdRef.current+ const prevLen = prevMessagesLenRef.current+ const prevHeight = prevScrollHeightRef.current+ const prevHasMore = prevHasMoreRef.current+ const nextHead = messages[0]?.id ?? null+ const nextTail = messages[messages.length - 1]?.id ?? null+ const nextLen = messages.length+ const nextHeight = el.scrollHeight++ const olderPrepended =+ prevHead !== null &&+ nextHead !== null &&+ prevHead !== nextHead &&+ nextLen > prevLen+ // Hero swap: `hasMore` flipped true → false while the tail stayed put.+ // Even when 0 rows landed on the last page, the top block grew from+ // sentinel to hero and everything below shifted down.+ const heroSwap =+ prevHasMore === true &&+ hasMore === false &&+ prevTail !== null &&+ prevTail === nextTail++ if (+ didInitialScrollRef.current &&+ prevHeight > 0 &&+ (olderPrepended || heroSwap)+ ) {+ const delta = nextHeight - prevHeight+ if (delta > 0) el.scrollTop = el.scrollTop + delta+ }++ prevHeadIdRef.current = nextHead+ prevTailIdRef.current = nextTail+ prevMessagesLenRef.current = nextLen+ prevScrollHeightRef.current = nextHeight+ prevHasMoreRef.current = hasMore+ }, [messages, hasMore])++ // Top sentinel — when it intersects the scroll root's viewport, request the+ // next older page. Mirrors the pattern in member-list.tsx: root is the+ // scroll container (NOT the page viewport), rootMargin `200px` so the+ // fetch kicks in before the user hits the true edge.+ const topSentinelRef = useRef<HTMLDivElement>(null)+ useEffect(() => {+ if (!onLoadOlder || !hasMore) return+ const el = topSentinelRef.current+ const root = scrollRef.current+ if (!el || !root) return+ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting && !isFetchingOlder) onLoadOlder()+ }+ },+ { root, rootMargin: "200px" },+ )+ observer.observe(el)+ return () => observer.disconnect()+ }, [onLoadOlder, hasMore, isFetchingOlder])++ // Bottom sentinel — symmetric to the top one. Only mounted when the loaded+ // window is not tail-attached (`hasMoreNewer === true`). Appended rows from+ // a newer-fetch prepend to `pages[0]` in cache order → after the sort in+ // `mergeMessagesPages` they land at the natural tail of `messages`, which+ // grows the container downward and leaves the viewer's scrollTop untouched.+ // No compensating scroll needed.+ const bottomSentinelRef = useRef<HTMLDivElement>(null)+ useEffect(() => {+ if (!onLoadNewer || !hasMoreNewer) return+ const el = bottomSentinelRef.current+ const root = scrollRef.current+ if (!el || !root) return+ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting && !isFetchingNewer) onLoadNewer()+ }+ },+ { root, rootMargin: "200px" },+ )+ observer.observe(el)+ return () => observer.disconnect()+ }, [onLoadNewer, hasMoreNewer, isFetchingNewer])// Live count of messages sitting below the viewport. Recomputed on scroll,// on messages change, and via a ResizeObserver so appended rows update the@@ -250,26 +437,58 @@ export function MessageList({// All hooks must run before any conditional return — rule-of-hooks.if (loading && messages.length === 0) return <MessageListSkeleton dm={!!hero} />+ // ↓ N pill precedence:+ // - When there are messages the client hasn't fetched yet+ // (`hasMoreNewer`), show the server-derived `unreadCount` (may be+ // larger than the DOM `belowCount`) and click → `onJumpToPresent`+ // resets the query to newest, cutting out multi-RTT page walks.+ // - Otherwise fall back to `belowCount` and `scrollToBottom` — the+ // tail-attached path unchanged from pre-A2.+ const jumpMode = !!hasMoreNewer+ const pillCount = jumpMode+ ? ((unreadCount ?? belowCount) || 0)+ : belowCount+ const pillOnClick = jumpMode+ ? (onJumpToPresent ?? scrollToBottom)+ : scrollToBottom+return (<div className="relative flex min-h-0 flex-1 flex-col"><ScrollDownButton- count={belowCount}- onClick={scrollToBottom}+ count={pillCount}+ mode={jumpMode ? "jump" : "scroll"}+ onClick={pillOnClick}/><TypingIndicator names={typingUsers ?? []} /><div ref={scrollRef} className="flex-1 overflow-y-auto thin-scrollbar"><div className="flex min-h-full flex-col justify-end px-4 py-8">- <div className="mb-6">- {hero ?? (- <>- <div className="mb-2 grid size-12 place-items-center rounded-full bg-muted/60">- <ChannelIcon className="text-xl text-muted-foreground" />- </div>- <h2 className="text-xl font-semibold leading-tight">{channel}</h2>- <p className="mt-2 text-sm text-muted-foreground">Beginning of the channel. Say hello, share what you're working on, or drop a link.</p>- </>- )}- </div>+ {/*+ When `hasMore` is true the hero's "Beginning of …" copy would+ lie — there's more history above — so we swap it for the top+ sentinel + inline "Loading older messages…" indicator. Once+ the last page loads (`hasMore === false`) the hero returns+ and reads as "you've reached the top".+ */}+ {hasMore ? (+ <div+ ref={topSentinelRef}+ className="mb-6 flex h-8 items-center justify-center text-xs text-muted-foreground"+ >+ {isFetchingOlder ? "Loading older messages…" : ""}+ </div>+ ) : (+ <div className="mb-6">+ {hero ?? (+ <>+ <div className="mb-2 grid size-12 place-items-center rounded-full bg-muted/60">+ <ChannelIcon className="text-xl text-muted-foreground" />+ </div>+ <h2 className="text-xl font-semibold leading-tight">{channel}</h2>+ <p className="mt-2 text-sm text-muted-foreground">Beginning of the channel. Say hello, share what you're working on, or drop a link.</p>+ </>+ )}+ </div>+ )}{clusters.map((cluster, ci) => (<div key={cluster.messages[0].m.id ?? ci}>@@ -304,6 +523,15 @@ export function MessageList({</div>))}+ {hasMoreNewer && (+ <div+ ref={bottomSentinelRef}+ className="mt-6 flex h-8 items-center justify-center text-xs text-muted-foreground"+ >+ {isFetchingNewer ? "Loading newer messages…" : ""}+ </div>+ )}+</div></div></div>@@ -392,8 +620,23 @@ function cssEscape(id: string): string {// are still messages below the viewport. `count === 0` hides the button// entirely (fade + slide-down, matches the shared scroll-to-bottom pill's// visual language).-function ScrollDownButton({ count, onClick }: { count: number; onClick: () => void }) {+//+// `mode="jump"` — the loaded window is not tail-attached (bi-directional+// pagination has more newer rows to fetch); click jumps to present rather+// than a plain scroll. `mode="scroll"` — legacy tail-attached path.+function ScrollDownButton({+ count,+ mode = "scroll",+ onClick,+}: {+ count: number+ mode?: "scroll" | "jump"+ onClick: () => void+}) {const visible = count > 0+ const aria = mode === "jump"+ ? `Jump to present, ${count} unread below`+ : `Scroll to bottom, ${count} more below`return (<divclassName={`pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 transition-all duration-200 ease-out ${@@ -403,7 +646,7 @@ function ScrollDownButton({ count, onClick }: { count: number; onClick: () => vo<buttontype="button"onClick={onClick}- aria-label={`Scroll to bottom, ${count} more below`}+ aria-label={aria}className={`pointer-events-auto flex h-8 items-center gap-1.5 rounded-full border border-border bg-background/90 pl-2 pr-3 text-xs font-medium text-foreground shadow-(--e1) backdrop-blur-sm transition-colors hover:bg-accent ${visible ? "" : "pointer-events-none"}`}diff --git a/src/web/src/components/community/message-markdown.test.ts b/src/web/src/components/community/message-markdown.test.tsindex 0d4c1091f..46a90942c 100644--- a/src/web/src/components/community/message-markdown.test.ts+++ b/src/web/src/components/community/message-markdown.test.ts@@ -58,6 +58,27 @@ describe("preprocessMarkdown", () => {expect(preprocessMarkdown("text/studio/general")).toBe("text/studio/general")})+ it("does NOT wrap a 3+-segment docs-style path — trailing `/segment` fails the terminator boundary", () => {+ // Regression guard: `CHANNEL_REF_REGEX` used to greedily eat `/api/user`+ // out of a docs URL, orphaning `/123` as broken trailing text next to a+ // muted pill. The trailing boundary lookahead rejects this — a real+ // 2-segment ref must sit alone (space, EOS, or punctuation after it).+ expect(preprocessMarkdown("look at /api/user/123")).toBe("look at /api/user/123")+ expect(preprocessMarkdown("hit /docs/api/v1 first")).toBe("hit /docs/api/v1 first")+ })++ it("still wraps a 2-segment ref followed by punctuation (period, comma, close-paren)", () => {+ expect(preprocessMarkdown("see /studio/general.")).toBe(+ "see <channelref>/studio/general</channelref>.",+ )+ expect(preprocessMarkdown("visit /studio/general, ok?")).toBe(+ "visit <channelref>/studio/general</channelref>, ok?",+ )+ expect(preprocessMarkdown("(see /studio/general)")).toBe(+ "(see <channelref>/studio/general</channelref>)",+ )+ })+it("wraps the thread form /studio/general/#42", () => {expect(preprocessMarkdown("see /studio/general/#42")).toBe("see <channelref>/studio/general/#42</channelref>",diff --git a/src/web/src/components/community/message-markdown.tsx b/src/web/src/components/community/message-markdown.tsxindex 0869f2297..65b5ad167 100644--- a/src/web/src/components/community/message-markdown.tsx+++ b/src/web/src/components/community/message-markdown.tsx@@ -10,7 +10,13 @@ import { ChannelRefPill } from "./channel-ref-pill"// spaces/punctuation can't round-trip through this regex (same limitation the// legacy `#channel-name` chip had). The pinned-message form (`#N` directly, no// slash) is intentionally not matched — see plan §1 for why.-const CHANNEL_REF_REGEX = /(^|\s)(\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+)?)/g+//+// Trailing `(?=\s|$|[.,;:!?)\]])` boundary lookahead: a 2-segment path+// followed by ANOTHER `/segment` (e.g. `/api/user/123` in a docs URL) must+// NOT match — otherwise CHANNEL_REF_REGEX greedily takes `/api/user` and+// orphans `/123` as trailing text next to a broken pill. Requiring a+// terminator forces the match to sit ONLY on a real leaf ref.+const CHANNEL_REF_REGEX = /(^|\s)(\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+(?:\/#\d+)?)(?=\s|$|[.,;:!?)\]])/g// Sentinels for stashing code spans/fences (private-use chars — won't collide with// real text or markdown punctuation).diff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/server-rail.tsxindex 3b8e5f135..289a24a85 100644--- a/src/web/src/components/community/server-rail.tsx+++ b/src/web/src/components/community/server-rail.tsx@@ -18,7 +18,7 @@ import { serverGradient } from "./server-gradient"import type { Server, CommunityFolder, MobileZone, View } from "./_types"export const ServerRail = memo(function ServerRail({- servers, folders, activeServerId: activeServerIdProp, serversLoading, setMobileZone, view, bottomInset,+ servers, folders, activeServerId: activeServerIdProp, serversLoading, serversReady, setMobileZone, view, bottomInset,onHome, onServer, onServerNavigate, onCreateServer, onJoinServer, onLeaveServer,onOpenSettings, onOpenInvitePopover, onUngroupFolder, onReorderRail, onReorderFolders, onFolderItemsChange, onDragCreateFolder,}: {@@ -26,6 +26,13 @@ export const ServerRail = memo(function ServerRail({folders: CommunityFolder[]activeServerId?: stringserversLoading?: boolean+ // Auto-open the "Create a Server" dialog when the user genuinely has no+ // servers — gated on `serversReady` (query has completed at least one+ // fetch AND isn't refetching) instead of `!serversLoading`. TanStack v5+ // `isLoading` is only true on the very first fetch, so any subsequent+ // invalidate (WS `member.leave`, reconnect) briefly flips servers=[] with+ // `isLoading=false`, which would re-trigger the dialog mid-session.+ serversReady?: booleansetMobileZone?: (z: MobileZone) => voidview: ViewbottomInset?: number@@ -69,11 +76,16 @@ export const ServerRail = memo(function ServerRail({const [createOpen, setCreateOpen] = useState(false)const [didAutoOpen, setDidAutoOpen] = useState(false)useEffect(() => {- if (!didAutoOpen && servers.length === 0 && folders.length === 0 && serversLoading === false) {+ // Only fire when the servers query has genuinely settled (fetched at+ // least once AND not currently refetching). `serversLoading` (from+ // TanStack `isLoading`) is only true on the very first fetch, so it+ // false-triggers on any subsequent cache invalidate where the servers+ // list is transiently empty. `serversReady` is `isFetched && !isFetching`.+ if (!didAutoOpen && serversReady && servers.length === 0 && folders.length === 0) {setDidAutoOpen(true)setCreateOpen(true)}- }, [servers.length, folders.length, serversLoading, didAutoOpen])+ }, [servers.length, folders.length, serversReady, didAutoOpen])const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))const pickServer = (id: string) => { setActiveId(id); onServer(); onServerNavigate?.(id); setMobileZone?.("nav") }diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 6488d8d1f..d5941312c 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -20,6 +20,7 @@ import { ProfileCard } from "./profile-card"import { ImageLightbox } from "./image-lightbox"import type { MobileZone, Profile, View } from "./_types"import { signOut } from "@/lib/auth-client"+import { clearPersistedCache } from "@/lib/query-persister"import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"import { useCurrentUser, useSetCurrentUser } from "@/contexts/community/current-user"@@ -98,6 +99,7 @@ export function ShellFrame({const inboxUnreads = useInboxUnreads()const inboxMentions = useInboxMentions()const unreadFeed = inboxUnreads.servers+ const unreadDms = inboxUnreads.dmsconst mentions = inboxMentions.mentionsconst inboxLoading = inboxUnreads.isLoading || inboxMentions.isLoading@@ -254,6 +256,11 @@ export function ShellFrame({folders,activeServerId,serversLoading: serversQuery.isLoading,+ // `serversReady` gates the ServerRail auto-open — true only after the+ // very first fetch settles AND the query isn't refetching. Using+ // `isLoading` alone would let post-invalidate races (WS member.leave,+ // reconnect) with `servers=[]` re-fire the "Create a Server" dialog.+ serversReady: serversQuery.isFetched && !serversQuery.isFetching,setMobileZone,view,onHome: goHome,@@ -407,12 +414,34 @@ export function ShellFrame({[router],)+ const openInboxDm = useCallback(+ (dmId: string) => {+ // Mirrors the DM sidebar's `enterDm` (see app/community/me/layout.tsx):+ // client-only optimistic clear on `communityKeys.dms()` — no eager+ // mark-read PUT. Eagerly aligning the read pointer to the tail here+ // would resolve the DM's read-state snapshot at tail on mount and+ // suppress the NEW divider. The DM page's IntersectionObserver+ // (`useDmWatermark`) is authoritative for advancing the server pointer.+ queryClient.setQueryData(+ communityKeys.dms(),+ (prev: { conversations: { id: string; unread?: boolean }[] } | undefined) =>+ prev+ ? { ...prev, conversations: prev.conversations.map((d) => (d.id === dmId ? { ...d, unread: false } : d)) }+ : prev,+ )+ router.push(`/community/me/${dmId}`)+ },+ [router, queryClient],+ )+const inboxElement = (<InboxPopoverunreads={unreadFeed}+ unreadDms={unreadDms}mentions={mentions}loading={inboxLoading}onOpenChannel={openServerChannel}+ onOpenDm={openInboxDm}onOpenMention={(mention) => {if (mention.serverId && mention.channelId) openServerChannel(mention.serverId, mention.channelId)}}@@ -421,13 +450,14 @@ export function ShellFrame({/>)const inboxHasUnread =- (unreadFeed?.length ?? 0) > 0 || (mentions?.length ?? 0) > 0+ (unreadFeed?.length ?? 0) > 0 || (unreadDms?.length ?? 0) > 0 || (mentions?.length ?? 0) > 0const userSettingsDialog = (<Dialog open={editingProfile} onOpenChange={(o) => { if (!o) setEditingProfile(false) }}><DialogContent className="flex h-[calc(100vh-4rem)] w-[calc(100vw-4rem)] sm:max-w-none flex-col gap-0 overflow-hidden rounded-xl p-0" showCloseButton={false}><UserSettingsonClose={() => setEditingProfile(false)}+ userId={currentUser.id}userName={currentUser.name}aboutMe={currentUser.aboutMe ?? ""}onSave={async (data) => {@@ -448,6 +478,9 @@ export function ShellFrame({// the debounce window — covers every sign-out path uniformly.useCommunityStore.getState().reset()useCommunityWsStore.getState().reset()+ // Drop the persisted IDB blob so the next user on this machine+ // doesn't see the previous session's cached message rows.+ await clearPersistedCache(currentUser.id).catch(() => {})await signOut()router.push("/sign-in")}}diff --git a/src/web/src/components/nav-user.tsx b/src/web/src/components/nav-user.tsxindex f2227be65..187ed0cd4 100644--- a/src/web/src/components/nav-user.tsx+++ b/src/web/src/components/nav-user.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";import { useRouter } from "next/navigation";import { useSession, signOut } from "@/lib/auth-client";import { clearAllCache } from "@/lib/chat-cache";+import { clearPersistedCache } from "@/lib/query-persister";import { useCommunityStore } from "@/stores/community";import { useCommunityWsStore } from "@/stores/community/ws";import {@@ -78,6 +79,9 @@ export function NavUser() {useCommunityStore.getState().reset();useCommunityWsStore.getState().reset();await clearAllCache();+ // Drop the persisted IDB blob so the next user on this machine+ // doesn't inherit the previous session's cached message rows.+ await clearPersistedCache(user.id).catch(() => {});await signOut();router.push("/sign-in");}}diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex c0577a43c..13d85695a 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -148,8 +148,55 @@ describe("useSendMessage — rollback", () => {})})+// Regression pin — the mount-time effect in <MessageList> gates self-send+// auto-scroll on `tail.authorId === viewerUserId`. A missing `authorId` on+// the optimistic row silently disables that scroll, so pin the field on+// BOTH the channel and DM optimistic paths.+describe("useSendMessage — stamps authorId on optimistic row", () => {+ it("optimistic row carries the sender's authorId", async () => {+ capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))+ // Never resolves — we only care about the optimistic write from onMutate.+ apiFetchMock.mockImplementation(() => new Promise(() => {}))+ const mod = await loadMod()+ mod.useSendMessage()+ const cfg = capturedConfig!+ await cfg.onMutate!({+ channelId: "ch_1",+ content: "hi",+ author: { id: "u_me", name: "me", avatar: "M" },+ })+ const cache = capturedQc.getQueryData<{ pages: { messages: { authorId?: string }[] }[] }>(+ communityKeys.channelMessages("ch_1"),+ )+ expect(cache?.pages[0].messages).toHaveLength(1)+ expect(cache?.pages[0].messages[0].authorId).toBe("u_me")+ })+})+// ── useSendDmMessage ──────────────────────────────────────────────────────+describe("useSendDmMessage — stamps authorId on optimistic row", () => {+ // Companion regression: without authorId the self-send auto-scroll bails+ // in <MessageList> because `undefined !== viewerUserId`. Pin the field.+ it("optimistic DM row carries the sender's authorId", async () => {+ capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))+ apiFetchMock.mockImplementation(() => new Promise(() => {}))+ const mod = await loadMod()+ mod.useSendDmMessage()+ const cfg = capturedConfig!+ await cfg.onMutate!({+ dmId: "dm_1",+ content: "hi",+ author: { id: "u_me", name: "me", avatar: "M" },+ })+ const cache = capturedQc.getQueryData<{ pages: { messages: { authorId?: string }[] }[] }>(+ communityKeys.dmMessages("dm_1"),+ )+ expect(cache?.pages[0].messages).toHaveLength(1)+ expect(cache?.pages[0].messages[0].authorId).toBe("u_me")+ })+})+describe("useSendDmMessage — rollback", () => {it("marks the temp DM row failed on server failure", async () => {capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))@@ -210,6 +257,50 @@ describe("useSendDmMessage — 403 blocked special-case", () => {})})+// 429 rate-limit toasts on both channel and DM send paths — the pill stays+// as `failed: true` so the retry affordance is still visible, but a toast+// fires so the user knows why the send didn't go through.+describe("useSendMessage — 429 rate limit fires a toast + marks failed", () => {+ it("channel 429: toast fires and row is marked failed:true", async () => {+ capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))+ const mod = await loadMod()+ const { ApiError } = await import("@/lib/errors")+ apiFetchMock.mockRejectedValueOnce(new ApiError("rate_limited", 429))+ mod.useSendMessage()+ await runMutation({+ channelId: "ch_1",+ content: "hi",+ author: { id: "u_me", name: "me", avatar: "M" },+ }).catch(() => {})+ const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(+ communityKeys.channelMessages("ch_1"),+ )+ expect(cache?.pages[0].messages[0].failed).toBe(true)+ expect(toastMock).toHaveBeenCalledWith(expect.stringContaining("Rate limited"))+ })+})++describe("useSendDmMessage — 429 rate limit fires a toast + marks failed", () => {+ it("DM 429: toast fires and row is marked failed:true (not scrubbed like 403 blocked)", async () => {+ capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))+ const mod = await loadMod()+ const { ApiError } = await import("@/lib/errors")+ apiFetchMock.mockRejectedValueOnce(new ApiError("rate_limited", 429))+ mod.useSendDmMessage()+ await runMutation({+ dmId: "dm_1",+ content: "hi",+ author: { id: "u_me", name: "me", avatar: "M" },+ }).catch(() => {})+ const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(+ communityKeys.dmMessages("dm_1"),+ )+ expect(cache?.pages[0].messages).toHaveLength(1)+ expect(cache?.pages[0].messages[0].failed).toBe(true)+ expect(toastMock).toHaveBeenCalledWith(expect.stringContaining("Rate limited"))+ })+})+// Regression guard — channel path stays generic-error, never fires the blocked// toast even on 403 blocked (that shouldn't happen on channels; ensure the// hook doesn't accidentally add DM's onBlocked branch to `useSendMessage`).@@ -611,7 +702,7 @@ describe("useMarkChannelRead — #13 debounced read stampede", () => {// ── scheduleMarkRead — extended signature (with messageId body) ──────────describe("scheduleMarkRead — with messageId body", () => {- it("posts { lastMessageId } when a messageId is passed", async () => {+ it("posts { lastReadMessageId } when a messageId is passed", async () => {vi.useFakeTimers()try {apiFetchMock.mockResolvedValue(undefined)@@ -623,7 +714,7 @@ describe("scheduleMarkRead — with messageId body", () => {(c) => (c[1] as { method?: string })?.method === "PUT",)expect(put).toBeDefined()- expect((put![1] as RequestInit).body).toBe(JSON.stringify({ lastMessageId: "m_42" }))+ expect((put![1] as RequestInit).body).toBe(JSON.stringify({ lastReadMessageId: "m_42" }))} finally {vi.useRealTimers()}@@ -643,7 +734,7 @@ describe("scheduleMarkRead — with messageId body", () => {(c) => (c[1] as { method?: string })?.method === "PUT",)expect(puts).toHaveLength(1)- expect((puts[0][1] as RequestInit).body).toBe(JSON.stringify({ lastMessageId: "m_fresh" }))+ expect((puts[0][1] as RequestInit).body).toBe(JSON.stringify({ lastReadMessageId: "m_fresh" }))} finally {vi.useRealTimers()}@@ -669,7 +760,7 @@ describe("scheduleMarkRead — with messageId body", () => {// ── useAdvanceChannelWatermark — thin wrapper for viewport advances ─────describe("useAdvanceChannelWatermark", () => {- it("returns a callable that PUTs { lastMessageId } after the debounce", async () => {+ it("returns a callable that PUTs { lastReadMessageId } after the debounce", async () => {vi.useFakeTimers()try {apiFetchMock.mockResolvedValue(undefined)@@ -683,7 +774,7 @@ describe("useAdvanceChannelWatermark", () => {)expect(put).toBeDefined()expect((put![0] as string)).toBe("/api/community/channels/ch_1/read")- expect((put![1] as RequestInit).body).toBe(JSON.stringify({ lastMessageId: "m_42" }))+ expect((put![1] as RequestInit).body).toBe(JSON.stringify({ lastReadMessageId: "m_42" }))} finally {vi.useRealTimers()}@@ -713,6 +804,90 @@ describe("useAdvanceChannelWatermark", () => {})})+// ── useAdvanceDmWatermark — DM sibling of the channel wrapper ───────────+describe("useAdvanceDmWatermark", () => {+ it("returns a callable that PUTs { lastReadMessageId } to the DM read route", async () => {+ vi.useFakeTimers()+ try {+ apiFetchMock.mockResolvedValue(undefined)+ const mod = await loadMod()+ mod._resetPendingReads_forTesting()+ const advance = mod.useAdvanceDmWatermark()+ advance("dm_1", "m_42")+ await vi.advanceTimersByTimeAsync(500)+ const put = apiFetchMock.mock.calls.find(+ (c) => (c[1] as { method?: string })?.method === "PUT",+ )+ expect(put).toBeDefined()+ expect(put![0] as string).toBe("/api/community/dm/dm_1/read")+ expect((put![1] as RequestInit).body).toBe(+ JSON.stringify({ lastReadMessageId: "m_42" }),+ )+ } finally {+ vi.useRealTimers()+ }+ })++ it("DM and channel schedules share the debounce map but don't alias each other", async () => {+ // Regression: the "dm:<id>" namespace makes a DM schedule and a+ // channel schedule with the same underlying id coexist in the same+ // pendingReads map. If they aliased, one would clobber the other's+ // pointer and one of the two PUTs would go missing.+ vi.useFakeTimers()+ try {+ apiFetchMock.mockResolvedValue(undefined)+ const mod = await loadMod()+ mod._resetPendingReads_forTesting()+ const advanceDm = mod.useAdvanceDmWatermark()+ const advanceCh = mod.useAdvanceChannelWatermark()+ // Same underlying id `x` — one DM, one channel.+ advanceDm("x", "m_dm")+ advanceCh("x", "m_ch")+ await vi.advanceTimersByTimeAsync(500)+ const puts = apiFetchMock.mock.calls.filter(+ (c) => (c[1] as { method?: string })?.method === "PUT",+ )+ expect(puts).toHaveLength(2)+ const dmPut = puts.find((c) => (c[0] as string).startsWith("/api/community/dm/"))+ const chPut = puts.find((c) =>+ (c[0] as string).startsWith("/api/community/channels/"),+ )+ expect(dmPut).toBeDefined()+ expect(chPut).toBeDefined()+ expect((dmPut![1] as RequestInit).body).toBe(+ JSON.stringify({ lastReadMessageId: "m_dm" }),+ )+ expect((chPut![1] as RequestInit).body).toBe(+ JSON.stringify({ lastReadMessageId: "m_ch" }),+ )+ } finally {+ vi.useRealTimers()+ }+ })++ it("onDone invalidates inbox + dms after the PUT resolves", async () => {+ apiFetchMock.mockResolvedValue(undefined)+ const mod = await loadMod()+ mod._resetPendingReads_forTesting()+ const advance = mod.useAdvanceDmWatermark()+ const spy = vi.spyOn(capturedQc, "invalidateQueries")+ advance("dm_1", "m_42")+ mod.flushPendingReads()+ await Promise.resolve()+ await Promise.resolve()+ const inboxCalls = spy.mock.calls.filter((c) => {+ const key = c[0]?.queryKey as unknown[] | undefined+ return Array.isArray(key) && key.includes("inbox")+ })+ const dmsCalls = spy.mock.calls.filter((c) => {+ const key = c[0]?.queryKey as unknown[] | undefined+ return Array.isArray(key) && key.length === 2 && key[1] === "dms"+ })+ expect(inboxCalls.length).toBeGreaterThanOrEqual(1)+ expect(dmsCalls.length).toBeGreaterThanOrEqual(1)+ })+})+// ── useMarkDmRead — rollback ──────────────────────────────────────────────describe("useMarkDmRead — rollback", () => {@@ -763,7 +938,7 @@ describe("useMarkAllInboxRead", () => {const mod = await loadMod()mod.useMarkAllInboxRead()await runMutation<void>(undefined as unknown as void)- expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual({ servers: [] })+ expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual({ servers: [], dms: [] })expect(capturedQc.getQueryData(communityKeys.inboxMentions())).toEqual({ mentions: [] })})diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 14f36b453..a8d0e11f5 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -216,8 +216,15 @@ export function useSendMessage() {queryClient.setQueryData<PageCache>(key, (c) => prependOptimistic(c, msg))return { tempId, key }},- onError: (_err, _args, ctx) => {+ onError: (err, _args, ctx) => {if (!ctx) return+ // 429: server-side rate limit. Fire an explicit toast so the user+ // knows why the send failed — otherwise the only signal is a+ // `failed: true` pill, which reads like a generic error. The row+ // still gets marked failed so the retry affordance stays available.+ if (err instanceof ApiError && err.status === 429) {+ toast.error("Rate limited — please wait a moment before trying again")+ }queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.channelMessages>, (c) =>markFailedById(c, ctx.tempId),)@@ -265,6 +272,11 @@ export function useSendDmMessage() {const optimisticAttachments = args.attachments?.map(toAttachmentVm)const msg: Msg = {id: tempId,+ // Mirror the channel path: stamp the sender's userId so the+ // self-send auto-scroll effect in <MessageList> (gated on+ // `tail.authorId === viewerUserId`) recognizes the optimistic row+ // as viewer-authored and pins to bottom on send.+ authorId: args.author.id,authorName: args.author.name,authorAvatar: args.author.avatar,content: args.content,@@ -287,6 +299,12 @@ export function useSendDmMessage() {toast("You cannot send messages to this user")return}+ // 429: server-side rate limit. Fire a scoped toast so the user knows+ // the send was throttled; still mark the row `failed: true` so the+ // retry pill is available (mirrors the channel path).+ if (err instanceof ApiError && err.status === 429) {+ toast.error("Rate limited — please wait a moment before trying again")+ }queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.dmMessages>, (c) =>markFailedById(c, ctx.tempId),)@@ -652,27 +670,53 @@ export function flushPendingReads() {export type ScheduleMarkReadOpts = {/**- * When set, PUT `{ lastMessageId }` — advances the read pointer to that- * message's `(createdAt, id)`. Omit for the mass mark-read case (no body).- * The mutation layer trusts whatever value the caller passes most- * recently; monotonicity is the caller's responsibility (see- * `useChannelWatermark`).+ * When set, PUT `{ lastReadMessageId }` — advances the read pointer to+ * that message's `(createdAt, id)`. Omit for the mass mark-read case+ * (no body). The mutation layer trusts whatever value the caller passes+ * most recently; monotonicity is the caller's responsibility (see+ * `useChannelWatermark` / `useDmWatermark`). Body key matches the DM ++ * thread read routes.*/messageId?: stringonDone: () => void}/**- * Debounce a mark-channel-read PUT. Same-channel re-invokes within the- * 500ms window replace the pending intent (previous `messageId` and- * `onDone` are dropped; the new pair takes over). Nothing is left "hanging"- * because `mutationFn` no longer awaits the debounced work.+ * Resolve a schedule key to a target read-endpoint URL. The debounce key+ * is a string namespace so `channelId` and `dm:<dmId>` coexist in the same+ * `pendingReads` map without ever aliasing each other — a channel and a+ * DM with the same underlying id would otherwise share a debounce slot+ * and clobber each other's pointers.+ *+ * Channel keys are bare ids (legacy — the debounce was channel-only+ * before B2). DM keys are prefixed with `"dm:"` so the map stays keyed by+ * unique strings without a discriminated-union tag on `PendingRead`.+ */+function resolveReadEndpoint(key: string): string {+ if (key.startsWith("dm:")) {+ const dmId = key.slice(3)+ return `/api/community/dm/${dmId}/read`+ }+ return `/api/community/channels/${key}/read`+}++/**+ * Debounce a mark-read PUT. Same-key re-invokes within the 500ms window+ * replace the pending intent (previous `messageId` and `onDone` are+ * dropped; the new pair takes over). Nothing is left "hanging" because+ * `mutationFn` no longer awaits the debounced work.+ *+ * `key` is a string namespace: a bare `channelId` for channel/thread reads+ * (legacy contract — every existing call site passes a channel id+ * directly) or `"dm:<dmId>"` for DM reads. `resolveReadEndpoint` maps the+ * key back to the target URL. Consumers should never build the DM+ * namespace directly — call `useAdvanceDmWatermark` which handles it.*/export function scheduleMarkRead(- channelId: string,+ key: string,opts: ScheduleMarkReadOpts,): void {- const existing = pendingReads.get(channelId)+ const existing = pendingReads.get(key)if (existing) clearTimeout(existing.timer)// `entry` is captured inside `fire` so it can read the freshest// `messageId` at the moment the PUT actually issues — even if a later@@ -687,16 +731,16 @@ export function scheduleMarkRead(// scheduling replaced us), do nothing. This is what makes it safe for// both the timer AND `flushPendingReads()` to call `fire` in the same// tick — only the first wins.- const cur = pendingReads.get(channelId)+ const cur = pendingReads.get(key)if (cur !== entry) return- pendingReads.delete(channelId)+ pendingReads.delete(key)const body = entry.messageId- ? JSON.stringify({ lastMessageId: entry.messageId })+ ? JSON.stringify({ lastReadMessageId: entry.messageId }): undefinedconst init: RequestInit = body? { method: "PUT", body }: { method: "PUT" }- void apiFetch(`/api/community/channels/${channelId}/read`, init)+ void apiFetch(resolveReadEndpoint(key), init).then(() => opts.onDone()).catch(() => {// Silent — the inbox will reconcile once the WS invalidate fires.@@ -704,7 +748,7 @@ export function scheduleMarkRead(},}entry.timer = setTimeout(entry.fire, MARK_CHANNEL_READ_DEBOUNCE_MS)- pendingReads.set(channelId, entry)+ pendingReads.set(key, entry)}export type MarkChannelReadArgs = { channelId: string }@@ -802,6 +846,36 @@ export function useAdvanceChannelWatermark(): (}}+// ── Advance DM watermark (progressive read) ───────────────────────────────++/**+ * DM sibling of `useAdvanceChannelWatermark` — a thin wrapper that PUTs+ * `{ lastReadMessageId }` to `/api/community/dm/:id/read`. Same debounce+ * primitive underneath (`scheduleMarkRead`), keyed by `"dm:<dmId>"` so+ * DM and channel schedules never alias each other in the shared pending+ * map.+ *+ * Invalidations: `communityKeys.inbox()` for the top-of-app unread badge+ * and `communityKeys.dms()` for the sidebar DM list (its `unread`+ * flag). No `servers()` invalidate — DMs don't feed the server-rail+ * badge.+ */+export function useAdvanceDmWatermark(): (+ dmId: string,+ messageId: string,+) => void {+ const queryClient = useQueryClient()+ return (dmId, messageId) => {+ scheduleMarkRead(`dm:${dmId}`, {+ messageId,+ onDone: () => {+ void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })+ },+ })+ }+}+// ── Mark DM read ───────────────────────────────────────────────────────────export type MarkDmReadArgs = { dmId: string }@@ -840,7 +914,12 @@ export function useMarkAllInboxRead() {])},onMutate: async () => {- queryClient.setQueryData(communityKeys.inboxUnreads(), { servers: [] })+ // DMs live under `inboxUnreads` too — clear both keys so the popover's+ // "caught up" empty state renders while the mutation is in flight. The+ // `read-all` route only marks server channels; DM unread counts will+ // re-populate on the next refetch. Users mostly hit this to clear+ // mention/channel noise, so the brief DM flash is acceptable.+ queryClient.setQueryData(communityKeys.inboxUnreads(), { servers: [], dms: [] })queryClient.setQueryData(communityKeys.inboxMentions(), { mentions: [] })},onSuccess: () => {diff --git a/src/web/src/hooks/community/use-channel-read-state.ts b/src/web/src/hooks/community/use-channel-read-state.tsindex a1a4e3ecf..090ef02e2 100644--- a/src/web/src/hooks/community/use-channel-read-state.ts+++ b/src/web/src/hooks/community/use-channel-read-state.ts@@ -13,6 +13,11 @@ import { communityKeys } from "@/lib/query-keys"export type ChannelReadStateSnapshot = {lastReadMessageId: string | nulllastReadAt: string | null+ // Numeric equivalent of `lastReadMessageId` — the seq of the row that+ // pointer refers to. Server returns `0` when the viewer has never read+ // this channel; consumers subtract from `latestSeq` for the unread-count+ // pill without needing to walk loaded rows.+ lastReadSeq: number}/**@@ -60,6 +65,13 @@ export function useChannelReadStateSnapshot(channelId: string | null | undefined// old position because TanStack's `staleTime: Infinity` treats cached// data as fresh and refuses to refetch on remount.gcTime: 0,+ // Belt-and-braces alongside `gcTime: 0`. If a persisted or hydrated+ // snapshot ever lands in the cache (e.g. a future feature flips this+ // key back into the persist allowlist), `refetchOnMount: "always"` still+ // fires a network fetch on mount. The `snapshotRef` below latches only+ // the FIRST non-null resolution, so the refetched value is what gets+ // frozen — the freeze semantics are preserved.+ refetchOnMount: "always",refetchOnWindowFocus: false,refetchOnReconnect: false,// Snapshot is one-shot; even if TanStack retries a failed fetch, thediff --git a/src/web/src/hooks/community/use-channel-watermark.test.ts b/src/web/src/hooks/community/use-channel-watermark.test.tsindex ff04700ac..ef555f4b2 100644--- a/src/web/src/hooks/community/use-channel-watermark.test.ts+++ b/src/web/src/hooks/community/use-channel-watermark.test.ts@@ -154,7 +154,7 @@ beforeEach(() => {})describe("useChannelWatermark — visibility gate", () => {- it("advances the watermark when a row hits >=0.75 visibility", async () => {+ it("advances the watermark when a row hits >=0.2 visibility", async () => {const useHook = await loadHook()const root = makeRoot()const row = makeRow("m_1")@@ -167,11 +167,11 @@ describe("useChannelWatermark — visibility gate", () => {scrollRootEl: root,})flushEffects()- fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.9 }])+ fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.3 }])expect(advanceSpy).toHaveBeenCalledWith("ch_1", "m_1")})- it("does NOT advance when ratio is below 0.75", async () => {+ it("does NOT advance when ratio is below 0.2", async () => {const useHook = await loadHook()const root = makeRoot()const row = makeRow("m_1")@@ -184,7 +184,7 @@ describe("useChannelWatermark — visibility gate", () => {scrollRootEl: root,})flushEffects()- fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.5 }])+ fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.1 }])expect(advanceSpy).not.toHaveBeenCalled()})diff --git a/src/web/src/hooks/community/use-channel-watermark.ts b/src/web/src/hooks/community/use-channel-watermark.tsindex edde119f6..d5ede6c95 100644--- a/src/web/src/hooks/community/use-channel-watermark.ts+++ b/src/web/src/hooks/community/use-channel-watermark.ts@@ -8,10 +8,13 @@ import { useCurrentUser } from "@/contexts/community/current-user"/*** Threshold at which a message must be visible before it counts as "read".- * 0.75 mirrors Slack — the whole message row must be substantially on- * screen; a single-pixel intersection is not "the user looked at it".+ * 0.2 = Discord-style: a message counts as read as soon as any meaningful+ * portion enters the viewport. Higher values (0.75, Slack-style) forced+ * users to scroll a full row PAST the viewport bottom before the watermark+ * would move — badges only cleared "when you dragged the message to the+ * very bottom." 0.2 clears them the moment a message is genuinely visible.*/-const READ_VISIBILITY_THRESHOLD = 0.75+const READ_VISIBILITY_THRESHOLD = 0.2/*** Slack-style progressive read watermark. Observes every rendered messagediff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex e2a3d17b1..3aebc5e50 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -247,6 +247,101 @@ describe("useCommunityWs — message.create", () => {expect(ids[0]).toBe("seed_1")})+ it("flips hasMore/hasMoreOlder to true when the head-slice discards history (legacy shape)", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()++ const MAX_LIVE_PAGE_MESSAGES = 500+ const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({+ id: `seed_${i}`,+ content: "x",+ createdAt: "2026-07-03T00:00:00.000Z",+ }))+ // Legacy newest-mode envelope: only `hasMore` is defined.+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {+ pages: [{ messages: seeded, hasMore: false }],+ pageParams: [null],+ })++ capturedOnMessage!(messageCreate("ch_1", "new_message"))++ const cache = capturedQueryClient.getQueryData<{+ pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean }[]+ }>(communityKeys.channelMessages("ch_1"))+ // Head-slice discarded seed_0; the "Load older" affordance must re-arm+ // via `hasMore: true` (legacy shape had no `hasMoreOlder` so we don't+ // synthesize it).+ expect(cache?.pages[0].hasMore).toBe(true)+ expect(cache?.pages[0].hasMoreOlder).toBeUndefined()+ })++ it("flips hasMoreOlder to true on head-slice for anchor-mode envelopes", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()++ const MAX_LIVE_PAGE_MESSAGES = 500+ const seeded = Array.from({ length: MAX_LIVE_PAGE_MESSAGES }, (_, i) => ({+ id: `seed_${i}`,+ content: "x",+ createdAt: "2026-07-03T00:00:00.000Z",+ }))+ // Anchor-mode envelope: hasMoreOlder + hasMoreNewer, no `hasMore`.+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {+ pages: [{ messages: seeded, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }],+ pageParams: [{ mode: "anchor", anchor: "seed_0" }],+ })++ capturedOnMessage!(messageCreate("ch_1", "new_message"))++ const cache = capturedQueryClient.getQueryData<{+ pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]+ }>(communityKeys.channelMessages("ch_1"))+ expect(cache?.pages[0].hasMoreOlder).toBe(true)+ // We must NOT invent a legacy `hasMore` flag on an anchor envelope —+ // the two shapes are mutually exclusive.+ expect(cache?.pages[0].hasMore).toBeUndefined()+ // `hasMoreNewer` untouched.+ expect(cache?.pages[0].hasMoreNewer).toBe(false)+ })++ it("does not touch hasMore flags when the page hasn't been trimmed", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()++ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {+ pages: [+ {+ messages: [{ id: "seed_0", content: "x", createdAt: "t" }],+ hasMoreOlder: false,+ hasMoreNewer: false,+ latestSeq: 1,+ },+ ],+ pageParams: [null],+ })+ capturedOnMessage!(messageCreate("ch_1", "m_new"))+ const cache = capturedQueryClient.getQueryData<{+ pages: { hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]+ }>(communityKeys.channelMessages("ch_1"))+ expect(cache?.pages[0].hasMoreOlder).toBe(false)+ expect(cache?.pages[0].hasMoreNewer).toBe(false)+ })+it("does not drop below the cap when the page isn't at capacity yet", async () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")@@ -961,6 +1056,105 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {}),).toBe(true)})++ it("invalidates the focused channel's message + read-state queries + inbox on reconnect", async () => {+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_focus" })++ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")++ expect(capturedOnReconnect).not.toBeNull()+ capturedOnReconnect!()++ const invalidatedKeys = spy.mock.calls.map(+ (c) => c[0]?.queryKey as unknown[] | undefined,+ )+ // Focused channel messages+ expect(+ invalidatedKeys.some(+ (k) =>+ Array.isArray(k) &&+ k[0] === "community" &&+ k[1] === "channel" &&+ k[2] === "ch_focus" &&+ k[3] === "messages",+ ),+ ).toBe(true)+ // Focused channel read-state snapshot+ expect(+ invalidatedKeys.some(+ (k) =>+ Array.isArray(k) &&+ k[0] === "community" &&+ k[1] === "channel" &&+ k[2] === "ch_focus" &&+ k[3] === "read-state-snapshot",+ ),+ ).toBe(true)+ // Inbox+ expect(+ invalidatedKeys.some(+ (k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",+ ),+ ).toBe(true)+ })++ it("invalidates the focused DM's message + read-state queries on reconnect", async () => {+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })++ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")++ expect(capturedOnReconnect).not.toBeNull()+ capturedOnReconnect!()++ const invalidatedKeys = spy.mock.calls.map(+ (c) => c[0]?.queryKey as unknown[] | undefined,+ )+ expect(+ invalidatedKeys.some(+ (k) =>+ Array.isArray(k) &&+ k[0] === "community" &&+ k[1] === "dm" &&+ k[2] === "dm_focus" &&+ k[3] === "messages",+ ),+ ).toBe(true)+ expect(+ invalidatedKeys.some(+ (k) =>+ Array.isArray(k) &&+ k[0] === "community" &&+ k[1] === "dm" &&+ k[2] === "dm_focus" &&+ k[3] === "read-state-snapshot",+ ),+ ).toBe(true)+ })++ it("only invalidates the focused scope — no channel invalidation when only a DM is focused", async () => {+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })++ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")++ expect(capturedOnReconnect).not.toBeNull()+ capturedOnReconnect!()++ const invalidatedKeys = spy.mock.calls.map(+ (c) => c[0]?.queryKey as unknown[] | undefined,+ )+ // No channel-scoped message invalidation should have fired.+ expect(+ invalidatedKeys.some(+ (k) => Array.isArray(k) && k[1] === "channel" && k[3] === "messages",+ ),+ ).toBe(false)+ })})// ── Regression #15 — double-mount guard warns ───────────────────────────diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 5c4bab3fa..0f1715219 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -180,12 +180,29 @@ function insertMessageIntoCache(const merged = [...first.messages, rendered]// Drop from the head (oldest end of this page) once the live tail grows// past the cap — keeps the newest messages, sheds the oldest.- const messages = merged.length > MAX_LIVE_PAGE_MESSAGES+ const trimmed = merged.length > MAX_LIVE_PAGE_MESSAGES+ const messages = trimmed? merged.slice(merged.length - MAX_LIVE_PAGE_MESSAGES): merged+ // When we drop rows off the head of the live page we've forgotten history+ // that the server still has. Flip both the anchor-mode and the legacy+ // `hasMore` flags to `true` so the older-pagination affordance re-arms —+ // otherwise `hasMoreOlder ?? hasMore ?? false` collapses to `false` for+ // the trimmed page and the UI stops offering "Load more" even though+ // there's still history to fetch. Only touch the flags that already+ // existed on the page so we don't accidentally invent an anchor-mode+ // envelope on a legacy newest cache (or vice versa).+ const nextFirst = trimmed+ ? {+ ...first,+ messages,+ ...(first.hasMoreOlder !== undefined ? { hasMoreOlder: true } : {}),+ ...(first.hasMore !== undefined ? { hasMore: true } : {}),+ }+ : { ...first, messages }return {...cache,- pages: [{ ...first, messages }, ...cache.pages.slice(1)],+ pages: [nextFirst, ...cache.pages.slice(1)],}}@@ -799,8 +816,40 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// (`contexts/agent-context.tsx`): resync the machines query on every// reconnect so a missed transition self-corrects within the reconnect// window instead of requiring a manual reload.+ //+ // Same rationale for the focused channel/DM message stream after Commit C:+ // the IDB persister rehydrates the cache from the last session, but the+ // socket may have dropped WS `message.create` events while we were offline+ // (or the tab was suspended). Invalidating the focused scope's message+ // query on reconnect fires a top-up refetch — TanStack re-runs every+ // page's `pageParam`, so anchor windows and newest-tail windows both+ // catch up without any client-side `?since` bookkeeping. Read-state+ // snapshots (also persisted) are invalidated too so the NEW divider+ // matches the fresh server watermark on reconnect.const handleReconnect = useCallback(() => {queryClient.invalidateQueries({ queryKey: communityKeys.machines() })+ const sub = useCommunityStore.getState().subscription+ if (sub.channelId) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelMessages(sub.channelId),+ })+ void queryClient.invalidateQueries({+ queryKey: communityKeys.channelReadStateSnapshot(sub.channelId),+ })+ }+ if (sub.dmConversationId) {+ void queryClient.invalidateQueries({+ queryKey: communityKeys.dmMessages(sub.dmConversationId),+ })+ void queryClient.invalidateQueries({+ queryKey: communityKeys.dmReadStateSnapshot(sub.dmConversationId),+ })+ }+ // Inbox counts also need a refetch — unreads and mentions could have+ // grown while offline and the live invalidator only fires on incoming+ // `message.create` events, none of which arrive while the socket is+ // down.+ void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })}, [queryClient])const { send } = useUserWs(handleMessage, { onReconnect: handleReconnect })diff --git a/src/web/src/hooks/community/use-dm-read-state.test.ts b/src/web/src/hooks/community/use-dm-read-state.test.tsnew file mode 100644index 000000000..e24133868--- /dev/null+++ b/src/web/src/hooks/community/use-dm-read-state.test.ts@@ -0,0 +1,190 @@+/**+ * `useDmReadStateSnapshot` — DM sibling of `useChannelReadStateSnapshot`.+ * Mirrors the freeze invariant tests exactly; if the two hooks ever+ * diverge in behavior the divider anchor will drift out of parity across+ * channels and DMs.+ */+import { describe, it, expect, vi, beforeEach } from "vitest"++// ── React shim ────────────────────────────────────────────────────────────+let refs: Map<string, { current: unknown }> = new Map()+let refCounter = 0+let pendingEffects: Array<() => void> = []++vi.mock("react", () => ({+ useRef: (initial: unknown) => {+ const id = `ref-${refCounter++}`+ if (!refs.has(id)) refs.set(id, { current: initial })+ return refs.get(id)!+ },+ useEffect: (fn: () => void, _deps: unknown[]) => {+ pendingEffects.push(fn)+ },+}))++function flushEffects() {+ const effects = pendingEffects+ pendingEffects = []+ for (const fn of effects) fn()+}++// ── TanStack Query shim — we control the returned value per-render ────────+let queryReturn: { data: unknown; isFetching: boolean } = {+ data: undefined,+ isFetching: false,+}+vi.mock("@tanstack/react-query", () => ({+ useQuery: (_config: unknown) => queryReturn,+}))++vi.mock("@/lib/api/client", () => ({+ apiFetch: vi.fn(),+}))++function resetHarness() {+ refs = new Map()+ refCounter = 0+ pendingEffects = []+ queryReturn = { data: undefined, isFetching: false }+}++async function loadHook() {+ const mod = await import("./use-dm-read-state")+ return mod.useDmReadStateSnapshot+}++beforeEach(() => {+ resetHarness()+})++describe("useDmReadStateSnapshot — freeze invariant", () => {+ it("returns null before the query resolves", async () => {+ const useHook = await loadHook()+ queryReturn = { data: undefined, isFetching: true }+ const first = useHook("dm_1")+ flushEffects()+ expect(first.snapshot).toBeNull()+ expect(first.isFetching).toBe(true)+ })++ it("returns the resolved value on first success", async () => {+ const useHook = await loadHook()+ queryReturn = {+ data: {+ lastReadMessageId: "m_42",+ lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 42,+ },+ isFetching: false,+ }+ const r = useHook("dm_1")+ flushEffects()+ expect(r.snapshot).toEqual({+ lastReadMessageId: "m_42",+ lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 42,+ })+ })++ it("freezes the snapshot — a subsequent 'refetch' with a NEW value must NOT change what the hook returns", async () => {+ const useHook = await loadHook()++ // First render: query resolves with value A.+ queryReturn = {+ data: {+ lastReadMessageId: "m_original",+ lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 10,+ },+ isFetching: false,+ }+ useHook("dm_1")+ flushEffects()++ // Second render (same mount, same DM): simulate a phantom refetch+ // that would have advanced the pointer.+ refCounter = 0+ pendingEffects = []+ queryReturn = {+ data: {+ lastReadMessageId: "m_way_later",+ lastReadAt: "2026-07-15T00:00:00.000Z",+ lastReadSeq: 999,+ },+ isFetching: false,+ }+ const r2 = useHook("dm_1")+ flushEffects()++ expect(r2.snapshot).toEqual({+ lastReadMessageId: "m_original",+ lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 10,+ })+ })++ it("resets the ref on dmId change so switching DMs rebuilds the snapshot", async () => {+ const useHook = await loadHook()++ queryReturn = {+ data: {+ lastReadMessageId: "m_a",+ lastReadAt: "2026-07-01T00:00:00.000Z",+ lastReadSeq: 1,+ },+ isFetching: false,+ }+ useHook("dm_1")+ flushEffects()++ // Same-mount DM switch — the hook body checks lastDmIdRef and+ // clears snapshotRef. Simulate the re-render:+ refCounter = 0+ pendingEffects = []+ queryReturn = {+ data: {+ lastReadMessageId: "m_b",+ lastReadAt: "2026-07-02T00:00:00.000Z",+ lastReadSeq: 2,+ },+ isFetching: false,+ }+ const r = useHook("dm_2")+ flushEffects()++ expect(r.snapshot).toEqual({+ lastReadMessageId: "m_b",+ lastReadAt: "2026-07-02T00:00:00.000Z",+ lastReadSeq: 2,+ })+ })++ it("returns the null-pointer sentinel when the initial fetch resolved with no prior read row", async () => {+ const useHook = await loadHook()+ queryReturn = {+ data: { lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },+ isFetching: false,+ }+ useHook("dm_1")+ flushEffects()++ refCounter = 0+ pendingEffects = []+ // Even if a phantom refetch produced a real pointer, the freeze holds.+ queryReturn = {+ data: {+ lastReadMessageId: "m_late",+ lastReadAt: "2026-07-15T00:00:00.000Z",+ lastReadSeq: 50,+ },+ isFetching: false,+ }+ const r = useHook("dm_1")+ flushEffects()+ expect(r.snapshot).toEqual({+ lastReadMessageId: null,+ lastReadAt: null,+ lastReadSeq: 0,+ })+ })+})diff --git a/src/web/src/hooks/community/use-dm-read-state.ts b/src/web/src/hooks/community/use-dm-read-state.tsnew file mode 100644index 000000000..2d1d273f0--- /dev/null+++ b/src/web/src/hooks/community/use-dm-read-state.ts@@ -0,0 +1,81 @@+"use client"++import { useEffect, useRef } from "react"+import { useQuery } from "@tanstack/react-query"+import { apiFetch } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"++/**+ * The DM read-state snapshot returned by+ * `GET /api/community/dm/:id/read-state`. Fields default to `null` / `0`+ * when the viewer has never opened this DM.+ */+export type DmReadStateSnapshot = {+ lastReadMessageId: string | null+ lastReadAt: string | null+ // Numeric equivalent of `lastReadMessageId` — the seq of the row that+ // pointer refers to. Server returns `0` when the viewer has never read+ // this DM; consumers subtract from `latestSeq` for the unread-count pill+ // without walking loaded rows.+ lastReadSeq: number+}++/**+ * Once-per-mount snapshot of the viewer's read pointer for a DM. The+ * channel-side sibling is `useChannelReadStateSnapshot` — this hook mirrors+ * it exactly, because the invariants are shared: fix a bug on one side and+ * the same fix must reach the other, or the divider anchors diverge across+ * channels vs DMs and users lose their place.+ *+ * See `use-channel-read-state.ts` for the full doc — same freeze rule,+ * same `staleTime: Infinity` + `gcTime: 0` combo, same channelId → dmId+ * substitution.+ */+export function useDmReadStateSnapshot(dmId: string | null | undefined): {+ snapshot: DmReadStateSnapshot | null+ isFetching: boolean+} {+ const query = useQuery<DmReadStateSnapshot>({+ queryKey: dmId+ ? communityKeys.dmReadStateSnapshot(dmId)+ : ["community", "dm", "__none__", "read-state-snapshot"],+ queryFn: async () => {+ return apiFetch<DmReadStateSnapshot>(+ `/api/community/dm/${dmId}/read-state`,+ )+ },+ enabled: !!dmId,+ staleTime: Infinity,+ // Match the channel hook exactly — see its docstring for why `gcTime: 0`+ // is the only reliable way to force a real refetch on remount when+ // `staleTime: Infinity` treats the cached anchor as fresh forever.+ gcTime: 0,+ // Belt-and-braces alongside `gcTime: 0` — see channel sibling for the+ // rationale. The `snapshotRef` freeze semantics still hold because the+ // ref latches only the first non-null resolution.+ refetchOnMount: "always",+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ retry: 1,+ })++ const snapshotRef = useRef<DmReadStateSnapshot | null>(null)+ const lastDmIdRef = useRef<string | null | undefined>(dmId)+ /* eslint-disable react-hooks/refs -- sync dm switch reset; see channel hook tests */+ if (lastDmIdRef.current !== dmId) {+ snapshotRef.current = null+ lastDmIdRef.current = dmId+ }+ /* eslint-enable react-hooks/refs */+ useEffect(() => {+ if (snapshotRef.current !== null) return+ if (query.data) snapshotRef.current = query.data+ }, [query.data])++ /* eslint-disable react-hooks/refs -- latched snapshot read; see channel hook tests */+ return {+ snapshot: snapshotRef.current ?? (query.data ?? null),+ isFetching: query.isFetching,+ }+ /* eslint-enable react-hooks/refs */+}diff --git a/src/web/src/hooks/community/use-dm-watermark.test.ts b/src/web/src/hooks/community/use-dm-watermark.test.tsnew file mode 100644index 000000000..a2b59e4d2--- /dev/null+++ b/src/web/src/hooks/community/use-dm-watermark.test.ts@@ -0,0 +1,239 @@+/**+ * `useDmWatermark` — DM sibling of `useChannelWatermark`. Same+ * IntersectionObserver behavior, same monotone forward invariant, same+ * self-authored skip, same flush-on-unmount contract. Tests mirror the+ * channel-side coverage so a divergence between the two hooks would+ * surface here immediately.+ */+import { describe, it, expect, vi, beforeEach } from "vitest"++// ── React shim ────────────────────────────────────────────────────────────+let refs: Map<string, { current: unknown }> = new Map()+let refCounter = 0+let pendingEffects: Array<{ fn: () => void | (() => void); deps: unknown[] }> = []+let effectCleanups: Array<() => void> = []++vi.mock("react", () => ({+ useRef: (initial: unknown) => {+ const id = `ref-${refCounter++}`+ if (!refs.has(id)) refs.set(id, { current: initial })+ return refs.get(id)!+ },+ useEffect: (fn: () => void | (() => void), deps: unknown[]) => {+ pendingEffects.push({ fn, deps })+ },+}))++function flushEffects() {+ const effects = pendingEffects+ pendingEffects = []+ for (const e of effects) {+ const cleanup = e.fn()+ if (typeof cleanup === "function") effectCleanups.push(cleanup)+ }+}++function runCleanups() {+ const c = effectCleanups+ effectCleanups = []+ for (const fn of c) fn()+}++// ── IntersectionObserver polyfill ────────────────────────────────────────+type ObserverInstance = {+ callback: IntersectionObserverCallback+ root: Element | null+ threshold: number+ observed: Set<Element>+ disconnected: boolean+}+let observers: ObserverInstance[] = []++class MockIntersectionObserver {+ private inst: ObserverInstance+ constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {+ this.inst = {+ callback,+ root: (options?.root as Element | null | undefined) ?? null,+ threshold: Array.isArray(options?.threshold)+ ? options!.threshold[0]!+ : options?.threshold ?? 0,+ observed: new Set(),+ disconnected: false,+ }+ observers.push(this.inst)+ }+ observe(el: Element) {+ this.inst.observed.add(el)+ }+ unobserve(el: Element) {+ this.inst.observed.delete(el)+ }+ disconnect() {+ this.inst.disconnected = true+ this.inst.observed.clear()+ }+}++function fireIntersections(+ entries: Array<{ target: Element; isIntersecting: boolean; intersectionRatio: number }>,+) {+ for (const obs of observers) {+ if (obs.disconnected) continue+ const scoped = entries.filter((e) => obs.observed.has(e.target))+ if (scoped.length === 0) continue+ obs.callback(+ scoped.map((e) => ({+ ...e,+ rootBounds: null,+ boundingClientRect: {} as DOMRectReadOnly,+ intersectionRect: {} as DOMRectReadOnly,+ time: 0,+ })) as unknown as IntersectionObserverEntry[],+ undefined as unknown as IntersectionObserver,+ )+ }+}++// ── Mocks for the hook's imports ─────────────────────────────────────────+const advanceSpy = vi.fn()+const flushSpy = vi.fn()++vi.mock("@/hooks/community/mutations/messages", () => ({+ useAdvanceDmWatermark: () => advanceSpy,+ flushPendingReads: () => flushSpy(),+}))++vi.mock("@/contexts/community/current-user", () => ({+ useCurrentUser: () => ({ id: "u_viewer", name: "viewer", avatar: "V" }),+}))++function resetHarness() {+ refs = new Map()+ refCounter = 0+ pendingEffects = []+ effectCleanups = []+ observers = []+ advanceSpy.mockClear()+ flushSpy.mockClear()+}++async function loadHook() {+ const mod = await import("./use-dm-watermark")+ return mod.useDmWatermark+}++function makeRoot(): HTMLElement {+ return { __kind: "root" } as unknown as HTMLElement+}++function makeRow(id: string): Element {+ return { dataset: { msgId: id } } as unknown as Element+}++function attachRows(root: HTMLElement, rows: Element[]) {+ ;(root as unknown as { querySelectorAll: (sel: string) => Iterable<Element> }).querySelectorAll =+ () => rows+}++beforeEach(() => {+ resetHarness()+ ;(globalThis as unknown as { IntersectionObserver: unknown }).IntersectionObserver =+ MockIntersectionObserver+})++describe("useDmWatermark — visibility gate", () => {+ it("advances the watermark when a row hits >=0.2 visibility", async () => {+ const useHook = await loadHook()+ const root = makeRoot()+ const row = makeRow("m_1")+ attachRows(root, [row])+ useHook({+ dmId: "dm_1",+ messages: [+ { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },+ ],+ scrollRootEl: root,+ })+ flushEffects()+ fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.3 }])+ expect(advanceSpy).toHaveBeenCalledWith("dm_1", "m_1")+ })++ it("does NOT advance when ratio is below 0.2", async () => {+ const useHook = await loadHook()+ const root = makeRoot()+ const row = makeRow("m_1")+ attachRows(root, [row])+ useHook({+ dmId: "dm_1",+ messages: [+ { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },+ ],+ scrollRootEl: root,+ })+ flushEffects()+ fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.1 }])+ expect(advanceSpy).not.toHaveBeenCalled()+ })+})++describe("useDmWatermark — monotone forward", () => {+ it("NEVER regresses — a stale-older intersection after seeing a newer row is ignored", async () => {+ const useHook = await loadHook()+ const root = makeRoot()+ const rowOld = makeRow("m_old")+ const rowNew = makeRow("m_new")+ attachRows(root, [rowOld, rowNew])+ useHook({+ dmId: "dm_1",+ messages: [+ { id: "m_old", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },+ { id: "m_new", createdAt: "2026-07-02T00:00:00.000Z", authorId: "u_other" },+ ],+ scrollRootEl: root,+ })+ flushEffects()+ fireIntersections([{ target: rowNew, isIntersecting: true, intersectionRatio: 0.9 }])+ fireIntersections([{ target: rowOld, isIntersecting: true, intersectionRatio: 0.9 }])+ expect(advanceSpy.mock.calls.map((c) => c[1])).toEqual(["m_new"])+ })+})++describe("useDmWatermark — self-authored skip", () => {+ it("does NOT advance for a message authored by the viewer", async () => {+ const useHook = await loadHook()+ const root = makeRoot()+ const row = makeRow("m_1")+ attachRows(root, [row])+ useHook({+ dmId: "dm_1",+ messages: [+ { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_viewer" },+ ],+ scrollRootEl: root,+ })+ flushEffects()+ fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.99 }])+ expect(advanceSpy).not.toHaveBeenCalled()+ })+})++describe("useDmWatermark — lifecycle", () => {+ it("flushes pending mark-reads on unmount / DM change", async () => {+ const useHook = await loadHook()+ const root = makeRoot()+ attachRows(root, [])+ useHook({ dmId: "dm_1", messages: [], scrollRootEl: root })+ flushEffects()+ runCleanups()+ expect(flushSpy).toHaveBeenCalled()+ })++ it("no-op when scrollRootEl is null (IntersectionObserver never mounts)", async () => {+ const useHook = await loadHook()+ useHook({ dmId: "dm_1", messages: [], scrollRootEl: null })+ flushEffects()+ expect(observers).toHaveLength(0)+ })+})diff --git a/src/web/src/hooks/community/use-dm-watermark.ts b/src/web/src/hooks/community/use-dm-watermark.tsnew file mode 100644index 000000000..17e0559ae--- /dev/null+++ b/src/web/src/hooks/community/use-dm-watermark.ts@@ -0,0 +1,114 @@+"use client"++import { useEffect, useRef } from "react"+import { flushPendingReads } from "@/hooks/community/mutations/messages"+import { useAdvanceDmWatermark } from "@/hooks/community/mutations/messages"+import type { Msg } from "@/components/community/_types"+import { useCurrentUser } from "@/contexts/community/current-user"++/**+ * See `use-channel-watermark.ts` for the rationale — mirrors channel side.+ * MUST stay identical or DM and channel divider timing drifts.+ */+const READ_VISIBILITY_THRESHOLD = 0.2++/**+ * Slack-style progressive read watermark for DMs. Behaves identically to+ * `useChannelWatermark` — same threshold, same monotone `maxSeen` ref,+ * same self-authored skip, same flush-on-unmount contract. The shape is+ * intentionally mirrored so bugs fixed on one side reach the other:+ * this is single-source-of-truth for the watermark UX, split into two+ * hook files only because the write path differs (`useAdvanceDmWatermark`+ * PUTs `/dm/:id/read` instead of `/channels/:id/read`).+ *+ * See `useChannelWatermark` for the full invariant list. Any change to+ * that hook's ratio, ordering, or lifecycle rules MUST be mirrored here+ * or the DM divider / read pointer will drift out of parity with+ * channels.+ */+export function useDmWatermark({+ dmId,+ messages,+ scrollRootEl,+}: {+ dmId: string | null | undefined+ messages: Msg[]+ scrollRootEl: HTMLElement | null+}) {+ const currentUser = useCurrentUser()+ const viewerId = currentUser.id+ const advance = useAdvanceDmWatermark()++ // `maxSeen` is a `(createdAt, id)` pair — lex ordering so identical+ // createdAt strings still sort deterministically. Reset when the DM+ // changes so a switch between DMs doesn't leak the prior DM's pointer.+ const maxSeenRef = useRef<{ createdAt: string; id: string } | null>(null)+ useEffect(() => {+ maxSeenRef.current = null+ }, [dmId])++ // Keep the freshest `messages` array visible to the IntersectionObserver+ // callback via a ref — the callback captures once per observer re-attach+ // and shouldn't recreate on every render. See channel hook for details.+ const messagesRef = useRef<Msg[]>(messages)+ const advanceRef = useRef(advance)+ useEffect(() => {+ messagesRef.current = messages+ advanceRef.current = advance+ })++ useEffect(() => {+ if (!dmId) return+ if (!scrollRootEl) return+ if (typeof IntersectionObserver === "undefined") return++ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (!entry.isIntersecting) continue+ if (entry.intersectionRatio < READ_VISIBILITY_THRESHOLD) continue+ const target = entry.target as HTMLElement+ const id = target.dataset.msgId+ if (!id) continue+ const msg = messagesRef.current.find((m) => m.id === id)+ if (!msg || !msg.createdAt) continue+ // Skip self-authored messages — mirrors channel hook. Server+ // stamps the sender's own watermark on POST so a client PUT+ // here would be redundant.+ if (msg.authorId && msg.authorId === viewerId) continue++ const cur = maxSeenRef.current+ const isNewer =+ !cur ||+ msg.createdAt > cur.createdAt ||+ (msg.createdAt === cur.createdAt && id > cur.id)+ if (!isNewer) continue+ maxSeenRef.current = { createdAt: msg.createdAt, id }+ advanceRef.current(dmId, id)+ }+ },+ {+ root: scrollRootEl,+ threshold: READ_VISIBILITY_THRESHOLD,+ },+ )++ // Observe every currently-rendered message row. React re-runs this+ // effect whenever the `messages` reference changes (send / receive /+ // pagination), so the observer picks up fresh rows on the next render.+ const nodes = scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]")+ nodes.forEach((n) => observer.observe(n))++ return () => observer.disconnect()+ }, [dmId, messages, scrollRootEl, viewerId])++ // On unmount / DM switch, flush the debounce so the last-watched message+ // isn't stranded in the pending window. `flushPendingReads` fires every+ // entry (channel + DM) — safe because each entry's `fire` is idempotent+ // and only the ones scheduled here belong to this DM's write path.+ useEffect(() => {+ return () => {+ flushPendingReads()+ }+ }, [dmId])+}diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.tsindex d3665e19c..4202fd2e0 100644--- a/src/web/src/hooks/community/use-inbox.test.ts+++ b/src/web/src/hooks/community/use-inbox.test.ts@@ -13,13 +13,13 @@ beforeEach(() => {describe("useInboxUnreads / inboxUnreadsQueryFn", () => {it("fetches /inbox/unreads and populates queryClient at communityKeys.inboxUnreads()", async () => {- apiFetchMock.mockResolvedValueOnce({ servers: [] })+ apiFetchMock.mockResolvedValueOnce({ servers: [], dms: [] })const { inboxUnreadsQueryFn } = await import("./use-inbox")const qc = new QueryClient()const key = communityKeys.inboxUnreads()await qc.fetchQuery({ queryKey: key, queryFn: inboxUnreadsQueryFn })expect(apiFetchMock).toHaveBeenCalledWith("/api/community/inbox/unreads")- expect(qc.getQueryData(key)).toEqual({ servers: [] })+ expect(qc.getQueryData(key)).toEqual({ servers: [], dms: [] })})})@@ -40,7 +40,7 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {describe("communityKeys.inbox() prefix invalidation", () => {it("invalidates both inbox queries in a single call", async () => {apiFetchMock- .mockResolvedValueOnce({ servers: [] })+ .mockResolvedValueOnce({ servers: [], dms: [] }).mockResolvedValueOnce({ mentions: [] })const { inboxUnreadsQueryFn, inboxMentionsQueryFn } = await import("./use-inbox"diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.tsindex 18a54d6c6..ee4db6665 100644--- a/src/web/src/hooks/community/use-inbox.ts+++ b/src/web/src/hooks/community/use-inbox.ts@@ -3,10 +3,11 @@import { useQuery, type UseQueryResult } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"-import type { UnreadServer, Mention } from "@/components/community/_types"+import type { UnreadServer, UnreadDm, Mention } from "@/components/community/_types"// Frozen empty fallbacks — see `use-servers.ts` for the rationale.const EMPTY_UNREADS: readonly UnreadServer[] = Object.freeze([])+const EMPTY_DMS: readonly UnreadDm[] = Object.freeze([])const EMPTY_MENTIONS: readonly Mention[] = Object.freeze([])/**@@ -22,13 +23,14 @@ const EMPTY_MENTIONS: readonly Mention[] = Object.freeze([])* refresh doesn't re-render the other).*/-export type UnreadsResponse = { servers: UnreadServer[] }+export type UnreadsResponse = { servers: UnreadServer[]; dms: UnreadDm[] }export const inboxUnreadsQueryFn = () =>apiFetch<UnreadsResponse>("/api/community/inbox/unreads")export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {servers: UnreadServer[]+ dms: UnreadDm[]} {const query = useQuery({queryKey: communityKeys.inboxUnreads(),@@ -37,6 +39,7 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {return {...query,servers: query.data?.servers ?? (EMPTY_UNREADS as UnreadServer[]),+ dms: query.data?.dms ?? (EMPTY_DMS as UnreadDm[]),}}diff --git a/src/web/src/hooks/community/use-messages.test.ts b/src/web/src/hooks/community/use-messages.test.tsindex 9b1c64ff9..26c4563c4 100644--- a/src/web/src/hooks/community/use-messages.test.ts+++ b/src/web/src/hooks/community/use-messages.test.ts@@ -16,21 +16,64 @@ async function loadHook() {return await import("./use-messages")}-describe("channelMessagesQueryFn", () => {- it("appends ?cursor when a pageParam is provided", async () => {+// The queryFn dispatches on `pageParam.mode` — one URL per mode. Legacy+// pre-A2 tests passed a raw cursor string; the new signature takes a+// discriminated pageParam so the type-narrowing per branch is explicit.++describe("channelMessagesQueryFn — url per mode", () => {+ it("newest → no query params", async () => {const { channelMessagesQueryFn } = await loadHook()- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false })- const fn = channelMessagesQueryFn("ch_1")- await fn({ pageParam: null })+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })+ await channelMessagesQueryFn("ch_1")({ pageParam: { mode: "newest" } })expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/ch_1/messages")+ })- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false })- await fn({ pageParam: "2026-07-03T00:00:00.000Z|abc" })+ it("older → ?cursor=<c>", async () => {+ const { channelMessagesQueryFn } = await loadHook()+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })+ await channelMessagesQueryFn("ch_1")({+ pageParam: { mode: "older", cursor: "2026-07-03T00:00:00.000Z|abc" },+ })expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/ch_1/messages?cursor=2026-07-03T00%3A00%3A00.000Z%7Cabc",)})+ it("newer → ?since=<c>", async () => {+ const { channelMessagesQueryFn } = await loadHook()+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMoreNewer: false, latestSeq: 0 })+ await channelMessagesQueryFn("ch_1")({+ pageParam: { mode: "newer", cursor: "cur_new" },+ })+ expect(apiFetchMock).toHaveBeenLastCalledWith(+ "/api/community/channels/ch_1/messages?since=cur_new",+ )+ })++ it("anchor → ?anchor=<id>", async () => {+ const { channelMessagesQueryFn } = await loadHook()+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 })+ await channelMessagesQueryFn("ch_1")({+ pageParam: { mode: "anchor", anchor: "m_42" },+ })+ expect(apiFetchMock).toHaveBeenLastCalledWith(+ "/api/community/channels/ch_1/messages?anchor=m_42",+ )+ })++ it("since → ?since=<c>", async () => {+ const { channelMessagesQueryFn } = await loadHook()+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMoreNewer: false, latestSeq: 0 })+ await channelMessagesQueryFn("ch_1")({+ pageParam: { mode: "since", since: "cur_since" },+ })+ expect(apiFetchMock).toHaveBeenLastCalledWith(+ "/api/community/channels/ch_1/messages?since=cur_since",+ )+ })+})++describe("channelMessagesQueryFn — queryClient integration", () => {it("populates queryClient at communityKeys.channelMessages(channelId)", async () => {const { channelMessagesQueryFn } = await loadHook()apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_1" }], hasMore: false })@@ -39,22 +82,19 @@ describe("channelMessagesQueryFn", () => {await qc.fetchInfiniteQuery({queryKey: key,queryFn: channelMessagesQueryFn("ch_1"),- initialPageParam: null as string | null,+ initialPageParam: { mode: "newest" } as const,})expect(qc.getQueryData(key)).toBeDefined()})- // ── Prefix-invalidation integration guard ─────────────────────────────────// Foundation invariant: invalidating `channelMessages(channelId)` marks// every `channelMessagesPage(channelId, …)` variant as invalidated too.- // If a future change breaks the key-nesting contract, this test fails and- // the invariant is defended before it can silently regress in production.it("prefix invalidation via channelMessages(id) marks channelMessagesPage(id, cursor) invalidated", async () => {const { channelMessagesQueryFn } = await loadHook()apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false })const qc = new QueryClient()const cursorKey = communityKeys.channelMessagesPage("ch_1", "cur|abc")- await qc.fetchQuery({ queryKey: cursorKey, queryFn: channelMessagesQueryFn("ch_1") })+ await qc.fetchQuery({ queryKey: cursorKey, queryFn: () => apiFetchMock() })expect(qc.getQueryData(cursorKey)).toBeDefined()await qc.invalidateQueries({ queryKey: communityKeys.channelMessages("ch_1") })@@ -63,35 +103,111 @@ describe("channelMessagesQueryFn", () => {})describe("dmMessagesQueryFn", () => {- it("appends ?cursor when a pageParam is provided", async () => {+ it("newest → no query params", async () => {const { dmMessagesQueryFn } = await loadHook()- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false })- await dmMessagesQueryFn("dm_1")({ pageParam: null })+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })+ await dmMessagesQueryFn("dm_1")({ pageParam: { mode: "newest" } })expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/dm/dm_1/messages")+ })- apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false })- await dmMessagesQueryFn("dm_1")({ pageParam: "cur_1" })+ it("older cursor → ?cursor", async () => {+ const { dmMessagesQueryFn } = await loadHook()+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })+ await dmMessagesQueryFn("dm_1")({+ pageParam: { mode: "older", cursor: "cur_1" },+ })expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/dm/dm_1/messages?cursor=cur_1",)})- it("fetchNextPage produces a new page under the same infinite key", async () => {+ it("fetchNextPage (older) produces a new page under the same infinite key", async () => {const { dmMessagesQueryFn } = await loadHook()apiFetchMock- .mockResolvedValueOnce({ messages: [{ id: "m_1" }], hasMore: true, cursor: "cur_1" })- .mockResolvedValueOnce({ messages: [{ id: "m_2" }], hasMore: false })+ .mockResolvedValueOnce({ messages: [{ id: "m_1" }], hasMore: true, cursor: "cur_1", latestSeq: 1 })+ .mockResolvedValueOnce({ messages: [{ id: "m_2" }], hasMore: false, latestSeq: 1 })const qc = new QueryClient()const key = communityKeys.dmMessages("dm_1")await qc.fetchInfiniteQuery({queryKey: key,queryFn: dmMessagesQueryFn("dm_1"),- initialPageParam: null as string | null,- getNextPageParam: (last: { hasMore: boolean; cursor?: string }) =>- last.hasMore ? (last.cursor ?? null) : undefined,+ initialPageParam: { mode: "newest" } as const,+ getNextPageParam: (last: { hasMore?: boolean; cursor?: string }) =>+ last.hasMore && last.cursor ? { mode: "older" as const, cursor: last.cursor } : undefined,pages: 2,})const data = qc.getQueryData<InfiniteData<{ messages: unknown[] }>>(key)expect(data?.pages).toHaveLength(2)})})++// ── mergeMessagesPages reducer ──────────────────────────────────────────+//+// Pages may arrive out of order — anchor first, then interleaved+// older/newer fetches. The reducer sorts across ALL pages by+// (createdAt, id) and dedupes by id so the visible message list is+// always in chronological ASC regardless of fetch sequence.++describe("mergeMessagesPages", () => {+ it("sorts across pages by (createdAt, id) ASC", async () => {+ const { mergeMessagesPages } = await loadHook()+ const pages = [+ {+ messages: [+ { id: "m_3", createdAt: "2026-07-01T00:00:03.000Z" },+ { id: "m_4", createdAt: "2026-07-01T00:00:04.000Z" },+ ],+ hasMoreOlder: false,+ hasMoreNewer: false,+ },+ {+ messages: [+ { id: "m_1", createdAt: "2026-07-01T00:00:01.000Z" },+ { id: "m_2", createdAt: "2026-07-01T00:00:02.000Z" },+ ],+ hasMore: false,+ },+ ]+ const merged = mergeMessagesPages(pages)+ expect(merged.map((m) => m.id)).toEqual(["m_1", "m_2", "m_3", "m_4"])+ })++ it("dedupes by id (keeps first occurrence in sorted order)", async () => {+ const { mergeMessagesPages } = await loadHook()+ const pages = [+ {+ messages: [+ { id: "m_1", createdAt: "2026-07-01T00:00:01.000Z" },+ { id: "m_2", createdAt: "2026-07-01T00:00:02.000Z" },+ ],+ },+ {+ messages: [+ { id: "m_2", createdAt: "2026-07-01T00:00:02.000Z" },+ { id: "m_3", createdAt: "2026-07-01T00:00:03.000Z" },+ ],+ },+ ]+ const merged = mergeMessagesPages(pages)+ expect(merged.map((m) => m.id)).toEqual(["m_1", "m_2", "m_3"])+ })++ it("stable sort — equal createdAt tiebreaks on id", async () => {+ const { mergeMessagesPages } = await loadHook()+ const pages = [+ {+ messages: [+ { id: "m_b", createdAt: "2026-07-01T00:00:01.000Z" },+ { id: "m_a", createdAt: "2026-07-01T00:00:01.000Z" },+ ],+ },+ ]+ const merged = mergeMessagesPages(pages)+ expect(merged.map((m) => m.id)).toEqual(["m_a", "m_b"])+ })++ it("handles empty pages array", async () => {+ const { mergeMessagesPages } = await loadHook()+ expect(mergeMessagesPages([])).toEqual([])+ })+})diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 44c747ba5..c3d545494 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -2,10 +2,11 @@import {useInfiniteQuery,+ useQueryClient,type UseInfiniteQueryResult,type InfiniteData,} from "@tanstack/react-query"-import { useEffect, useMemo } from "react"+import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { Msg } from "@/components/community/_types"@@ -14,12 +15,16 @@ import { flushPendingReads } from "@/hooks/community/mutations/messages"/*** Fetches paginated messages for a community channel.*- * Uses `useInfiniteQuery` with a cursor pageParam matching the server's- * `?cursor=` param (format `createdAt|id`, materialised by- * `lib/community/messages.ts:parseCursor`). Each fetched page prepends- * older-than-cursor rows before the current messages; consumers concatenate- * `data.pages.flatMap(p => p.messages)` in the order the server returned- * (already reversed to chronological ascending inside the route).+ * Bi-directional after A2: an anchor window centred on the viewer's+ * `lastReadMessageId` (or a jump-target id) may sit in the middle of history,+ * so pagination now flows both up (older, via `fetchOlder`) and down (newer,+ * via `fetchNewer`). Legacy "newest page" behaviour is preserved for the case+ * where no anchor is provided.+ *+ * TanStack convention: `fetchNextPage` appends to `pages`, `fetchPreviousPage`+ * prepends. We map "next" → older (further into the past = further along the+ * infinite scroll direction) and "previous" → newer, then expose them under+ * `fetchOlder` / `fetchNewer` so callers never see the TanStack naming.** The query key nests under `communityKeys.channelMessages(channelId)` so a* single `invalidateQueries({ queryKey: communityKeys.channelMessages(id) })`@@ -27,142 +32,406 @@ import { flushPendingReads } from "@/hooks/community/mutations/messages"*/export type MessagesPage = {messages: Msg[]- hasMore: boolean+ latestSeq?: number+ // Anchor / since mode+ hasMoreOlder?: boolean+ hasMoreNewer?: boolean+ olderCursor?: string+ newerCursor?: string+ // Legacy (newest + older continuation) mode+ hasMore?: booleancursor?: string}+// Discriminated pageParam. The queryFn dispatches on `mode` — the URL param+// map is: newest → no param, older → cursor, newer/since → since, anchor →+// anchor. Since is reserved for future direct catch-up (Commit C); A2 never+// fires it, but the type covers it so the server contract stays honest.+export type MessagesPageParam =+ | { mode: "newest" }+ | { mode: "anchor"; anchor: string }+ | { mode: "since"; since: string }+ | { mode: "older"; cursor: string }+ | { mode: "newer"; cursor: string }++function buildMessagesUrl(base: string, pageParam: MessagesPageParam): string {+ const params = new URLSearchParams()+ switch (pageParam.mode) {+ case "newest":+ break+ case "older":+ params.set("cursor", pageParam.cursor)+ break+ case "newer":+ params.set("since", pageParam.cursor)+ break+ case "since":+ params.set("since", pageParam.since)+ break+ case "anchor":+ params.set("anchor", pageParam.anchor)+ break+ }+ const qs = params.toString()+ return qs ? `${base}?${qs}` : base+}+export const channelMessagesQueryFn =(channelId: string) =>- async ({ pageParam }: { pageParam: string | null | undefined }): Promise<MessagesPage> => {- const params = new URLSearchParams()- if (pageParam) params.set("cursor", pageParam)- const url = `/api/community/channels/${channelId}/messages${params.toString() ? `?${params}` : ""}`- return apiFetch<MessagesPage>(url)+ async ({ pageParam }: { pageParam: MessagesPageParam }): Promise<MessagesPage> => {+ return apiFetch<MessagesPage>(+ buildMessagesUrl(`/api/community/channels/${channelId}/messages`, pageParam),+ )}export const dmMessagesQueryFn =(dmId: string) =>- async ({ pageParam }: { pageParam: string | null | undefined }): Promise<MessagesPage> => {- const params = new URLSearchParams()- if (pageParam) params.set("cursor", pageParam)- const url = `/api/community/dm/${dmId}/messages${params.toString() ? `?${params}` : ""}`- return apiFetch<MessagesPage>(url)+ async ({ pageParam }: { pageParam: MessagesPageParam }): Promise<MessagesPage> => {+ return apiFetch<MessagesPage>(+ buildMessagesUrl(`/api/community/dm/${dmId}/messages`, pageParam),+ )+ }++/**+ * Merge all pages into a single chronological ASC list, deduping by id.+ * Extracted so tests can drive the reducer without spinning up a full hook.+ *+ * Pages arrive out of order — the initial page may be an anchor window in the+ * middle of history, then older pages append below and newer pages prepend+ * above. Sort once at the end so the visible order is always correct+ * regardless of fetch sequence. Bounded by loaded rows (typically < 500) —+ * O(n log n) is fine here.+ */+export function mergeMessagesPages(pages: MessagesPage[]): Msg[] {+ const all: Msg[] = []+ for (const p of pages) {+ for (const m of p.messages) all.push(m)}+ all.sort((a, b) => {+ const ta = a.createdAt ? new Date(a.createdAt).getTime() : 0+ const tb = b.createdAt ? new Date(b.createdAt).getTime() : 0+ if (ta !== tb) return ta - tb+ if (a.id < b.id) return -1+ if (a.id > b.id) return 1+ return 0+ })+ const seen = new Set<string>()+ const out: Msg[] = []+ for (const m of all) {+ if (seen.has(m.id)) continue+ seen.add(m.id)+ out.push(m)+ }+ return out+}-type MessagesReturn = UseInfiniteQueryResult<InfiniteData<MessagesPage>, Error> & {+// Fix 4 window: how stale a hydrated cache may be before a mount fires an+// invalidate. Short enough that a returning tab picks up fresh data on the+// first paint, long enough that rapid channel switching within a single+// session doesn't churn the network — the reconnect handler in+// `useCommunityWs` covers longer offline gaps on its own.+const STALE_HYDRATED_CACHE_MS = 30_000++type PageCache = InfiniteData<MessagesPage, MessagesPageParam>++type MessagesReturn = UseInfiniteQueryResult<PageCache, Error> & {messages: Msg[]- hasMore: boolean- fetchOlder: () => void+ latestSeq: number+ hasMoreOlder: boolean+ hasMoreNewer: booleanisFetchingOlder: boolean+ isFetchingNewer: boolean+ fetchOlder: () => void+ fetchNewer: () => void+ jumpToPresent: () => void+ // Legacy alias — mirrors `hasMoreOlder`. Kept so consumers not yet migrated+ // off the older-only API still compile until every call site is updated.+ hasMore: boolean}-/**- * Hook wrapper around `useInfiniteQuery` for a channel's message stream.- *- * Pass `null` for "no active channel" — the query stays disabled. DM views- * should call `useDmMessages` instead of this hook.- */-export function useMessages(channelId: string | null): MessagesReturn {- const enabled = !!channelId- const queryKey = communityKeys.channelMessages(channelId ?? "__none__")+type MessagesOpts = {+ /**+ * Anchor for the initial fetch. Undefined = read-state not resolved yet;+ * the hook stays disabled until this becomes a value or `null`. `null`+ * = no anchor (never read / DM without snapshot); goes straight to+ * newest-mode. A string = fetch `?anchor=<id>` on the first page.+ */+ lastReadMessageId?: string | null+}++// Shared pagination + reducer used by both channel and DM hooks. Kept inline+// as a hook because both variants need the same TanStack setup — factoring+// out a plain function would leak query internals; a hook stays clean.+function useMessagesInner(+ scopeId: string | null,+ queryKey: readonly unknown[],+ queryFn: ({ pageParam }: { pageParam: MessagesPageParam }) => Promise<MessagesPage>,+ opts: MessagesOpts | undefined,+): MessagesReturn {+ const queryClient = useQueryClient()++ // `undefined` = anchor snapshot is still resolving; gate the query on it+ // being a resolved value (string OR null). Owners without a snapshot+ // (currently DM) pass `null` explicitly.+ const anchorResolved = opts?.lastReadMessageId !== undefined+ const anchorId = opts?.lastReadMessageId ?? null+ const enabled = !!scopeId && anchorResolved++ // Force-newest override — flipped by `jumpToPresent`. Held in state so+ // React re-renders with the new options before the reset fires (see the+ // useEffect below). Cleared once the first newest page arrives.+ const [forceNewest, setForceNewest] = useState(false)++ const initialPageParam = useMemo<MessagesPageParam>(() => {+ if (forceNewest) return { mode: "newest" }+ if (anchorId) return { mode: "anchor", anchor: anchorId }+ return { mode: "newest" }+ }, [forceNewest, anchorId])+const query = useInfiniteQuery<MessagesPage,Error,- InfiniteData<MessagesPage>,+ PageCache,typeof queryKey,- string | null | undefined+ MessagesPageParam>({queryKey,queryFn: enabled- ? channelMessagesQueryFn(channelId!)- : (() => Promise.reject(new Error("disabled"))),- initialPageParam: null,- getNextPageParam: (last) => (last.hasMore ? (last.cursor ?? null) : undefined),+ ? queryFn+ : () => Promise.reject(new Error("disabled")),+ initialPageParam,+ // "next" = older side. `fetchNextPage` appends to `data.pages`, so the+ // LAST entry in `pages` is the oldest window we've loaded — that's the+ // page whose cursor gets consulted for the next older fetch.+ getNextPageParam: (last) => {+ const has = last.hasMoreOlder ?? last.hasMore ?? false+ if (!has) return undefined+ const cursor = last.olderCursor ?? last.cursor+ if (!cursor) return undefined+ return { mode: "older", cursor }+ },+ // "previous" = newer side. `fetchPreviousPage` prepends to `data.pages`,+ // so the FIRST entry is the newest window loaded. In legacy (newest)+ // mode `hasMoreNewer` is absent → falsy → no previous page.+ getPreviousPageParam: (first) => {+ if (!first.hasMoreNewer) return undefined+ const cursor = first.newerCursor+ if (!cursor) return undefined+ return { mode: "newer", cursor }+ },enabled,})- // Flush any pending mark-channel-read on channel switch / unmount so the- // 500ms debounce doesn't strand the last-read pointer when the user hops- // channels mid-window.+ // Flush any pending mark-read on scope switch / unmount so the 500ms+ // debounce doesn't strand the last-read pointer when the user hops+ // scopes mid-window. Same as the pre-A2 behaviour.useEffect(() => {- if (!channelId) return+ if (!scopeId) returnreturn () => {flushPendingReads()}- }, [channelId])+ }, [scopeId])++ // Two-phase reset: setForceNewest triggers a render that updates+ // `initialPageParam` to newest. THIS effect fires on that render and+ // actually clears the query, so the refetch reads the newest-mode options+ // rather than the pre-flip anchor options.+ useEffect(() => {+ if (!forceNewest) return+ void queryClient.resetQueries({ queryKey })+ }, [forceNewest, queryClient, queryKey])++ // Clear the flag once a newest-shape page lands — anchor pages carry+ // `hasMoreOlder`/`hasMoreNewer`; legacy newest carries `hasMore`. If the+ // first cached page reads as legacy, the jump succeeded.+ useEffect(() => {+ if (!forceNewest) return+ const first = query.data?.pages[0]+ if (!first) return+ const isNewestShape = first.hasMore !== undefined && first.hasMoreOlder === undefined+ if (isNewestShape) setForceNewest(false)+ }, [forceNewest, query.data])++ // Fix 3 — anchor re-validation.+ //+ // When a persisted cache is rehydrated, TanStack uses the cached `pages`+ // even if `initialPageParam` says "anchor at m_42". If m_42 isn't in the+ // hydrated window (e.g. the persisted cache was a newest-tail and the+ // read pointer has since advanced past it), `newDividerBefore` computes+ // to `undefined` and the list snaps to bottom — no NEW divider, wrong+ // position.+ //+ // Detect that shape and reset the query so it refetches under the correct+ // anchor pageParam. Fire exactly once per (scopeId, anchorId) pair via a+ // ref — a subsequent watermark tick that advances lastReadMessageId is a+ // different pair and gets its own single reset opportunity.+ const anchorResetKeyRef = useRef<string | null>(null)+ useEffect(() => {+ if (!enabled) return+ if (!anchorId) return+ if (query.isFetching) return+ if (query.isPending) return+ const pages = query.data?.pages+ if (!pages || pages.length === 0) return+ let messageCount = 0+ let anchorFound = false+ for (const p of pages) {+ messageCount += p.messages.length+ if (!anchorFound) {+ for (const m of p.messages) {+ if (m.id === anchorId) {+ anchorFound = true+ break+ }+ }+ }+ }+ if (messageCount === 0) return+ if (anchorFound) return+ const resetKey = `${scopeId ?? ""}::${anchorId}`+ if (anchorResetKeyRef.current === resetKey) return+ anchorResetKeyRef.current = resetKey+ void queryClient.resetQueries({ queryKey })+ }, [+ enabled,+ anchorId,+ scopeId,+ query.data,+ query.isFetching,+ query.isPending,+ queryClient,+ queryKey,+ ])++ // Fix 4 — staleness invalidate on mount / scope switch ONLY.+ //+ // When the cache is hydrated from IDB, `dataUpdatedAt` reflects the last+ // fetch of the previous session. TanStack won't refetch on mount for+ // infinite queries by default, so the client keeps rendering the stale+ // window even though `latestSeq` on the server may have advanced. On+ // mount, if the hydrated window is older than the freshness window, kick+ // off an invalidation — TanStack re-runs every persisted `pageParam` and+ // the fresh `latestSeq` in the server response drives `unreadCount` and+ // `hasMoreNewer` to the truth without any client bookkeeping.+ //+ // Fires EXACTLY ONCE per scope (channelId / dmId), gated by a scopeId ref.+ // Previously the effect had `query.dataUpdatedAt` in its dep list, which+ // re-evaluated on every fetch complete — including AFTER an optimistic+ // send stayed in-place past 30s of stillness. Any such re-eval could+ // invalidate the cache, refetch server pages, and drop the just-sent+ // (already reconciled) row visually before the WS broadcast caught up.+ // Locking to "one shot per scope" preserves the mount-time invariant+ // (hydrated-and-stale gets refreshed) without ever firing again for the+ // same open scope. WS reconnect + user-initiated navigation cover any+ // subsequent freshness needs.+ const staleCacheCheckedScopeRef = useRef<string | null>(null)+ useEffect(() => {+ if (!enabled) return+ if (!scopeId) return+ if (staleCacheCheckedScopeRef.current === scopeId) return+ if (query.isFetching) return+ if (query.isPending) return+ const updatedAt = query.dataUpdatedAt+ if (!updatedAt) return+ staleCacheCheckedScopeRef.current = scopeId+ if (Date.now() - updatedAt < STALE_HYDRATED_CACHE_MS) return+ void queryClient.invalidateQueries({ queryKey })+ }, [+ enabled,+ scopeId,+ query.dataUpdatedAt,+ query.isFetching,+ query.isPending,+ queryClient,+ queryKey,+ ])const messages = useMemo<Msg[]>(() => {if (!query.data) return []- // Pages are returned newest-first cursor-wise; the server reverses inside- // each page so each page's messages are already ASC. Concatenating in- // page order gives chronological ASC across the whole stream — matches- // what the context previously produced by prepending older rows.- const out: Msg[] = []- for (let i = query.data.pages.length - 1; i >= 0; i--) {- out.push(...query.data.pages[i].messages)+ return mergeMessagesPages(query.data.pages)+ }, [query.data])++ const latestSeq = useMemo<number>(() => {+ if (!query.data) return 0+ let max = 0+ for (const p of query.data.pages) {+ const s = p.latestSeq ?? 0+ if (s > max) max = s}- return out+ return max}, [query.data])- const lastPage = query.data?.pages[query.data.pages.length - 1]- const hasMore = lastPage?.hasMore ?? false+ const pages = query.data?.pages ?? []+ const oldestPage = pages[pages.length - 1]+ const newestPage = pages[0]+ const hasMoreOlder = (oldestPage?.hasMoreOlder ?? oldestPage?.hasMore) ?? false+ const hasMoreNewer = newestPage?.hasMoreNewer ?? false++ // Callbacks depend on `query.*` fields that TanStack refreshes on every+ // internal state change — closing over the whole query object keeps the+ // exhaustive-deps rule happy without spelling every subfield.+ const fetchOlder = useCallback(() => {+ if (!query.hasNextPage) return+ if (query.isFetchingNextPage) return+ void query.fetchNextPage()+ }, [query])++ const fetchNewer = useCallback(() => {+ if (!query.hasPreviousPage) return+ if (query.isFetchingPreviousPage) return+ void query.fetchPreviousPage()+ }, [query])++ const jumpToPresent = useCallback(() => {+ setForceNewest(true)+ }, [])return {...query,messages,- hasMore,- fetchOlder: () => {- if (!query.hasNextPage) return- if (query.isFetchingNextPage) return- void query.fetchNextPage()- },+ latestSeq,+ hasMoreOlder,+ hasMoreNewer,isFetchingOlder: query.isFetchingNextPage,+ isFetchingNewer: query.isFetchingPreviousPage,+ fetchOlder,+ fetchNewer,+ jumpToPresent,+ hasMore: hasMoreOlder,}}+/**+ * Hook wrapper around `useInfiniteQuery` for a channel's message stream.+ *+ * Pass `null` for "no active channel" — the query stays disabled. DM views+ * should call `useDmMessages` instead of this hook.+ */+export function useMessages(+ channelId: string | null,+ opts?: MessagesOpts,+): MessagesReturn {+ const queryKey = communityKeys.channelMessages(channelId ?? "__none__")+ return useMessagesInner(+ channelId,+ queryKey,+ channelMessagesQueryFn(channelId ?? "__none__"),+ opts,+ )+}+/*** DM-scoped sibling of `useMessages`. Same pagination shape, different route.*/-export function useDmMessages(dmId: string | null): MessagesReturn {- const enabled = !!dmId+export function useDmMessages(+ dmId: string | null,+ opts?: MessagesOpts,+): MessagesReturn {const queryKey = communityKeys.dmMessages(dmId ?? "__none__")- const query = useInfiniteQuery<- MessagesPage,- Error,- InfiniteData<MessagesPage>,- typeof queryKey,- string | null | undefined- >({+ return useMessagesInner(+ dmId,queryKey,- queryFn: enabled- ? dmMessagesQueryFn(dmId!)- : (() => Promise.reject(new Error("disabled"))),- initialPageParam: null,- getNextPageParam: (last) => (last.hasMore ? (last.cursor ?? null) : undefined),- enabled,- })-- const messages = useMemo<Msg[]>(() => {- if (!query.data) return []- const out: Msg[] = []- for (let i = query.data.pages.length - 1; i >= 0; i--) {- out.push(...query.data.pages[i].messages)- }- return out- }, [query.data])-- const lastPage = query.data?.pages[query.data.pages.length - 1]- const hasMore = lastPage?.hasMore ?? false-- return {- ...query,- messages,- hasMore,- fetchOlder: () => {- if (!query.hasNextPage) return- if (query.isFetchingNextPage) return- void query.fetchNextPage()- },- isFetchingOlder: query.isFetchingNextPage,- }+ dmMessagesQueryFn(dmId ?? "__none__"),+ opts,+ )}diff --git a/src/web/src/hooks/use-file-attachments.test.ts b/src/web/src/hooks/use-file-attachments.test.tsnew file mode 100644index 000000000..31d66f9be--- /dev/null+++ b/src/web/src/hooks/use-file-attachments.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect } from "vitest"+import { isMimeAllowed } from "./use-file-attachments"++// Pin the MIME allowlist logic against the server-side `mimeAllowed` in+// `src/web/src/lib/community/upload.ts`. Both must agree — if this fires the+// client filter and the server would still reject, users see two rejections+// for one upload; if the client accepts and server rejects, users see the+// dreaded generic "file type not allowed" 400 after the round-trip.+describe("isMimeAllowed", () => {+ const ATTACHMENT_ALLOWED = [+ "image/",+ "video/",+ "audio/",+ "application/pdf",+ "text/",+ ] as const++ it("prefix entries match by prefix", () => {+ expect(isMimeAllowed("image/png", ATTACHMENT_ALLOWED)).toBe(true)+ expect(isMimeAllowed("image/jpeg", ATTACHMENT_ALLOWED)).toBe(true)+ expect(isMimeAllowed("video/mp4", ATTACHMENT_ALLOWED)).toBe(true)+ expect(isMimeAllowed("audio/mpeg", ATTACHMENT_ALLOWED)).toBe(true)+ expect(isMimeAllowed("text/plain", ATTACHMENT_ALLOWED)).toBe(true)+ expect(isMimeAllowed("text/markdown", ATTACHMENT_ALLOWED)).toBe(true)+ expect(isMimeAllowed("text/csv", ATTACHMENT_ALLOWED)).toBe(true)+ })++ it("exact-match entries require full equality", () => {+ expect(isMimeAllowed("application/pdf", ATTACHMENT_ALLOWED)).toBe(true)+ // Not a prefix match — the entry is `application/pdf`, not `application/`.+ expect(isMimeAllowed("application/zip", ATTACHMENT_ALLOWED)).toBe(false)+ expect(isMimeAllowed("application/x-zip-compressed", ATTACHMENT_ALLOWED)).toBe(false)+ expect(isMimeAllowed("application/octet-stream", ATTACHMENT_ALLOWED)).toBe(false)+ })++ it("empty content-type is rejected", () => {+ // Browsers report `""` for files whose type can't be sniffed. Server+ // would 400 these too — align.+ expect(isMimeAllowed("", ATTACHMENT_ALLOWED)).toBe(false)+ })++ it("respects a bare exact-only list (no prefixes)", () => {+ const ICONS_ONLY = ["image/png", "image/jpeg", "image/webp", "image/gif"] as const+ expect(isMimeAllowed("image/png", ICONS_ONLY)).toBe(true)+ expect(isMimeAllowed("image/svg+xml", ICONS_ONLY)).toBe(false)+ expect(isMimeAllowed("video/mp4", ICONS_ONLY)).toBe(false)+ })+})diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.tsindex 2e009201f..48ce32917 100644--- a/src/web/src/hooks/use-file-attachments.ts+++ b/src/web/src/hooks/use-file-attachments.ts@@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useRef, useState } from "react";import { toast } from "sonner";import { generateThumbnail } from "../lib/image-thumbnail";-const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB+const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MBexport type PendingFile = {file: File;@@ -10,13 +10,51 @@ export type PendingFile = {thumbnailBlob: Blob | null;};+export type UseFileAttachmentsOptions = {+ /** Per-file byte ceiling. Defaults to 10 MB. */+ maxFileSize?: number;+ /**+ * Whitelist of allowed MIME prefixes. An entry ending in `/` (e.g.+ * `"image/"`) matches any MIME with that prefix; otherwise the full+ * MIME string must match exactly (e.g. `"application/pdf"`). When+ * unset, all MIMEs are accepted — that's the historical behavior. Pass+ * the server-side allowlist here so drag-drop AND file-picker paths+ * both reject unsupported types at the client boundary instead of+ * failing on upload.+ */+ allowedMimePrefixes?: readonly string[];+};+function revokeThumbnailUrls(files: PendingFile[]) {for (const pf of files) {if (pf.thumbnailUrl) URL.revokeObjectURL(pf.thumbnailUrl);}}-export function useFileAttachments() {+/**+ * MIME allowlist check. Mirrors the server-side `mimeAllowed` in+ * `src/web/src/lib/community/upload.ts`: an allowlist entry ending in `/`+ * (e.g. `"image/"`) matches any MIME with that prefix; otherwise the full+ * MIME string must match exactly (e.g. `"application/pdf"`). Exported for+ * unit tests — do not depend on it from outside this file.+ */+export function isMimeAllowed(contentType: string, allowed: readonly string[]): boolean {+ if (!contentType) return false;+ return allowed.some((entry) =>+ entry.endsWith("/") ? contentType.startsWith(entry) : contentType === entry,+ );+}++export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {+ const maxFileSize = opts.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;+ const allowedMimePrefixes = opts.allowedMimePrefixes;+ // Options are read via ref so `addPendingFiles`'s stable identity survives+ // caller re-renders — callers pass the constant array from shared+ // constants but the reference identity isn't guaranteed after HMR.+ const optsRef = useRef({ maxFileSize, allowedMimePrefixes });+ useEffect(() => {+ optsRef.current = { maxFileSize, allowedMimePrefixes };+ });const [pendingFiles, _setPendingFiles] = useState<PendingFile[]>([]);const pendingFilesRef = useRef(pendingFiles);useEffect(() => {@@ -40,13 +78,19 @@ export function useFileAttachments() {const fileInputRef = useRef<HTMLInputElement>(null);const addPendingFiles = useCallback(async (files: File[]) => {+ const { maxFileSize: maxSize, allowedMimePrefixes: allowed } = optsRef.current;const valid: File[] = [];for (const file of files) {- if (file.size > MAX_FILE_SIZE) {- toast.error(`"${file.name}" exceeds 10 MB limit`);- } else {- valid.push(file);+ if (file.size > maxSize) {+ const mb = Math.floor(maxSize / 1024 / 1024);+ toast.error(`"${file.name}" exceeds ${mb} MB limit`);+ continue;+ }+ if (allowed && !isMimeAllowed(file.type, allowed)) {+ toast.error(`"${file.name}" — file type not allowed`);+ continue;}+ valid.push(file);}if (valid.length === 0) return;diff --git a/src/web/src/lib/community/channel-ref-extension.test.ts b/src/web/src/lib/community/channel-ref-extension.test.tsindex 3dcf362c5..8d70d52e9 100644--- a/src/web/src/lib/community/channel-ref-extension.test.ts+++ b/src/web/src/lib/community/channel-ref-extension.test.ts@@ -144,6 +144,31 @@ describe("buildCommunityChannelRefExtension — renderText/renderHTML", () => {const spec = renderHTML({ options: { HTMLAttributes: {} }, node: { attrs: { label: null, id: "chn_abc" } } })expect(spec).toEqual(["span", {}, "/chn_abc"])})++ it("renderText NEVER emits a literal `/null/<id>` when serverId is unset (regression guard)", () => {+ // The `serverId` attribute default is `null`; a paste-from-HTML,+ // drag-drop, or future keyboard flow that commits a node without+ // setting `serverId` used to produce `"/null/chn_abc"` on the wire,+ // rendering as literal broken text to every recipient. Fall back to+ // the visible `/label` (matching renderHTML's own fallback) so the+ // ref stays readable even in this degraded path.+ const { ext } = build()+ const { renderText } = getRenderFns(ext)+ expect(+ renderText({ node: { attrs: { id: "chn_abc", serverId: null, label: "general" } } }),+ ).not.toContain("null")+ expect(+ renderText({ node: { attrs: { id: "chn_abc", serverId: null, label: "general" } } }),+ ).toBe("/general")+ })++ it("renderText emits empty string when neither serverId nor label is present", () => {+ const { ext } = build()+ const { renderText } = getRenderFns(ext)+ expect(+ renderText({ node: { attrs: { id: "chn_abc", serverId: null, label: null } } }),+ ).toBe("")+ })})describe("buildCommunityChannelRefExtension — keyboard callback", () => {diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.tsindex fc40029a9..735607f03 100644--- a/src/web/src/lib/community/channel-ref-extension.ts+++ b/src/web/src/lib/community/channel-ref-extension.ts@@ -13,7 +13,7 @@ export type ChannelRefCandidate = {// comment on the `name` → `label` mapping). Mirrors// `MentionPopupState.command`'s own mapped-shape typing in// `mention-extension.ts`.-export type ChannelRefCommandProps = { id: string; label: string; serverId: string }+type ChannelRefCommandProps = { id: string; label: string; serverId: string }export interface ChannelRefPopupState {items: ChannelRefCandidate[]@@ -114,7 +114,17 @@ export function buildCommunityChannelRefExtension(opts: {return ChannelRefNode.configure({HTMLAttributes: { class: "channel-ref-highlight" },- renderText: ({ node }) => `/${node.attrs.serverId}/${node.attrs.id}`,+ // `serverId` has `default: null`; paste-from-HTML, drag-drop, or any+ // future flow that commits the node without setting it would otherwise+ // emit the literal string `"/null/<channelId>"` on the wire. Fall back+ // to the visible label so the recipient reads a real word instead of+ // a broken pill — degraded, but not misleading. The command flow that+ // DOES set both fields (Enter/Tab on a suggestion) is unaffected.+ renderText: ({ node }) => {+ const { serverId, id, label } = node.attrs as { serverId?: string | null; id?: string; label?: string }+ if (!serverId || !id) return label ? `/${label}` : ""+ return `/${serverId}/${id}`+ },renderHTML: ({ options, node }) => ["span", options.HTMLAttributes, `/${node.attrs.label ?? node.attrs.id}`],suggestion: {char: "/",diff --git a/src/web/src/lib/community/channel-ref.ts b/src/web/src/lib/community/channel-ref.tsindex 2bb04fdb7..3dfdc7528 100644--- a/src/web/src/lib/community/channel-ref.ts+++ b/src/web/src/lib/community/channel-ref.ts@@ -7,8 +7,8 @@ import { parseRef } from "@alook/shared"* (`resolveServerByNameForMember`/`resolveChannelByNameForMember`), scoped to* whatever servers/channels the client already has loaded.*/-export type ChannelRefDirectoryChannel = { id: string; name: string }-export type ChannelRefDirectoryServer = {+type ChannelRefDirectoryChannel = { id: string; name: string }+type ChannelRefDirectoryServer = {id: stringname: stringchannels: ChannelRefDirectoryChannel[]diff --git a/src/web/src/lib/community/fanout.test.ts b/src/web/src/lib/community/fanout.test.tsindex b6ee6d8fe..01844c68d 100644--- a/src/web/src/lib/community/fanout.test.ts+++ b/src/web/src/lib/community/fanout.test.ts@@ -17,7 +17,6 @@ vi.mock("@alook/shared", async () => {error: vi.fn(),debug: vi.fn(),}),- createDb: vi.fn(() => ({})),queries: {communityMember: {listMembers: (...a: unknown[]) => mockListMembers(...a),@@ -33,6 +32,10 @@ vi.mock("@alook/shared", async () => {}})+vi.mock("../db", () => ({+ getDb: vi.fn(() => ({})),+}))+const mockBroadcastToUser = vi.fn()vi.mock("../broadcast", () => ({broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),diff --git a/src/web/src/lib/community/fanout.ts b/src/web/src/lib/community/fanout.tsindex d76596867..5e3f29b2a 100644--- a/src/web/src/lib/community/fanout.ts+++ b/src/web/src/lib/community/fanout.ts@@ -13,8 +13,9 @@*/import { getCloudflareContext } from "@opennextjs/cloudflare"-import { createDb, queries, createLogger, WS_EVENTS } from "@alook/shared"-import type { CommunityWsEvent } from "@alook/shared"+import { queries, createLogger, WS_EVENTS } from "@alook/shared"+import type { CommunityWsEvent, Database } from "@alook/shared"+import { getDb } from "../db"import { broadcastToUser } from "../broadcast"import { enqueueBotWakes, type WakeMessageRow } from "./wake-producer"@@ -35,14 +36,14 @@ type WakeOpts = { wakeMessageRow?: WakeMessageRow }/*** Resolves all member user IDs for a server.*/-async function getServerMemberUserIds(db: ReturnType<typeof createDb>, serverId: string): Promise<string[]> {+async function getServerMemberUserIds(db: Database, serverId: string): Promise<string[]> {return queries.communityMember.listMemberUserIds(db, serverId)}/*** Resolves the server a channel belongs to, then returns all member user IDs.*/-async function getChannelRecipientUserIds(db: ReturnType<typeof createDb>, channelId: string): Promise<string[]> {+async function getChannelRecipientUserIds(db: Database, channelId: string): Promise<string[]> {const channel = await queries.communityChannel.getChannel(db, channelId)if (!channel) {log.warn("fanOutToChannel: channel not found", { channelId })@@ -61,7 +62,7 @@ export async function fanOutToChannel(): Promise<void> {try {const { env } = getCloudflareContext()- const db = createDb((env as Env).DB)+ const db = getDb((env as Env).DB)const userIds = await getChannelRecipientUserIds(db, channelId)await broadcastToRecipients(userIds, event, opts?.excludeUserId)maybeEnqueueWakes(event, userIds, { channelId }, opts)@@ -84,7 +85,7 @@ export async function fanOutToDM(): Promise<void> {try {const { env } = getCloudflareContext()- const db = createDb((env as Env).DB)+ const db = getDb((env as Env).DB)const dm = await queries.communityDm.getDM(db, dmConversationId)if (!dm) {log.warn("fanOutToDM: DM conversation not found", { dmConversationId })@@ -137,7 +138,7 @@ export async function fanOutToServerMembers(): Promise<void> {try {const { env } = getCloudflareContext()- const db = createDb((env as Env).DB)+ const db = getDb((env as Env).DB)const userIds = await getServerMemberUserIds(db, serverId)await broadcastToRecipients(userIds, event, opts?.excludeUserId)} catch (err) {diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.tsindex 74af8b26d..2ae7eb35c 100644--- a/src/web/src/lib/community/messages.ts+++ b/src/web/src/lib/community/messages.ts@@ -15,6 +15,14 @@ export function parseCursor(cursorParam: string | null): { createdAt: string; idreturn 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.@@ -57,6 +65,46 @@ export function buildPaginatedResponse<T extends { createdAt: string; id: stringreturn { items, hasMore, cursor }}+// Compose the anchor-mode response envelope. `older` arrives DESC (newest of+// the older half first); reverse it before concatenation so the caller gets one+// chronological ASC array. Cursors point at the boundary rows: `olderCursor`+// = the oldest returned row, `newerCursor` = the newest.+export function buildAnchorResponse<T extends { createdAt: string; id: string }>(+ older: T[],+ newer: T[],+ opts: { hasMoreOlder: boolean; hasMoreNewer: boolean },+): {+ items: T[]+ hasMoreOlder: boolean+ hasMoreNewer: boolean+ olderCursor: string | undefined+ newerCursor: string | undefined+} {+ const olderAsc = [...older].reverse()+ const items = [...olderAsc, ...newer]+ const olderCursor = opts.hasMoreOlder && items.length > 0+ ? `${items[0].createdAt}|${items[0].id}`+ : undefined+ const newerCursor = opts.hasMoreNewer && items.length > 0+ ? `${items[items.length - 1].createdAt}|${items[items.length - 1].id}`+ : undefined+ return { items, hasMoreOlder: opts.hasMoreOlder, hasMoreNewer: opts.hasMoreNewer, olderCursor, newerCursor }+}++// Compose the since-mode response envelope. Rows arrive ASC with `+1` extra+// probe; slice off the probe and encode `newerCursor` as the newest row.+export function buildSinceResponse<T extends { createdAt: string; id: string }>(+ rows: T[],+ pageSize: number,+): { items: T[]; hasMoreNewer: boolean; newerCursor: string | undefined } {+ const hasMoreNewer = rows.length > pageSize+ const items = hasMoreNewer ? rows.slice(0, pageSize) : rows+ const newerCursor = hasMoreNewer && items.length > 0+ ? `${items[items.length - 1].createdAt}|${items[items.length - 1].id}`+ : undefined+ return { items, hasMoreNewer, newerCursor }+}+// Build a paginated member response — same shape as buildPaginatedResponse but// the cursor is keyed on `joinedAt`. The shared query returns `hasMore` + a// typed `{ joinedAt, id }` cursor already; this helper encodes that as thediff --git a/src/web/src/lib/community/wake-producer.test.ts b/src/web/src/lib/community/wake-producer.test.tsindex cf1e67271..fb01f18a4 100644--- a/src/web/src/lib/community/wake-producer.test.ts+++ b/src/web/src/lib/community/wake-producer.test.ts@@ -17,7 +17,6 @@ vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return {...actual,- createDb: vi.fn(() => ({})),createLogger: () => ({info: (...a: unknown[]) => mockInfo(...a),warn: (...a: unknown[]) => mockWarn(...a),@@ -32,6 +31,10 @@ vi.mock("@alook/shared", async () => {}})+vi.mock("../db", () => ({+ getDb: vi.fn(() => ({})),+}))+const mockQueueSend = vi.fn()const mockDevHttpSend = vi.fn()const mockCreateQueueWakeTransport = vi.fn(() => ({ send: mockQueueSend }))diff --git a/src/web/src/lib/community/wake-producer.ts b/src/web/src/lib/community/wake-producer.tsindex 77893d76c..afb2857f8 100644--- a/src/web/src/lib/community/wake-producer.ts+++ b/src/web/src/lib/community/wake-producer.ts@@ -17,8 +17,9 @@* `wrangler dev`/`next dev` processes today).*/import { getCloudflareContext } from "@opennextjs/cloudflare"-import { createDb, queries, createLogger } from "@alook/shared"+import { queries, createLogger } from "@alook/shared"import type { WakePayload } from "@alook/shared"+import { getDb } from "../db"import { createQueueWakeTransport, createDevHttpWakeTransport } from "./wake-transport"import type { WakeTransport } from "./wake-transport"@@ -90,7 +91,7 @@ async function doEnqueueBotWakes(env: Env, opts: EnqueueBotWakesOpts): Promise<vconst { recipients, channelId, dmConversationId, messageRow } = optsif (recipients.length === 0) return- const db = createDb(env.DB)+ const db = getDb(env.DB)const candidates = await queries.communityBot.findWakeCandidates(db, {recipients,channelId,diff --git a/src/web/src/lib/query-client.ts b/src/web/src/lib/query-client.tsindex 35aade25b..19d094b1e 100644--- a/src/web/src/lib/query-client.ts+++ b/src/web/src/lib/query-client.ts@@ -1,4 +1,5 @@import { QueryClient } from "@tanstack/react-query"+import { PERSIST_MAX_AGE_MS } from "@/lib/query-persister"/*** Factory for a QueryClient with app defaults.@@ -8,12 +9,18 @@ import { QueryClient } from "@tanstack/react-query"* from being reset by React strict-mode double-invocation in dev, keeps SSR* safe (no module-scoped client shared across requests), and gives tests a* fresh client per render.+ *+ * `gcTime` matches the persister's `maxAge` so TanStack doesn't garbage-collect+ * inactive queries before the persister has a chance to write them out — the+ * TanStack docs are explicit that `gcTime >= maxAge` or restore returns empty+ * caches for anything the user hasn't touched in the current session.*/export function createQueryClient(): QueryClient {return new QueryClient({defaultOptions: {queries: {staleTime: 5_000,+ gcTime: PERSIST_MAX_AGE_MS,refetchOnWindowFocus: false,retry: 1,},diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex 094b9eb7a..334eb3a66 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -63,6 +63,11 @@ export const communityKeys = {// anchored while the watermark advances.channelReadStateSnapshot: (channelId: string) =>[...communityKeys.all, "channel", channelId, "read-state-snapshot"] as const,+ // DM sibling of `channelReadStateSnapshot`. Same freeze semantics — the+ // hook latches the first non-null response so the "New" divider anchor+ // stays put while the progressive watermark advances.+ dmReadStateSnapshot: (dmId: string) =>+ [...communityKeys.all, "dm", dmId, "read-state-snapshot"] as const,// Single hydrated message (opener block, deep-link previews).message: (messageId: string) =>diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.tsnew file mode 100644index 000000000..458dfcfdc--- /dev/null+++ b/src/web/src/lib/query-persister.test.ts@@ -0,0 +1,412 @@+import "fake-indexeddb/auto"+import { describe, expect, it, beforeEach } from "vitest"+import { get } from "idb-keyval"+import { QueryClient } from "@tanstack/react-query"+import type { PersistedClient } from "@tanstack/react-query-persist-client"+import { communityKeys } from "@/lib/query-keys"+import {+ clearPersistedCache,+ createIdbPersister,+ isTrustedMessagesPageZero,+ shouldPersistQuery,+ shouldPersistQueryKey,+} from "@/lib/query-persister"+import type { MessagesPage } from "@/hooks/community/use-messages"++// ── shouldPersistQueryKey ─────────────────────────────────────────────────++describe("shouldPersistQueryKey", () => {+ it("persists channel message queries", () => {+ expect(shouldPersistQueryKey(communityKeys.channelMessages("ch_1"))).toBe(true)+ })++ it("persists DM message queries", () => {+ expect(shouldPersistQueryKey(communityKeys.dmMessages("dm_1"))).toBe(true)+ })++ it("does NOT persist channel read-state snapshot (refetched on every mount)", () => {+ expect(+ shouldPersistQueryKey(communityKeys.channelReadStateSnapshot("ch_1")),+ ).toBe(false)+ })++ it("does NOT persist DM read-state snapshot (refetched on every mount)", () => {+ expect(+ shouldPersistQueryKey(communityKeys.dmReadStateSnapshot("dm_1")),+ ).toBe(false)+ })++ it("does NOT persist server list, presence, members, or machines", () => {+ expect(shouldPersistQueryKey(communityKeys.servers())).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.presence("srv_1"))).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.members("srv_1"))).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.machines())).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.friends())).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.dms())).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.inbox())).toBe(false)+ })++ it("does NOT persist pins/threads/forum posts (message-related but ephemeral)", () => {+ expect(shouldPersistQueryKey(communityKeys.pins("ch_1"))).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.threads("ch_1"))).toBe(false)+ expect(shouldPersistQueryKey(communityKeys.forumPosts("ch_1"))).toBe(false)+ })++ it("returns false for keys outside the community namespace", () => {+ expect(shouldPersistQueryKey(["auth", "session"])).toBe(false)+ expect(shouldPersistQueryKey([])).toBe(false)+ })+})++// ── createIdbPersister: serialize scrubbing ───────────────────────────────++function makePage(messages: Array<Partial<MessagesPage["messages"][number]>>): MessagesPage {+ return {+ messages: messages as MessagesPage["messages"],+ hasMore: false,+ latestSeq: 0,+ }+}++async function readPersistedBlob(userId: string | null): Promise<PersistedClient> {+ const raw = await get<string>(+ `alook:qc:v1:${userId ?? "anon"}:client`,+ )+ if (!raw) throw new Error("no persisted blob")+ return JSON.parse(raw) as PersistedClient+}++describe("createIdbPersister — serialize filter", () => {+ beforeEach(async () => {+ await clearPersistedCache("u_1")+ await clearPersistedCache(null)+ })++ it("strips temp_* rows from persisted channel message pages", async () => {+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.channelMessages("ch_1"), {+ pages: [+ makePage([+ { id: "m_real_1", content: "keep", createdAt: "2026-07-01T00:00:00.000Z" },+ { id: "temp_abc", content: "drop", createdAt: "2026-07-01T00:00:01.000Z" },+ { id: "m_real_2", content: "keep", createdAt: "2026-07-01T00:00:02.000Z" },+ ]),+ ],+ pageParams: [{ mode: "newest" }],+ })++ const persister = createIdbPersister("u_1")+ await persister.persistClient({+ timestamp: Date.now(),+ buster: "v1",+ clientState: {+ mutations: [],+ queries: [+ {+ queryKey: communityKeys.channelMessages("ch_1"),+ queryHash: JSON.stringify(communityKeys.channelMessages("ch_1")),+ state: qc.getQueryState(communityKeys.channelMessages("ch_1"))!,+ },+ ],+ },+ })++ const blob = await readPersistedBlob("u_1")+ const q = blob.clientState.queries[0]+ const data = q.state.data as { pages: MessagesPage[] }+ expect(data.pages[0].messages.map((m) => m.id)).toEqual([+ "m_real_1",+ "m_real_2",+ ])+ })++ it("strips failed:true rows from persisted DM message pages", async () => {+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.dmMessages("dm_1"), {+ pages: [+ makePage([+ { id: "m_ok", content: "keep", createdAt: "2026-07-01T00:00:00.000Z" },+ {+ id: "m_bad",+ content: "drop",+ createdAt: "2026-07-01T00:00:01.000Z",+ failed: true,+ },+ ]),+ ],+ pageParams: [{ mode: "newest" }],+ })++ const persister = createIdbPersister("u_1")+ await persister.persistClient({+ timestamp: Date.now(),+ buster: "v1",+ clientState: {+ mutations: [],+ queries: [+ {+ queryKey: communityKeys.dmMessages("dm_1"),+ queryHash: JSON.stringify(communityKeys.dmMessages("dm_1")),+ state: qc.getQueryState(communityKeys.dmMessages("dm_1"))!,+ },+ ],+ },+ })++ const blob = await readPersistedBlob("u_1")+ const q = blob.clientState.queries[0]+ const data = q.state.data as { pages: MessagesPage[] }+ expect(data.pages[0].messages.map((m) => m.id)).toEqual(["m_ok"])+ })++ it("drops message queries whose pages[0] is a since-mode envelope (no hasMore flag on tail)", async () => {+ const qc = new QueryClient()+ // Simulate a since-mode envelope: only `hasMoreNewer` / `newerCursor` /+ // `latestSeq` — no `hasMore`, no `hasMoreOlder`. If we persisted this,+ // the next mount would compute `hasMoreOlder ?? hasMore ?? false === false`+ // and silently claim there's no more history.+ qc.setQueryData(communityKeys.channelMessages("ch_since"), {+ pages: [+ {+ messages: [+ { id: "m_1", content: "x", createdAt: "2026-07-01T00:00:00.000Z" },+ ],+ hasMoreNewer: true,+ newerCursor: "cur_new",+ latestSeq: 42,+ },+ ],+ pageParams: [{ mode: "since", since: "cur_since" }],+ })++ const persister = createIdbPersister("u_1")+ await persister.persistClient({+ timestamp: Date.now(),+ buster: "v1",+ clientState: {+ mutations: [],+ queries: [+ {+ queryKey: communityKeys.channelMessages("ch_since"),+ queryHash: JSON.stringify(communityKeys.channelMessages("ch_since")),+ state: qc.getQueryState(communityKeys.channelMessages("ch_since"))!,+ },+ ],+ },+ })++ const blob = await readPersistedBlob("u_1")+ // The whole query was dropped by scrubDehydratedClient — nothing to+ // rehydrate, so the next mount refetches from scratch (self-healing).+ expect(blob.clientState.queries).toHaveLength(0)+ })++ it("keeps message queries whose pages[0] is anchor-mode with tail attached (hasMoreNewer=false)", async () => {+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.channelMessages("ch_anchor"), {+ pages: [+ {+ messages: [+ { id: "m_1", content: "x", createdAt: "2026-07-01T00:00:00.000Z" },+ ],+ hasMoreOlder: true,+ olderCursor: "cur_older",+ hasMoreNewer: false,+ latestSeq: 42,+ },+ ],+ pageParams: [{ mode: "anchor", anchor: "m_1" }],+ })++ const persister = createIdbPersister("u_1")+ await persister.persistClient({+ timestamp: Date.now(),+ buster: "v1",+ clientState: {+ mutations: [],+ queries: [+ {+ queryKey: communityKeys.channelMessages("ch_anchor"),+ queryHash: JSON.stringify(communityKeys.channelMessages("ch_anchor")),+ state: qc.getQueryState(communityKeys.channelMessages("ch_anchor"))!,+ },+ ],+ },+ })++ const blob = await readPersistedBlob("u_1")+ expect(blob.clientState.queries).toHaveLength(1)+ })++ it("keeps message queries whose pages[0] is legacy newest-mode (hasMore defined, no anchor flags)", async () => {+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.channelMessages("ch_legacy"), {+ pages: [+ makePage([+ { id: "m_1", content: "x", createdAt: "2026-07-01T00:00:00.000Z" },+ ]),+ ],+ pageParams: [{ mode: "newest" }],+ })++ const persister = createIdbPersister("u_1")+ await persister.persistClient({+ timestamp: Date.now(),+ buster: "v1",+ clientState: {+ mutations: [],+ queries: [+ {+ queryKey: communityKeys.channelMessages("ch_legacy"),+ queryHash: JSON.stringify(communityKeys.channelMessages("ch_legacy")),+ state: qc.getQueryState(communityKeys.channelMessages("ch_legacy"))!,+ },+ ],+ },+ })++ const blob = await readPersistedBlob("u_1")+ expect(blob.clientState.queries).toHaveLength(1)+ })+})++// ── isTrustedMessagesPageZero + shouldPersistQuery invariants ────────────++describe("isTrustedMessagesPageZero", () => {+ it("trusts legacy newest-mode envelopes (hasMore defined, no anchor flags)", () => {+ expect(+ isTrustedMessagesPageZero({ messages: [], hasMore: false, latestSeq: 0 }),+ ).toBe(true)+ expect(+ isTrustedMessagesPageZero({ messages: [], hasMore: true, latestSeq: 0 }),+ ).toBe(true)+ })++ it("trusts anchor-mode envelopes with the tail attached (hasMoreNewer=false)", () => {+ expect(+ isTrustedMessagesPageZero({+ messages: [],+ hasMoreOlder: true,+ hasMoreNewer: false,+ latestSeq: 0,+ }),+ ).toBe(true)+ })++ it("rejects since-mode envelopes (no hasMore flag on tail)", () => {+ expect(+ isTrustedMessagesPageZero({+ messages: [],+ hasMoreNewer: true,+ newerCursor: "c",+ latestSeq: 0,+ }),+ ).toBe(false)+ })++ it("rejects anchor-mode envelopes that still have newer history above (hasMoreNewer=true)", () => {+ expect(+ isTrustedMessagesPageZero({+ messages: [],+ hasMoreOlder: false,+ hasMoreNewer: true,+ latestSeq: 0,+ }),+ ).toBe(false)+ })++ it("rejects undefined pages", () => {+ expect(isTrustedMessagesPageZero(undefined)).toBe(false)+ })+})++describe("shouldPersistQuery", () => {+ it("returns true for a message query with a trusted page[0]", () => {+ expect(+ shouldPersistQuery(communityKeys.channelMessages("ch_1"), {+ pages: [{ messages: [], hasMore: false, latestSeq: 0 }],+ pageParams: [],+ }),+ ).toBe(true)+ })++ it("returns false for a message query with an untrusted page[0]", () => {+ expect(+ shouldPersistQuery(communityKeys.channelMessages("ch_1"), {+ pages: [{ messages: [], hasMoreNewer: true, newerCursor: "c", latestSeq: 0 }],+ pageParams: [],+ }),+ ).toBe(false)+ })++ it("returns false for message queries with empty pages", () => {+ expect(+ shouldPersistQuery(communityKeys.channelMessages("ch_1"), {+ pages: [],+ pageParams: [],+ }),+ ).toBe(false)+ })++ it("returns false for keys outside the allowlist regardless of data", () => {+ expect(shouldPersistQuery(communityKeys.servers(), undefined)).toBe(false)+ expect(+ shouldPersistQuery(communityKeys.channelReadStateSnapshot("ch_1"), {+ lastReadMessageId: "m_1",+ }),+ ).toBe(false)+ })+})++// ── User-scoped namespaces ────────────────────────────────────────────────++describe("createIdbPersister — user scoping", () => {+ beforeEach(async () => {+ await clearPersistedCache("u_alice")+ await clearPersistedCache("u_bob")+ })++ it("writes to a per-user IDB key so accounts don't leak", async () => {+ const alice = createIdbPersister("u_alice")+ const bob = createIdbPersister("u_bob")+ const stateForAlice: PersistedClient = {+ timestamp: 1,+ buster: "v1",+ clientState: { mutations: [], queries: [] },+ }+ const stateForBob: PersistedClient = {+ timestamp: 2,+ buster: "v1",+ clientState: { mutations: [], queries: [] },+ }+ await alice.persistClient(stateForAlice)+ await bob.persistClient(stateForBob)++ const aliceBlob = await readPersistedBlob("u_alice")+ const bobBlob = await readPersistedBlob("u_bob")+ expect(aliceBlob.timestamp).toBe(1)+ expect(bobBlob.timestamp).toBe(2)+ })++ it("clearPersistedCache only removes the target user's blob", async () => {+ const alice = createIdbPersister("u_alice")+ const bob = createIdbPersister("u_bob")+ await alice.persistClient({+ timestamp: 1,+ buster: "v1",+ clientState: { mutations: [], queries: [] },+ })+ await bob.persistClient({+ timestamp: 2,+ buster: "v1",+ clientState: { mutations: [], queries: [] },+ })++ await clearPersistedCache("u_alice")++ // Alice's blob is gone but Bob's is untouched.+ expect(await get(`alook:qc:v1:u_alice:client`)).toBeUndefined()+ const bobBlob = await readPersistedBlob("u_bob")+ expect(bobBlob.timestamp).toBe(2)+ })+})diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.tsnew file mode 100644index 000000000..72c6b84cd--- /dev/null+++ b/src/web/src/lib/query-persister.ts@@ -0,0 +1,226 @@+import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister"+import type {+ PersistedClient,+ Persister,+} from "@tanstack/react-query-persist-client"+import { del, get, set } from "idb-keyval"+import type { Msg } from "@/components/community/_types"+import type { MessagesPage } from "@/hooks/community/use-messages"++/**+ * IDB namespace root. Bumping the tail segment (`v1` → `v2`) invalidates every+ * cached payload — use it as the escape hatch when the persisted query shape+ * changes in a way the runtime can't reconcile against fresh server data.+ */+const IDB_PREFIX = "alook:qc:v1"++/**+ * Buster tag paired with `PersistedClient`. TanStack throws away restored+ * state whose buster doesn't match — a cheap secondary lever when just the+ * shape of a specific query needs to be reset without touching the IDB+ * namespace.+ */+export const PERSIST_BUSTER = "v1"++/** Persister max-age; queries older than this are discarded on restore. */+export const PERSIST_MAX_AGE_MS = 24 * 60 * 60 * 1000++/**+ * Only these query-key kinds are persisted. Everything else refetches on mount+ * — presence, live server list, member rosters, etc. are cheap and should+ * always reflect the live server.+ *+ * Note: read-state snapshots were previously persisted but were removed to+ * kill a self-inflicted staleness bug — a hydrated snapshot with a stale+ * `lastReadMessageId` would anchor the "New" divider to a row that had long+ * since scrolled off. The snapshot hooks now refetch on every mount, so+ * persisting them is a strict downside (bytes on disk + risk of drift).+ */+const PERSISTED_KINDS = new Set<string>([+ "channelMessages",+ "dmMessages",+])++// Query keys start with `["community", <kind>, ...]` — the first segment is+// the namespace, the second segment is a discriminator (`"channel"`, `"dm"`,+// `"servers"`, …), and for message queries the third+ segments carry the id+// and the literal `"messages"` / `"read-state-snapshot"` tail. See+// `src/web/src/lib/query-keys.ts`.+function keyKindFor(queryKey: readonly unknown[]): string | null {+ if (!Array.isArray(queryKey) || queryKey.length < 2) return null+ if (queryKey[0] !== "community") return null+ const second = queryKey[1]+ // Message queries: ["community", "channel", <id>, "messages"] or+ // ["community", "dm", <id>, "messages"].+ if (second === "channel" || second === "dm") {+ const tail = queryKey[queryKey.length - 1]+ if (tail === "messages") {+ return second === "channel" ? "channelMessages" : "dmMessages"+ }+ if (tail === "read-state-snapshot") {+ return second === "channel"+ ? "channelReadStateSnapshot"+ : "dmReadStateSnapshot"+ }+ }+ return null+}++export function shouldPersistQueryKey(queryKey: readonly unknown[]): boolean {+ const kind = keyKindFor(queryKey)+ return kind !== null && PERSISTED_KINDS.has(kind)+}++/**+ * Trust rule for the first page of a persisted message stream.+ *+ * Persistence is only safe when the cached window represents "we know we have+ * the newest tail." A since-mode or older-only envelope has no `hasMore` flag+ * on `pages[0]`, so the tail-of-history read (`oldestPage.hasMoreOlder ??+ * oldestPage.hasMore ?? false`) collapses to `false` on the next mount and+ * the UI silently loses history until a manual cache clear.+ *+ * Trusted shapes:+ * - Legacy newest-mode: `hasMore !== undefined && hasMoreOlder === undefined+ * && hasMoreNewer === undefined`. This is the pre-anchor cache shape.+ * - Anchor-mode with the tail attached: `hasMoreNewer === false`. Guarantees+ * the client has loaded everything up to the current latestSeq, so the+ * window on disk is a real newest-side window we can safely hand to the+ * next mount.+ */+export function isTrustedMessagesPageZero(page: MessagesPage | undefined): boolean {+ if (!page) return false+ const isLegacyNewest =+ page.hasMore !== undefined &&+ page.hasMoreOlder === undefined &&+ page.hasMoreNewer === undefined+ if (isLegacyNewest) return true+ if (page.hasMoreNewer === false) return true+ return false+}++/**+ * Query-level filter used by both `shouldDehydrateQuery` (write side) and+ * `scrubDehydratedClient` (read side of the same walk). Non-message queries+ * fall through to `shouldPersistQueryKey`; message queries additionally check+ * `pages[0]` shape so a stale/mid-history cache never survives to the next+ * mount.+ */+export function shouldPersistQuery(+ queryKey: readonly unknown[],+ data: unknown,+): boolean {+ if (!shouldPersistQueryKey(queryKey)) return false+ const kind = keyKindFor(queryKey)+ if (kind !== "channelMessages" && kind !== "dmMessages") return true+ const pages = (data as { pages?: MessagesPage[] } | undefined)?.pages+ if (!Array.isArray(pages) || pages.length === 0) return false+ return isTrustedMessagesPageZero(pages[0])+}++/**+ * Optimistic rows carry an id that starts with `temp_` until the server+ * assigns a real id. Persisting them would surface ghost rows on reload — the+ * outgoing POST may never have committed, and if it did, the WS layer will+ * re-deliver the real message with the canonical id. Also strips `failed:+ * true` rows since they only exist to prompt a retry that no longer makes+ * sense once the tab has been closed.+ */+function scrubMessage(m: Msg): boolean {+ if (typeof m.id === "string" && m.id.startsWith("temp_")) return false+ if (m.failed === true) return false+ return true+}++function scrubPage(page: MessagesPage): MessagesPage {+ const messages = page.messages.filter(scrubMessage)+ if (messages.length === page.messages.length) return page+ return { ...page, messages }+}++/**+ * Walk the dehydrated client and:+ * 1. Drop optimistic / failed message rows from each page (temp_/failed rows+ * would surface as ghosts on the next mount — see `scrubMessage`).+ * 2. Drop the whole query when its trimmed `pages[0]` no longer represents a+ * trusted newest-tail cache. TanStack's dehydrate step already ran the+ * `shouldDehydrateQuery` predicate against the *pre-scrub* data; if+ * scrubbing changed the shape (or the shape was borderline to begin with),+ * re-run the invariant here so nothing untrustworthy hits disk.+ *+ * Mutates a shallow copy — the live QueryClient cache is untouched. Called+ * from the persister's `serialize` hook, so the filter is applied every time+ * TanStack throttles a save.+ */+function scrubDehydratedClient(client: PersistedClient): PersistedClient {+ const queries: typeof client.clientState.queries = []+ for (const q of client.clientState.queries) {+ const kind = keyKindFor(q.queryKey)+ if (kind !== "channelMessages" && kind !== "dmMessages") {+ queries.push(q)+ continue+ }+ const data = q.state.data as+ | { pages: MessagesPage[]; pageParams: unknown[] }+ | undefined+ if (!data || !Array.isArray(data.pages)) continue+ const pages = data.pages.map(scrubPage)+ const nextData = { ...data, pages }+ if (!shouldPersistQuery(q.queryKey, nextData)) continue+ queries.push({ ...q, state: { ...q.state, data: nextData } })+ }+ 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. */+function blobKeyFor(userId: string | null): string {+ return `${namespaceFor(userId)}:client`+}++/**+ * Create an async-storage persister scoped to a specific user id.+ *+ * Every read/write is namespaced by `userId` so signing in as a different+ * account never surfaces the previous user's cached rows. `serialize` scrubs+ * `temp_*` and `failed: true` rows before they hit disk (see `scrubMessage`).+ */+export function createIdbPersister(userId: string | null): Persister {+ const key = blobKeyFor(userId)+ return createAsyncStoragePersister({+ storage: {+ getItem: async (_k: string) => {+ const value = await get<string>(key)+ return value ?? null+ },+ setItem: async (_k: string, value: string) => {+ await set(key, value)+ },+ removeItem: async (_k: string) => {+ await del(key)+ },+ },+ // Passed to storage under the covers, but our storage adapter ignores the+ // key argument (we own the namespace). Leaving a stable literal keeps the+ // persister's internal throttle bookkeeping predictable.+ key: "alook-query-cache",+ serialize: (client) => JSON.stringify(scrubDehydratedClient(client)),+ deserialize: (raw) => JSON.parse(raw) as PersistedClient,+ })+}++/**+ * Delete the persisted blob for a given user id. Wire into the sign-out flow+ * so a shared machine doesn't leak the previous session's cached message+ * history to the next tab.+ */+export async function clearPersistedCache(userId: string | null): Promise<void> {+ await del(blobKeyFor(userId))+}diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex eb33fb7d0..0cf9420a1 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -673,6 +673,38 @@ describe("WebSocketDurableObject", () => {).resolves.toBeUndefined()expect(mockListBotsForMachine).not.toHaveBeenCalled()})++ it("resolves cleanly when the owner-notify stub fetch rejects — the whole method is under try/catch, callers never see the throw", async () => {+ // Regression guard: the owner-notify `userStub.fetch(...)` used to+ // sit OUTSIDE the method's try/catch. A stub-fetch throw would+ // propagate through every caller's `.catch(() => {})` and skip the+ // bot fan-out entirely, contradicting the comment that claims the+ // failure would "at least be visible."+ const { durable } = createDO()+ mockStubFetch.mockClear()+ // First call is the owner notify — reject it. Subsequent calls+ // (bot fan-out per-audience-member) should still fire.+ mockStubFetch.mockRejectedValueOnce(new Error("stub unreachable"))+ mockListBotsForMachine.mockResolvedValue([+ { id: "bot-1", name: "Bot One", discriminator: "0001", description: "" },+ ])+ mockGetCoMemberUserIds.mockResolvedValue(["viewer-1"])+ mockGetFriendUserIds.mockResolvedValue([])++ await expect(+ (durable as unknown as NotifyInternals).notifyUserDO("owner-1", {+ type: "community:machine.status",+ machineId: "m1",+ status: "online",+ lastSeenAt: "2026-01-01T00:00:00.000Z",+ })+ ).resolves.toBeUndefined()++ // Owner notify was attempted (and failed) — bot fan-out still ran.+ expect(mockListBotsForMachine).toHaveBeenCalledWith({}, "m1")+ // Owner notify + at least one broadcastPresence fetch to viewer-1.+ expect(mockStubFetch.mock.calls.length).toBeGreaterThanOrEqual(2)+ })})describe("webSocketMessage — daemon auth flow", () => {diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex b5deaa83b..033323290 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -808,38 +808,50 @@ export class WebSocketDurableObject extends DurableObject<Env> {}private async notifyUserDO(userId: string, payload: unknown): Promise<void> {- const userDoId = this.env.WS_DO.idFromName("user:" + userId)- const userStub = this.env.WS_DO.get(userDoId)- await userStub.fetch(new Request("http://internal/broadcast", {- method: "POST",- body: JSON.stringify(payload),- }))-- // Single choke point for every `community:machine.status` emission (see- // plans/community-account-debt-fixes.md Fix 3) — a bot has no WS of its- // own, so its online/offline flip otherwise only ever reaches its owner- // via the fetch above. Fan the same transition out through the exact- // audience-based pipeline human presence already uses, for every bot- // bound to this machine.- //// Every one of the 5 call sites wraps this whole method in// `.catch(() => {})` (fire-and-forget — a presence hiccup must never// block the machine-status write it rides on), which means an- // unhandled throw here vanishes with zero trace. Own try/catch + log so- // a real failure (bad query, DO unreachable, etc.) is at least visible- // instead of silently degrading to "you have to refresh to see your bot- // come online."+ // unhandled throw ANYWHERE inside vanishes with zero trace. Own+ // try/catch + log around the WHOLE body — including the primary owner+ // notify — so a real failure is at least visible instead of silently+ // degrading to "you have to refresh to see the update."+ //+ // The primary owner notify (`userStub.fetch`) and the bot-presence+ // fan-out below are independent: a failed owner notify must NOT skip+ // the bot fan-out, and vice versa. Each has its own inner try so one+ // can't cascade into the other.try {- const status = this.machineStatusPayload(payload)- if (!status) return- const db = createDb(this.env.DB)- const bots = await queries.communityBot.listBotsForMachine(db, status.machineId)- if (bots.length === 0) return- await Promise.allSettled(- bots.map((bot) => this.broadcastPresence(bot.id, status.online))- )+ const userDoId = this.env.WS_DO.idFromName("user:" + userId)+ const userStub = this.env.WS_DO.get(userDoId)+ try {+ await userStub.fetch(new Request("http://internal/broadcast", {+ method: "POST",+ body: JSON.stringify(payload),+ }))+ } catch (err) {+ log.error("notifyUserDO: owner notify failed", { err: String(err), userId })+ }++ // Single choke point for every `community:machine.status` emission (see+ // plans/community-account-debt-fixes.md Fix 3) — a bot has no WS of its+ // own, so its online/offline flip otherwise only ever reaches its owner+ // via the fetch above. Fan the same transition out through the exact+ // audience-based pipeline human presence already uses, for every bot+ // bound to this machine.+ try {+ const status = this.machineStatusPayload(payload)+ if (!status) return+ const db = createDb(this.env.DB)+ const bots = await queries.communityBot.listBotsForMachine(db, status.machineId)+ if (bots.length === 0) return+ await Promise.allSettled(+ bots.map((bot) => this.broadcastPresence(bot.id, status.online))+ )+ } catch (err) {+ log.error("notifyUserDO: bot presence fan-out failed", { err: String(err), userId })+ }} catch (err) {- log.error("notifyUserDO: bot presence fan-out failed", { err: String(err), userId })+ log.error("notifyUserDO: unexpected failure", { err: String(err), userId })}}diff --git a/tests/utils/src/seed.ts b/tests/utils/src/seed.tsindex 70027f996..385d2c8d1 100644--- a/tests/utils/src/seed.ts+++ b/tests/utils/src/seed.ts@@ -38,7 +38,7 @@ export function seedTestData(): TestSeed {const now = new Date().toISOString()const slug = `test-${nanoid()}`- sqlRun(`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)`, userId, 'Test User', `${userId}@test.local`, now, now)+ sqlRun(`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)`, userId, `Test User ${userId}`, `${userId}@test.local`, now, now)sqlRun(`INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`, workspaceId, 'Test Workspace', slug, now, now)sqlRun(`INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES (?, ?, ?, ?, ?)`, memberId, workspaceId, userId, 'owner', now)sqlRun(`INSERT INTO machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at, owner_id) VALUES (?, ?, ?, ?, ?, ?, ?)`, daemonId, workspaceId, 'test-device', now, now, now, userId)@@ -92,7 +92,7 @@ export function seedSecondaryUser(workspaceId: string, role = "member"): Secondaconst memberId = `mb_${nanoid()}`const now = new Date().toISOString()- sqlRun(`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)`, userId, 'Secondary User', `${userId}@test.local`, now, now)+ sqlRun(`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES (?, ?, ?, 1, ?, ?)`, userId, `Secondary User ${userId}`, `${userId}@test.local`, now, now)sqlRun(`INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES (?, ?, ?, ?, ?)`, memberId, workspaceId, userId, role, now)return { userId, memberId }