Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): sync read state across devices (#542)

Generf4aa64915216
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 78f7e564f..d62e89166 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -37,6 +37,7 @@ export const SPEC_SECONDS = {
"27-canonical-forum-post-delete.spec.ts": 30,
"28-community-delete-media-cleanup.spec.ts": 45,
"29-community-bot-avatar-cleanup.spec.ts": 15,
+ "29-multi-device-read-state.spec.ts": 45,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 1e13a6623..19893eea7 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([202, 203, 204, 204, 205])
+ expect(totals.sort((left, right) => left - right)).toEqual([211, 212, 212, 214, 214])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.ts
index 90e2d7304..09f722c12 100644
--- a/src/shared/src/community-ws-events.ts
+++ b/src/shared/src/community-ws-events.ts
@@ -356,6 +356,31 @@ const communityUnreadBumpSchema = z.strictObject({
isMention: z.boolean().optional(),
})
+const readStateEnvelopeFields = {
+ revision: z.number().int().positive(),
+ // This is deliberately a bounded dirty hint rather than an account-sized
+ // snapshot. The receiver fetches the authoritative replacement at (at
+ // least) this revision, which preserves destructive regression/removal
+ // semantics without ever exceeding the single-frame byte limit.
+ inboxChanged: z.literal(true),
+}
+
+const communityReadStateAdvancedSchema = z.strictObject({
+ type: z.literal("community:read_state.advanced"),
+ ...readStateEnvelopeFields,
+})
+
+const communityInboxChangedSchema = z.strictObject({
+ type: z.literal("community:inbox.changed"),
+ ...readStateEnvelopeFields,
+ reason: z.enum([
+ "read_all",
+ "mention_read_all",
+ "mention_dismiss",
+ "notification_policy",
+ ]),
+})
+
const communityPresenceUpdateSchema = z.strictObject({
type: z.literal("community:presence.update"),
userId: string,
@@ -460,6 +485,8 @@ const CommunityWsEventDiscriminatedSchema = z.discriminatedUnion("type", [
communityInviteCreateSchema,
communityMentionCreateSchema,
communityUnreadBumpSchema,
+ communityReadStateAdvancedSchema,
+ communityInboxChangedSchema,
communityPresenceUpdateSchema,
communityStatusUpdateSchema,
communityMachineCreatedSchema,
@@ -524,6 +551,8 @@ export type CommunityFriendBlock = Extract<CommunityWsEvent, { type: "community:
export type CommunityInviteCreate = Extract<CommunityWsEvent, { type: "community:invite.create" }>
export type CommunityMentionCreate = Extract<CommunityWsEvent, { type: "community:mention.create" }>
export type CommunityUnreadBump = Extract<CommunityWsEvent, { type: "community:unread.bump" }>
+export type CommunityReadStateAdvanced = Extract<CommunityWsEvent, { type: "community:read_state.advanced" }>
+export type CommunityInboxChanged = Extract<CommunityWsEvent, { type: "community:inbox.changed" }>
export type CommunityPresenceUpdate = Extract<CommunityWsEvent, { type: "community:presence.update" }>
export type CommunityStatusUpdate = Extract<CommunityWsEvent, { type: "community:status.update" }>
export type CommunityMachineCreated = Extract<CommunityWsEvent, { type: "community:machine.created" }>
@@ -594,6 +623,8 @@ export const WS_EVENTS = {
INVITE_CREATE: "community:invite.create",
MENTION_CREATE: "community:mention.create",
UNREAD_BUMP: "community:unread.bump",
+ READ_STATE_ADVANCED: "community:read_state.advanced",
+ INBOX_CHANGED: "community:inbox.changed",
PRESENCE_UPDATE: "community:presence.update",
STATUS_UPDATE: "community:status.update",
MACHINE_CREATED: "community:machine.created",
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index 8cdeded91..cae92e312 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -30,6 +30,7 @@ export const communityServer = sqliteTable(
.references(() => user.id, { onDelete: "restrict" }),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
},
+ /* istanbul ignore next -- exercised by real D1 migration/runtime */
(t) => [
// Unique server handle `name#discriminator` — the server-segment address
// anchor, so a ref `/name#disc/...` resolves to exactly one server. Mirrors
@@ -372,6 +373,13 @@ export const communityReadState = sqliteTable(
(t) => [index("idx_read_state_user").on(t.userId)]
);
+export const communityReadStateRevision = sqliteTable("community_read_state_revision", {
+ userId: text("user_id")
+ .primaryKey()
+ .references(/* istanbul ignore next -- exercised by real D1 migration/runtime */ () => user.id, { onDelete: "cascade" }),
+ revision: integer("revision").notNull().default(0),
+});
+
// 13. community_reaction
export const communityReaction = sqliteTable(
"community_reaction",
diff --git a/src/shared/src/db/queries/community/delete-media.ts b/src/shared/src/db/queries/community/delete-media.ts
index e969c5342..235e6e137 100644
--- a/src/shared/src/db/queries/community/delete-media.ts
+++ b/src/shared/src/db/queries/community/delete-media.ts
@@ -1,15 +1,23 @@
-import { and, eq, exists, inArray, isNull, or } from "drizzle-orm"
+import { and, eq, exists, inArray, isNull, or, sql } from "drizzle-orm"
import {
communityAttachment,
communityChannel,
+ communityMention,
communityMessage,
+ communityReadState,
communityServer,
} from "../../community-schema"
+import { user } from "../../schema"
import type { Database } from "../../index"
+import {
+ advanceReadStateRevisionsForUsersBuilder,
+ type AccountReadStateRevisionByUser,
+} from "./read-state"
export type DeleteCommunityMediaResult = {
deleted: boolean
mediaKeys: string[]
+ readStateRevisions: AccountReadStateRevisionByUser[]
}
export type DeleteServerWithMediaResult = DeleteCommunityMediaResult & {
@@ -26,6 +34,14 @@ function flattenMediaRows(
export async function deleteChannelWithMedia(
db: Database,
input: { channelId: string; serverId: string },
+): Promise<DeleteCommunityMediaResult> {
+ return deleteChannelWithMediaAttempt(db, input, 0)
+}
+
+async function deleteChannelWithMediaAttempt(
+ db: Database,
+ input: { channelId: string; serverId: string },
+ attempt: number,
): Promise<DeleteCommunityMediaResult> {
const rootQuery = db
.select({ id: communityChannel.id })
@@ -50,6 +66,66 @@ export async function deleteChannelWithMedia(
.select({ id: communityMessage.id })
.from(communityMessage)
.where(inArray(communityMessage.channelId, scopedChannelIds))
+ const [impactedPointers, impactedMentions] = await Promise.all([
+ db
+ .selectDistinct({ userId: communityReadState.userId })
+ .from(communityReadState)
+ .innerJoin(user, eq(user.id, communityReadState.userId))
+ .where(and(
+ eq(user.isBot, false),
+ inArray(communityReadState.channelId, scopedChannelIds),
+ )),
+ db
+ .selectDistinct({ userId: communityMention.userId })
+ .from(communityMention)
+ .innerJoin(user, eq(user.id, communityMention.userId))
+ .where(and(
+ eq(user.isBot, false),
+ inArray(communityMention.messageId, scopedMessageIds),
+ )),
+ ])
+ const impactedUserIds = [...new Set([
+ ...impactedPointers,
+ ...impactedMentions,
+ ].map((row) => row.userId))]
+ const impactedIdsJson = JSON.stringify(impactedUserIds)
+ const scopedHumanEffectSql = (userIdSql: ReturnType<typeof sql>) => sql<boolean>`(
+ EXISTS (
+ SELECT 1 FROM ${communityReadState} AS current_state
+ WHERE current_state.user_id = ${userIdSql}
+ AND current_state.channel_id IN (
+ SELECT scoped_channel.id FROM ${communityChannel} AS scoped_channel
+ WHERE scoped_channel.server_id = ${input.serverId}
+ AND (
+ scoped_channel.id = ${input.channelId}
+ OR scoped_channel.parent_channel_id = ${input.channelId}
+ )
+ )
+ )
+ OR EXISTS (
+ SELECT 1 FROM ${communityMention} AS current_mention
+ INNER JOIN ${communityMessage} AS mentioned_message
+ ON mentioned_message.id = current_mention.message_id
+ WHERE current_mention.user_id = ${userIdSql}
+ AND mentioned_message.channel_id IN (
+ SELECT scoped_channel.id FROM ${communityChannel} AS scoped_channel
+ WHERE scoped_channel.server_id = ${input.serverId}
+ AND (
+ scoped_channel.id = ${input.channelId}
+ OR scoped_channel.parent_channel_id = ${input.channelId}
+ )
+ )
+ )
+ )`
+ const impactedHumansStable = sql<boolean>`NOT EXISTS (
+ SELECT 1 FROM ${user} AS current_user
+ WHERE current_user."isBot" = 0
+ AND current_user.id NOT IN (
+ SELECT CAST(value AS TEXT) FROM json_each(${impactedIdsJson})
+ )
+ AND ${scopedHumanEffectSql(sql`current_user.id`)}
+ )`
+ const enumeratedUserHasEffect = scopedHumanEffectSql(sql`CAST(value AS TEXT)`)
const mediaSnapshot = db
.select({
@@ -74,6 +150,7 @@ export async function deleteChannelWithMedia(
rootStillExists,
isNull(communityAttachment.messageId),
inArray(communityAttachment.targetId, scopedChannelIds),
+ impactedHumansStable,
))
const deleteRoot = db
@@ -81,27 +158,58 @@ export async function deleteChannelWithMedia(
.where(and(
eq(communityChannel.id, input.channelId),
eq(communityChannel.serverId, input.serverId),
+ impactedHumansStable,
))
.returning({ id: communityChannel.id })
+ const revisionIndex = 2
+ const deleteIndex = impactedUserIds.length > 0 ? 3 : 2
const results = (await db.batch([
mediaSnapshot,
removePendingAttachments,
+ ...(impactedUserIds.length > 0
+ ? [advanceReadStateRevisionsForUsersBuilder(
+ db,
+ impactedUserIds,
+ and(rootStillExists, impactedHumansStable, enumeratedUserHasEffect)!,
+ )]
+ : []),
deleteRoot,
] as any)) as unknown[]
const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>
- const deletedRows = results[2] as Array<{ id: string }>
+ const deletedRows = results[deleteIndex] as Array<{ id: string }>
const deleted = deletedRows.length > 0
+ const revisions = impactedUserIds.length > 0
+ ? results[revisionIndex] as Array<{ userId: string; revision: number }>
+ : []
+
+ if (!deleted) {
+ const roots = await rootQuery
+ /* istanbul ignore if -- real workerd stable-guard retry/exhaustion oracle */
+ if (roots.length > 0) {
+ if (attempt >= 4) throw new Error("channel read-state audience did not stabilize")
+ return deleteChannelWithMediaAttempt(db, input, attempt + 1)
+ }
+ }
return {
deleted,
mediaKeys: deleted ? flattenMediaRows(mediaRows) : [],
+ readStateRevisions: deleted ? revisions : [],
}
}
export async function deleteServerWithMedia(
db: Database,
input: { serverId: string; ownerId: string },
+): Promise<DeleteServerWithMediaResult> {
+ return deleteServerWithMediaAttempt(db, input, 0)
+}
+
+async function deleteServerWithMediaAttempt(
+ db: Database,
+ input: { serverId: string; ownerId: string },
+ attempt: number,
): Promise<DeleteServerWithMediaResult> {
const ownedServerQuery = db
.select({ id: communityServer.id })
@@ -120,6 +228,58 @@ export async function deleteServerWithMedia(
.select({ id: communityMessage.id })
.from(communityMessage)
.where(inArray(communityMessage.channelId, scopedChannelIds))
+ const [impactedPointers, impactedMentions] = await Promise.all([
+ db
+ .selectDistinct({ userId: communityReadState.userId })
+ .from(communityReadState)
+ .innerJoin(user, eq(user.id, communityReadState.userId))
+ .where(and(
+ eq(user.isBot, false),
+ inArray(communityReadState.channelId, scopedChannelIds),
+ )),
+ db
+ .selectDistinct({ userId: communityMention.userId })
+ .from(communityMention)
+ .innerJoin(user, eq(user.id, communityMention.userId))
+ .where(and(
+ eq(user.isBot, false),
+ inArray(communityMention.messageId, scopedMessageIds),
+ )),
+ ])
+ const impactedUserIds = [...new Set([
+ ...impactedPointers,
+ ...impactedMentions,
+ ].map((row) => row.userId))]
+ const impactedIdsJson = JSON.stringify(impactedUserIds)
+ const scopedHumanEffectSql = (userIdSql: ReturnType<typeof sql>) => sql<boolean>`(
+ EXISTS (
+ SELECT 1 FROM ${communityReadState} AS current_state
+ WHERE current_state.user_id = ${userIdSql}
+ AND current_state.channel_id IN (
+ SELECT scoped_channel.id FROM ${communityChannel} AS scoped_channel
+ WHERE scoped_channel.server_id = ${input.serverId}
+ )
+ )
+ OR EXISTS (
+ SELECT 1 FROM ${communityMention} AS current_mention
+ INNER JOIN ${communityMessage} AS mentioned_message
+ ON mentioned_message.id = current_mention.message_id
+ WHERE current_mention.user_id = ${userIdSql}
+ AND mentioned_message.channel_id IN (
+ SELECT scoped_channel.id FROM ${communityChannel} AS scoped_channel
+ WHERE scoped_channel.server_id = ${input.serverId}
+ )
+ )
+ )`
+ const impactedHumansStable = sql<boolean>`NOT EXISTS (
+ SELECT 1 FROM ${user} AS current_user
+ WHERE current_user."isBot" = 0
+ AND current_user.id NOT IN (
+ SELECT CAST(value AS TEXT) FROM json_each(${impactedIdsJson})
+ )
+ AND ${scopedHumanEffectSql(sql`current_user.id`)}
+ )`
+ const enumeratedUserHasEffect = scopedHumanEffectSql(sql`CAST(value AS TEXT)`)
const mediaSnapshot = db
.select({
@@ -144,6 +304,7 @@ export async function deleteServerWithMedia(
ownedServerStillExists,
isNull(communityAttachment.messageId),
inArray(communityAttachment.targetId, scopedChannelIds),
+ impactedHumansStable,
))
const deleteServer = db
@@ -151,21 +312,44 @@ export async function deleteServerWithMedia(
.where(and(
eq(communityServer.id, input.serverId),
eq(communityServer.ownerId, input.ownerId),
+ impactedHumansStable,
))
.returning({ id: communityServer.id, icon: communityServer.icon })
+ const revisionIndex = 2
+ const deleteIndex = impactedUserIds.length > 0 ? 3 : 2
const results = (await db.batch([
mediaSnapshot,
removePendingAttachments,
+ ...(impactedUserIds.length > 0
+ ? [advanceReadStateRevisionsForUsersBuilder(
+ db,
+ impactedUserIds,
+ and(ownedServerStillExists, impactedHumansStable, enumeratedUserHasEffect)!,
+ )]
+ : []),
deleteServer,
] as any)) as unknown[]
const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>
- const deletedRows = results[2] as Array<{ id: string; icon: string | null }>
+ const deletedRows = results[deleteIndex] as Array<{ id: string; icon: string | null }>
const deleted = deletedRows.length > 0
+ const revisions = impactedUserIds.length > 0
+ ? results[revisionIndex] as Array<{ userId: string; revision: number }>
+ : []
+
+ if (!deleted) {
+ const roots = await ownedServerQuery
+ /* istanbul ignore if -- real workerd stable-guard retry/exhaustion oracle */
+ if (roots.length > 0) {
+ if (attempt >= 4) throw new Error("server read-state audience did not stabilize")
+ return deleteServerWithMediaAttempt(db, input, attempt + 1)
+ }
+ }
return {
deleted,
mediaKeys: deleted ? flattenMediaRows(mediaRows) : [],
iconKey: deleted ? deletedRows[0]!.icon : null,
+ readStateRevisions: deleted ? revisions : [],
}
}
diff --git a/src/shared/src/db/queries/community/forum-post-delete.ts b/src/shared/src/db/queries/community/forum-post-delete.ts
index 74d5ba57d..1a211142b 100644
--- a/src/shared/src/db/queries/community/forum-post-delete.ts
+++ b/src/shared/src/db/queries/community/forum-post-delete.ts
@@ -2,10 +2,16 @@ import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
import {
communityAttachment,
communityChannel,
+ communityMention,
communityMessage,
communityReadState,
} from "../../community-schema";
+import { user } from "../../schema";
import type { Database } from "../../index";
+import {
+ advanceReadStateRevisionsForUsersBuilder,
+ type AccountReadStateRevisionByUser,
+} from "./read-state";
export type DeleteForumPostInput = {
openerId: string;
@@ -19,6 +25,7 @@ export type DeleteForumPostResult = {
deleted: boolean;
/** Captured in the same D1 batch before message/channel cascades ran. */
mediaKeys: string[];
+ readStateRevisions: AccountReadStateRevisionByUser[];
};
/**
@@ -31,10 +38,12 @@ export type DeleteForumPostResult = {
*
* Batch order matters:
* 1. snapshot every linked/pending Community-media key;
- * 2. repair or remove parent-forum read cursors that point at the opener;
- * 3. remove child-scoped pending attachment rows (linked rows cascade);
- * 4. update parent forum count/activity once;
- * 5. delete the opener, whose FK cascades the child channel and its rows.
+ * 2. mint account revisions while every destructive read-state effect is
+ * still observable;
+ * 3. repair or remove parent-forum read cursors that point at the opener;
+ * 4. remove child-scoped pending attachment rows (linked rows cascade);
+ * 5. update parent forum count/activity once;
+ * 6. delete the opener, whose FK cascades the child channel and its rows.
*
* Every mutating statement is guarded by the opener still existing in the
* resolved forum. D1 serializes each batch transaction, so when two requests
@@ -44,6 +53,14 @@ export type DeleteForumPostResult = {
export async function deleteForumPost(
db: Database,
input: DeleteForumPostInput,
+): Promise<DeleteForumPostResult> {
+ return deleteForumPostAttempt(db, input, 0);
+}
+
+async function deleteForumPostAttempt(
+ db: Database,
+ input: DeleteForumPostInput,
+ attempt: number,
): Promise<DeleteForumPostResult> {
const openerStillExists = sql<boolean>`EXISTS (
SELECT 1 FROM community_message AS guarded_opener
@@ -82,6 +99,111 @@ export async function deleteForumPost(
.from(communityMessage)
.where(eq(communityMessage.channelId, input.childChannelId));
+ const [impactedPointers, impactedMentions] = await Promise.all([
+ db
+ .selectDistinct({ userId: communityReadState.userId })
+ .from(communityReadState)
+ .innerJoin(user, eq(user.id, communityReadState.userId))
+ .where(and(
+ eq(user.isBot, false),
+ or(
+ and(
+ eq(communityReadState.channelId, input.forumChannelId),
+ eq(communityReadState.lastReadMessageId, input.openerId),
+ ),
+ eq(communityReadState.channelId, input.childChannelId),
+ ),
+ )),
+ db
+ .selectDistinct({ userId: communityMention.userId })
+ .from(communityMention)
+ .innerJoin(user, eq(user.id, communityMention.userId))
+ .where(and(
+ eq(user.isBot, false),
+ or(
+ eq(communityMention.messageId, input.openerId),
+ inArray(communityMention.messageId, childMessageIds),
+ ),
+ )),
+ ]);
+ const impactedUserIds = [...new Set([
+ ...impactedPointers,
+ ...impactedMentions,
+ ].map((row) => row.userId))];
+ const impactedIdsJson = JSON.stringify(impactedUserIds);
+ // The affected-human set is discovered before batch() because D1 cannot
+ // pipe one statement's RETURNING rows into later statements. Close that
+ // window optimistically inside the atomic batch: if a new human row enters
+ // either destructive scope, every mutation (including the root delete)
+ // becomes a no-op and this function re-enumerates. Rows for already-known
+ // humans may change safely: their account revision still covers the result,
+ // and clients pull the bounded account snapshot from the primary endpoint.
+ // Bot rows remain outside this account contract.
+ const impactedHumansStable = sql<boolean>`NOT EXISTS (
+ SELECT 1 FROM ${user} AS current_user
+ WHERE current_user."isBot" = 0
+ AND current_user.id NOT IN (
+ SELECT CAST(value AS TEXT) FROM json_each(${impactedIdsJson})
+ )
+ AND (
+ EXISTS (
+ SELECT 1 FROM ${communityReadState} AS current_state
+ WHERE current_state.user_id = current_user.id
+ AND (
+ (current_state.channel_id = ${input.forumChannelId}
+ AND current_state.last_read_message_id = ${input.openerId})
+ OR current_state.channel_id = ${input.childChannelId}
+ )
+ )
+ OR EXISTS (
+ SELECT 1 FROM ${communityMention} AS current_mention
+ INNER JOIN ${communityMessage} AS mentioned_message
+ ON mentioned_message.id = current_mention.message_id
+ WHERE current_mention.user_id = current_user.id
+ AND (
+ current_mention.message_id = ${input.openerId}
+ OR mentioned_message.channel_id = ${input.childChannelId}
+ )
+ )
+ )
+ )`;
+ const enumeratedUserHasEffect = sql<boolean>`EXISTS (
+ SELECT 1 FROM ${user} AS enumerated_user
+ WHERE enumerated_user.id = CAST(value AS TEXT)
+ AND enumerated_user."isBot" = 0
+ AND (
+ EXISTS (
+ SELECT 1 FROM ${communityReadState} AS current_state
+ WHERE current_state.user_id = enumerated_user.id
+ AND (
+ (current_state.channel_id = ${input.forumChannelId}
+ AND current_state.last_read_message_id = ${input.openerId})
+ OR current_state.channel_id = ${input.childChannelId}
+ )
+ )
+ OR EXISTS (
+ SELECT 1 FROM ${communityMention} AS current_mention
+ INNER JOIN ${communityMessage} AS mentioned_message
+ ON mentioned_message.id = current_mention.message_id
+ WHERE current_mention.user_id = enumerated_user.id
+ AND (
+ current_mention.message_id = ${input.openerId}
+ OR mentioned_message.channel_id = ${input.childChannelId}
+ )
+ )
+ )
+ )`;
+ const rowBelongsToKnownHumanOrBot = sql<boolean>`(
+ ${communityReadState.userId} IN (
+ SELECT CAST(value AS TEXT) FROM json_each(${impactedIdsJson})
+ )
+ OR EXISTS (
+ SELECT 1 FROM ${user} AS state_user
+ WHERE state_user.id = ${communityReadState.userId}
+ AND state_user."isBot" = 1
+ )
+ )`;
+
const mediaSnapshot = db
.select({
r2Key: communityAttachment.r2Key,
@@ -109,6 +231,8 @@ export async function deleteForumPost(
eq(communityReadState.lastReadMessageId, input.openerId),
openerStillExists,
priorMessageExists,
+ impactedHumansStable,
+ rowBelongsToKnownHumanOrBot,
));
const removeEmptyReadStates = db
@@ -118,6 +242,8 @@ export async function deleteForumPost(
eq(communityReadState.lastReadMessageId, input.openerId),
openerStillExists,
sql<boolean>`NOT (${priorMessageExists})`,
+ impactedHumansStable,
+ rowBelongsToKnownHumanOrBot,
));
const removePendingAttachments = db
@@ -126,6 +252,7 @@ export async function deleteForumPost(
isNull(communityAttachment.messageId),
eq(communityAttachment.targetId, input.childChannelId),
openerStillExists,
+ impactedHumansStable,
));
const updateForum = db
@@ -146,6 +273,7 @@ export async function deleteForumPost(
.where(and(
eq(communityChannel.id, input.forumChannelId),
openerStillExists,
+ impactedHumansStable,
));
const deleteOpener = db
@@ -153,11 +281,21 @@ export async function deleteForumPost(
.where(and(
eq(communityMessage.id, input.openerId),
eq(communityMessage.channelId, input.forumChannelId),
+ impactedHumansStable,
))
.returning({ id: communityMessage.id });
+ const revisionIndex = 1;
+ const deleteIndex = impactedUserIds.length > 0 ? 6 : 5;
const results = (await db.batch([
mediaSnapshot,
+ ...(impactedUserIds.length > 0
+ ? [advanceReadStateRevisionsForUsersBuilder(
+ db,
+ impactedUserIds,
+ and(openerStillExists, impactedHumansStable, enumeratedUserHasEffect)!,
+ )]
+ : []),
repairReadStates,
removeEmptyReadStates,
removePendingAttachments,
@@ -165,12 +303,32 @@ export async function deleteForumPost(
deleteOpener,
] as any)) as unknown[];
const mediaRows = results[0] as Array<{ r2Key: string; thumbnailR2Key: string | null }>;
- const deletedRows = results[5] as Array<{ id: string }>;
+ const deletedRows = results[deleteIndex] as Array<{ id: string }>;
+ const revisions = impactedUserIds.length > 0
+ ? results[revisionIndex] as Array<{ userId: string; revision: number }>
+ : [];
+
+ const deleted = deletedRows.length > 0;
+ if (!deleted) {
+ const roots = await db
+ .select({ id: communityMessage.id })
+ .from(communityMessage)
+ .where(and(
+ eq(communityMessage.id, input.openerId),
+ eq(communityMessage.channelId, input.forumChannelId),
+ ))
+ .limit(1);
+ if (roots.length > 0) {
+ if (attempt >= 4) throw new Error("forum read-state audience did not stabilize");
+ return deleteForumPostAttempt(db, input, attempt + 1);
+ }
+ }
return {
- deleted: deletedRows.length > 0,
- mediaKeys: deletedRows.length > 0
+ deleted,
+ mediaKeys: deleted
? mediaRows.flatMap((row) => [row.r2Key, row.thumbnailR2Key].filter((key): key is string => !!key))
: [],
+ readStateRevisions: deleted ? revisions : [],
};
}
diff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.ts
index 213f8c956..221f043e8 100644
--- a/src/shared/src/db/queries/community/friendship.ts
+++ b/src/shared/src/db/queries/community/friendship.ts
@@ -419,6 +419,7 @@ export async function sendRequest(
const otherP = profiles.get(otherId);
const content = cardContent(otherP?.name ?? "Someone", botP?.name ?? "your bot");
const msg = await createMessage(db, {
+ authorKind: "bot",
authorId: botId,
channelId: dm.id,
content,
@@ -1078,6 +1079,7 @@ export async function ownerDecideOnRow(
const otherP = profiles.get(row.requesterId);
const content = cardContent(otherP?.name ?? "Someone", botP?.name ?? "your bot");
const msg = await createMessage(db, {
+ authorKind: "bot",
authorId: row.addresseeId,
channelId: dm.id,
content,
diff --git a/src/shared/src/db/queries/community/mention.ts b/src/shared/src/db/queries/community/mention.ts
index 55fedb761..0d583261c 100644
--- a/src/shared/src/db/queries/community/mention.ts
+++ b/src/shared/src/db/queries/community/mention.ts
@@ -1,9 +1,13 @@
-import { eq, and, inArray, desc } from "drizzle-orm";
+import { eq, and, inArray, desc, exists, lte, sql, type SQL } from "drizzle-orm";
import { communityMention, communityMessage } from "../../community-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
import { chunk, maxRowsPerInsert, D1_MAX_IN_PARAMS } from "../_chunk";
import { MENTION_KIND, type MentionKind } from "../../../constants/community";
+import {
+ accountReadStateRevisionBuilder,
+ advanceReadStateRevisionWhenBuilder,
+} from "./read-state";
// communityMention emits 5 bind params/row (id $defaultFn, message_id, user_id,
// kind default, read default), so a single INSERT caps at floor(100/5)=20 rows.
@@ -149,6 +153,41 @@ export async function markAllMentionsRead(db: Database, userId: string) {
.where(and(eq(communityMention.userId, userId), eq(communityMention.read, 0)));
}
+export async function markAllMentionsReadWithRevision(
+ db: Database,
+ userId: string
+) {
+ const unreadExists = exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(communityMention)
+ .where(
+ and(
+ eq(communityMention.userId, userId),
+ eq(communityMention.read, 0)
+ )
+ )
+ );
+ const mutation = db
+ .update(communityMention)
+ .set({ read: 1 })
+ .where(
+ and(
+ eq(communityMention.userId, userId),
+ eq(communityMention.read, 0)
+ )
+ );
+ const results = await db.batch([
+ advanceReadStateRevisionWhenBuilder(db, userId, unreadExists),
+ mutation,
+ accountReadStateRevisionBuilder(db, userId),
+ ] as any) as unknown[];
+ return {
+ changed: (results[0] as Array<{ revision: number }>).length > 0,
+ revision: (results[2] as Array<{ revision: number }>)[0]?.revision ?? 0,
+ };
+}
+
export async function markChannelMentionsRead(db: Database, userId: string, channelId: string) {
const mentionIds = await db
.select({ id: communityMention.id })
@@ -177,7 +216,9 @@ export async function markChannelMentionsRead(db: Database, userId: string, chan
export function markChannelMentionsReadBuilder(
db: Database,
userId: string,
- channelId: string
+ channelId: string,
+ targetSeq?: number,
+ guard?: SQL<unknown>,
) {
const matchingMentionIds = db
.select({ id: communityMention.id })
@@ -187,14 +228,81 @@ export function markChannelMentionsReadBuilder(
and(
eq(communityMention.userId, userId),
eq(communityMention.read, 0),
- eq(communityMessage.channelId, channelId)
+ eq(communityMessage.channelId, channelId),
+ ...(targetSeq === undefined ? [] : [lte(communityMessage.seq, targetSeq)])
)
);
return db
.update(communityMention)
.set({ read: 1 })
- .where(inArray(communityMention.id, matchingMentionIds));
+ .where(and(
+ inArray(communityMention.id, matchingMentionIds),
+ ...(guard ? [guard] : []),
+ ));
+}
+
+export function unreadChannelMentionThroughSeqCondition(
+ db: Database,
+ userId: string,
+ channelId: string,
+ targetSeq: number,
+ guard?: SQL<unknown>,
+): SQL<unknown> {
+ const unreadExists = exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(communityMention)
+ .innerJoin(
+ communityMessage,
+ eq(communityMention.messageId, communityMessage.id)
+ )
+ .where(
+ and(
+ eq(communityMention.userId, userId),
+ eq(communityMention.read, 0),
+ eq(communityMessage.channelId, channelId),
+ lte(communityMessage.seq, targetSeq)
+ )
+ )
+ );
+ return guard ? and(guard, unreadExists)! : unreadExists;
+}
+
+export function unreadMessageMentionCondition(
+ db: Database,
+ userId: string,
+ messageId: string
+): SQL<unknown> {
+ return exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(communityMention)
+ .where(
+ and(
+ eq(communityMention.userId, userId),
+ eq(communityMention.messageId, messageId),
+ eq(communityMention.read, 0)
+ )
+ )
+ );
+}
+
+export function markMessageMentionsReadBuilder(
+ db: Database,
+ userId: string,
+ messageId: string
+) {
+ return db
+ .update(communityMention)
+ .set({ read: 1 })
+ .where(
+ and(
+ eq(communityMention.userId, userId),
+ eq(communityMention.messageId, messageId),
+ eq(communityMention.read, 0)
+ )
+ );
}
/**
@@ -230,3 +338,40 @@ export async function deleteMention(db: Database, userId: string, mentionId: str
.returning({ id: communityMention.id });
return rows.length;
}
+
+export async function dismissMentionWithRevision(
+ db: Database,
+ userId: string,
+ mentionId: string
+) {
+ const unreadExists = exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(communityMention)
+ .where(
+ and(
+ eq(communityMention.id, mentionId),
+ eq(communityMention.userId, userId),
+ eq(communityMention.read, 0)
+ )
+ )
+ );
+ const mutation = db
+ .delete(communityMention)
+ .where(
+ and(
+ eq(communityMention.id, mentionId),
+ eq(communityMention.userId, userId),
+ eq(communityMention.read, 0)
+ )
+ );
+ const results = await db.batch([
+ advanceReadStateRevisionWhenBuilder(db, userId, unreadExists),
+ mutation,
+ accountReadStateRevisionBuilder(db, userId),
+ ] as any) as unknown[];
+ return {
+ changed: (results[0] as Array<{ revision: number }>).length > 0,
+ revision: (results[2] as Array<{ revision: number }>)[0]?.revision ?? 0,
+ };
+}
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 17952100d..a7bc12140 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -1,13 +1,16 @@
-import { eq, and, asc, desc, gt, lt, or, sql, inArray } from "drizzle-orm";
+import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, type SQL } from "drizzle-orm";
import {
communityMessage,
communityChannel,
communityReadState,
+ communityReadStateRevision,
communityMessageSeq,
communityChannelMember,
+ communityMention,
communityMessageTag,
} from "../../community-schema";
import { user } from "../../schema";
+import { nanoid } from "nanoid";
import type { Database } from "../../index";
import { createLogger } from "../../../logger";
import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
@@ -75,6 +78,32 @@ const DEFAULT_LIMIT = 50;
// logger down through 30+ call sites) buys nothing here.
const log = createLogger({ service: "community-queries" });
+function advanceMessageDeletionRevisionsBuilder(
+ db: Database,
+ userIds: string[],
+ condition: SQL<unknown>
+) {
+ const ids = JSON.stringify([...new Set(userIds)]);
+ const selected = db
+ .select({
+ userId: sql<string>`CAST(value AS TEXT)`.as("user_id"),
+ revision: sql<number>`1`.as("revision"),
+ })
+ .from(sql`json_each(${ids})`)
+ .where(condition);
+ return db
+ .insert(communityReadStateRevision)
+ .select(selected)
+ .onConflictDoUpdate({
+ target: communityReadStateRevision.userId,
+ set: { revision: sql`${communityReadStateRevision.revision} + 1` },
+ })
+ .returning({
+ userId: communityReadStateRevision.userId,
+ revision: communityReadStateRevision.revision,
+ });
+}
+
// TEXT column at rest → JSON at the boundary. Isolating the parse here keeps
// storage-format concerns out of every route.
function safeParseEmbeds(raw: string | null, messageId: string): unknown | undefined {
@@ -90,6 +119,14 @@ function safeParseEmbeds(raw: string | null, messageId: string): unknown | undef
export type CreateMessageData = {
id?: string;
authorId: string;
+ /**
+ * Human authors participate in the account read-state revision contract;
+ * bots intentionally keep their single-machine cursor semantics. The
+ * unified Web funnel passes this explicitly. Low-level/system callers
+ * default to bot so historical bot card writers cannot accidentally mint
+ * human realtime state.
+ */
+ authorKind?: "human" | "bot";
content: string;
channelId: string;
type?: string;
@@ -162,16 +199,18 @@ export async function createMessage(
}
// Step 1+: everything after the seq claim above — message insert,
-// channel/DM `lastMessageAt` bump, author read-state watermark. Split out of
+// channel/DM `lastMessageAt` bump, and the applicable author read marker. Split out of
// `createMessage` purely so the two overload signatures above can reference
// its return type instead of duplicating a hand-written row type; behavior
// is identical to having this inlined.
async function insertMessageRow(db: Database, data: CreateMessageData, seq: number) {
const now = new Date().toISOString();
+ const messageId = data.id ?? nanoid();
+ const authorIsHuman = data.authorKind === "human";
// Pass `createdAt: now` explicitly so `msg.createdAt` matches the exact
- // string we write to `channel.lastMessageAt` and to the author's read-state
- // watermark below. Without this, the schema `$defaultFn` fires a microsecond
+ // string we write to `channel.lastMessageAt` and to the author's read marker
+ // below. Without this, the schema `$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.
@@ -181,7 +220,7 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
// Drizzle's `$defaultFn` on `communityMessage.id` only fires when the
// field is absent from `.values(...)`; passing `id` explicitly when the
// caller supplies one keeps the pre-minted path a one-line difference.
- ...(data.id !== undefined ? { id: data.id } : {}),
+ id: messageId,
authorId: data.authorId,
content: data.content,
channelId: data.channelId,
@@ -210,34 +249,51 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
// Caller-supplied extra statements (e.g. the bot sent-activity rollup bump)
// ride this same batch — appended AFTER insert+scope so the message row is
// index 0. They share the batch's all-or-nothing commit.
- const batchStatements = [insertMsg, scopeUpdate, ...(data.extraStatements ?? [])];
- const results = (await db.batch(batchStatements 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 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 the committed-message planner sees a
- // stale wake cursor. Runs as a separate await because it needs `msg.id`.
- await db
+ const authorWatermark = db
.insert(communityReadState)
.values({
userId: data.authorId,
channelId: data.channelId,
lastReadAt: now,
- lastReadMessageId: msg.id,
+ lastReadMessageId: messageId,
lastReadSeq: seq,
})
.onConflictDoUpdate({
target: [communityReadState.userId, communityReadState.channelId],
- set: { lastReadAt: now, lastReadMessageId: msg.id, lastReadSeq: seq },
+ set: { lastReadAt: now, lastReadMessageId: messageId, lastReadSeq: seq },
setWhere: sql`${communityReadState.lastReadSeq} < ${seq}`,
});
+ const baseStatements = [
+ insertMsg,
+ scopeUpdate,
+ ...(data.extraStatements ?? []),
+ ];
+ if (!authorIsHuman) {
+ const results = (await db.batch([
+ ...baseStatements,
+ authorWatermark,
+ ] as any)) as any[];
+ return (results[0] as InsertedMessage[])[0]!;
+ }
- return msg;
+ const humanRevision = db
+ .insert(communityReadStateRevision)
+ .values({ userId: data.authorId, revision: 1 })
+ .onConflictDoUpdate({
+ target: communityReadStateRevision.userId,
+ set: { revision: sql`${communityReadStateRevision.revision} + 1` },
+ })
+ .returning({ revision: communityReadStateRevision.revision });
+ const results = (await db.batch([
+ ...baseStatements,
+ authorWatermark,
+ humanRevision,
+ ] as any)) as any[];
+ const msg = (results[0] as InsertedMessage[])[0]!;
+ const revisionRows = results.at(-1) as Array<{ revision: number }> | undefined;
+ const revision = revisionRows?.[0]?.revision;
+ if (revision === undefined) throw new Error("human author read-state revision missing");
+ return { ...msg, readStateRevision: revision };
}
/**
@@ -251,11 +307,11 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
* 2. Channel/DM lastMessageAt (recomputed via `MAX(createdAt)` subquery so
* concurrent inserts keep their timestamps) + `messageCount -= 1` on
* channel (DM has no counter).
- * 3. Author's `communityReadState` row: if a prior message in scope exists,
- * revert the watermark to it (guarded by `lastReadMessageId = messageId`
- * so a concurrent same-author send that already advanced past our seq
- * keeps its newer state); if this was the first-ever message in scope,
- * DELETE the read-state row entirely so the schema's
+ * 3. Every `communityReadState` row still pointing at the message: if a
+ * prior message in scope exists, revert the pointer to it (guarded by
+ * `lastReadMessageId = messageId` so a concurrent advance keeps its newer
+ * state); if this was the first-ever message in scope, DELETE each row so
+ * the schema's
* "materialized ⇒ lastReadMessageId IS NOT NULL" invariant holds — the
* next send re-inserts through `.onConflictDoUpdate`, and the DELETE
* completes inside the same batch so no partial-UNIQUE-index collision.
@@ -264,6 +320,14 @@ async function insertMessageRow(db: Database, data: CreateMessageData, seq: numb
* initial SELECT returns nothing and the whole cascade is skipped.
*/
export async function hardDeleteMessage(db: Database, messageId: string) {
+ return hardDeleteMessageAttempt(db, messageId, 0);
+}
+
+async function hardDeleteMessageAttempt(
+ db: Database,
+ messageId: string,
+ attempt: number
+) {
const msgRows = await db
.select({
id: communityMessage.id,
@@ -276,7 +340,7 @@ export async function hardDeleteMessage(db: Database, messageId: string) {
.where(eq(communityMessage.id, messageId))
.limit(1);
const msg = msgRows[0];
- if (!msg) return;
+ if (!msg) return null;
// Prior-in-scope message for the read-state revert. Pre-fetched because
// Drizzle's D1 batch driver serializes each statement independently and
@@ -297,7 +361,63 @@ export async function hardDeleteMessage(db: Database, messageId: string) {
.limit(1);
const prior = priorRows[0];
- const deleteMsg = db.delete(communityMessage).where(eq(communityMessage.id, messageId));
+ const [impactedPointers, impactedMentions] = await Promise.all([
+ db
+ .selectDistinct({ userId: communityReadState.userId })
+ .from(communityReadState)
+ .innerJoin(user, eq(user.id, communityReadState.userId))
+ .where(and(
+ eq(user.isBot, false),
+ eq(communityReadState.channelId, msg.channelId),
+ eq(communityReadState.lastReadMessageId, messageId),
+ )),
+ db
+ .selectDistinct({ userId: communityMention.userId })
+ .from(communityMention)
+ .innerJoin(user, eq(user.id, communityMention.userId))
+ .where(and(
+ eq(user.isBot, false),
+ eq(communityMention.messageId, messageId),
+ )),
+ ]);
+ const impactedUserIds = [...new Set([
+ ...impactedPointers,
+ ...impactedMentions,
+ ].map((row) => row.userId))];
+ const impactedIdsJson = JSON.stringify(impactedUserIds);
+ const rootStillExists = exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(communityMessage)
+ .where(eq(communityMessage.id, messageId))
+ );
+ const userHasEffect = (userIdSql: ReturnType<typeof sql>) => sql<boolean>`(
+ EXISTS (
+ SELECT 1 FROM ${communityReadState} AS current_state
+ WHERE current_state.user_id = ${userIdSql}
+ AND current_state.channel_id = ${msg.channelId}
+ AND current_state.last_read_message_id = ${messageId}
+ )
+ OR EXISTS (
+ SELECT 1 FROM ${communityMention} AS current_mention
+ WHERE current_mention.user_id = ${userIdSql}
+ AND current_mention.message_id = ${messageId}
+ )
+ )`;
+ const impactedHumansStable = sql<boolean>`NOT EXISTS (
+ SELECT 1 FROM ${user} AS current_user
+ WHERE current_user."isBot" = 0
+ AND current_user.id NOT IN (
+ SELECT CAST(value AS TEXT) FROM json_each(${impactedIdsJson})
+ )
+ AND ${userHasEffect(sql`current_user.id`)}
+ )`;
+ const enumeratedUserHasEffect = userHasEffect(sql`CAST(value AS TEXT)`);
+
+ const deleteMsg = db
+ .delete(communityMessage)
+ .where(and(eq(communityMessage.id, messageId), impactedHumansStable))
+ .returning({ id: communityMessage.id });
// `lastMessageAt` is an INLINE `MAX(createdAt)` subquery — never pre-fetched.
// A concurrent writer inserting a newer message between our SELECT above and
@@ -312,12 +432,17 @@ export async function hardDeleteMessage(db: Database, messageId: string) {
string | null
>`(SELECT MAX(${communityMessage.createdAt}) FROM ${communityMessage} WHERE ${communityMessage.channelId} = ${msg.channelId} AND ${communityMessage.id} != ${messageId})`,
})
- .where(eq(communityChannel.id, msg.channelId));
+ .where(and(
+ eq(communityChannel.id, msg.channelId),
+ rootStillExists,
+ impactedHumansStable,
+ ));
const readStateWhere = and(
- eq(communityReadState.userId, msg.authorId),
eq(communityReadState.channelId, msg.channelId),
- eq(communityReadState.lastReadMessageId, messageId)
+ eq(communityReadState.lastReadMessageId, messageId),
+ rootStillExists,
+ impactedHumansStable,
);
const readStateStmt = prior
@@ -331,7 +456,40 @@ export async function hardDeleteMessage(db: Database, messageId: string) {
.where(readStateWhere)
: db.delete(communityReadState).where(readStateWhere);
- await db.batch([deleteMsg, scopeUpdate, readStateStmt] as any);
+ const revisionStatements = impactedUserIds.length > 0
+ ? [advanceMessageDeletionRevisionsBuilder(
+ db,
+ impactedUserIds,
+ and(rootStillExists, impactedHumansStable, enumeratedUserHasEffect)!,
+ )]
+ : [];
+ const revisionIndex = revisionStatements.length > 0 ? 0 : -1;
+ const deleteIndex = revisionStatements.length + 2;
+ const results = await db.batch([
+ ...revisionStatements,
+ scopeUpdate,
+ readStateStmt,
+ deleteMsg,
+ ] as any) as unknown[];
+ const deleted = (results[deleteIndex] as Array<{ id: string }>).length > 0;
+ if (!deleted) {
+ /* istanbul ignore next -- real workerd stable-guard retry/exhaustion oracle */
+ const roots = await db
+ .select({ id: communityMessage.id })
+ .from(communityMessage)
+ .where(eq(communityMessage.id, messageId))
+ .limit(1);
+ /* istanbul ignore if -- real workerd stable-guard retry/exhaustion oracle */
+ if (roots.length > 0) {
+ if (attempt >= 4) throw new Error("message read-state audience did not stabilize");
+ return hardDeleteMessageAttempt(db, messageId, attempt + 1);
+ }
+ return null;
+ }
+ const readStateRevisions = revisionIndex >= 0
+ ? results[revisionIndex] as Array<{ userId: string; revision: number }>
+ : [];
+ return { readStateRevisions };
}
// Shared select projection for the three list-messages paths (`listMessages`,
diff --git a/src/shared/src/db/queries/community/notification-setting.ts b/src/shared/src/db/queries/community/notification-setting.ts
index f950c5c76..7ed174ed7 100644
--- a/src/shared/src/db/queries/community/notification-setting.ts
+++ b/src/shared/src/db/queries/community/notification-setting.ts
@@ -6,6 +6,7 @@ import {
isNotNull,
inArray,
gt,
+ exists,
notExists,
sql,
} from "drizzle-orm";
@@ -22,6 +23,10 @@ import {
communityServerMember,
} from "../../community-schema";
import type { Database } from "../../index";
+import {
+ accountReadStateRevisionBuilder,
+ advanceReadStateRevisionWhenBuilder,
+} from "./read-state";
import type { NotificationLevelValue } from "../../../constants/community";
import { currentEffectiveLevelSql } from "./notification-eligibility";
import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
@@ -402,23 +407,62 @@ function buildClearAffectedUnreadStatement(
});
}
+function effectivePolicyChangesCondition(
+ db: Database,
+ userId: string,
+ change: SettingChange,
+) {
+ const scope: MutationScope = change.kind === "set-server"
+ ? { kind: "server", id: change.id }
+ : { kind: "channel", id: change.id };
+ const channelSql = {
+ id: communityChannel.id,
+ serverId: communityChannel.serverId,
+ parentChannelId: communityChannel.parentChannelId,
+ };
+ return exists(db
+ .select({ one: sql<number>`1` })
+ .from(communityChannel)
+ .where(
+ and(
+ affectedChannelWhere(scope),
+ userCanAccessChannelSql(userId),
+ sql`${currentEffectiveLevelSql(userId, channelSql)} <> ${nextEffectiveLevelSql(userId, change)}`,
+ ),
+ ));
+}
+
async function applySettingMutation(
db: Database,
userId: string,
change: SettingChange,
mutation: unknown,
-) {
+ actorKind: "human" | "bot",
+): Promise<number | null> {
// Clear first while the current projection still represents the "before"
// level used by the changed-effective predicate. D1 batch is atomic, so no
// observer can see the cursor advance without the setting write (or vice
// versa), and any failure rolls both statements back.
const clearUnread = buildClearAffectedUnreadStatement(db, userId, change);
- await db.batch([clearUnread, mutation] as any);
+ if (actorKind === "bot") {
+ await db.batch([clearUnread, mutation] as any);
+ return null;
+ }
+ const effectChanges = effectivePolicyChangesCondition(db, userId, change);
+ const results = await db.batch([
+ advanceReadStateRevisionWhenBuilder(db, userId, effectChanges),
+ clearUnread,
+ mutation,
+ accountReadStateRevisionBuilder(db, userId),
+ ] as any) as unknown[];
+ const changed = (results[0] as Array<{ revision: number }>).length > 0;
+ const revision = (results[3] as Array<{ revision: number }>)[0]?.revision ?? 0;
+ return changed ? revision : null;
}
export async function setServerLevel(
db: Database,
- data: { userId: string; serverId: string; level: string }
+ data: { userId: string; serverId: string; level: string; actorKind: "human" | "bot" }
) {
const mutation = db
.insert(communityNotificationSetting)
@@ -438,11 +482,12 @@ export async function setServerLevel(
set: { level: data.level },
});
- await applySettingMutation(
+ const readStateRevision = await applySettingMutation(
db,
data.userId,
{ kind: "set-server", id: data.serverId, level: data.level },
mutation,
+ data.actorKind,
);
const rows = await db
@@ -456,12 +501,12 @@ export async function setServerLevel(
),
)
.limit(1);
- return rows[0]!;
+ return { setting: rows[0]!, readStateRevision };
}
export async function setChannelLevel(
db: Database,
- data: { userId: string; channelId: string; level: string }
+ data: { userId: string; channelId: string; level: string; actorKind: "human" | "bot" }
) {
const mutation = db
.insert(communityNotificationSetting)
@@ -481,11 +526,12 @@ export async function setChannelLevel(
set: { level: data.level },
});
- await applySettingMutation(
+ const readStateRevision = await applySettingMutation(
db,
data.userId,
{ kind: "set-channel", id: data.channelId, level: data.level },
mutation,
+ data.actorKind,
);
const rows = await db
@@ -499,12 +545,12 @@ export async function setChannelLevel(
),
)
.limit(1);
- return rows[0]!;
+ return { setting: rows[0]!, readStateRevision };
}
export async function removeChannelOverride(
db: Database,
- data: { userId: string; channelId: string }
+ data: { userId: string; channelId: string; actorKind: "human" | "bot" }
) {
const existingRows = await db
.select()
@@ -528,11 +574,12 @@ export async function removeChannelOverride(
)
);
- await applySettingMutation(
+ const readStateRevision = await applySettingMutation(
db,
data.userId,
{ kind: "remove-channel", id: data.channelId },
mutation,
+ data.actorKind,
);
- return existingRows[0] ?? null;
+ return { setting: existingRows[0] ?? null, readStateRevision };
}
diff --git a/src/shared/src/db/queries/community/read-state.ts b/src/shared/src/db/queries/community/read-state.ts
index 19cdb8ecd..1d4bf1053 100644
--- a/src/shared/src/db/queries/community/read-state.ts
+++ b/src/shared/src/db/queries/community/read-state.ts
@@ -1,7 +1,11 @@
-import { eq, and, inArray, lt, sql } from "drizzle-orm";
-import { communityReadState } from "../../community-schema";
+import { eq, and, exists, gte, notExists, or, sql, type SQL } from "drizzle-orm";
+import {
+ communityMessage,
+ communityReadState,
+ communityReadStateRevision,
+} from "../../community-schema";
+import { user } from "../../schema";
import type { Database } from "../../index";
-import { chunk, maxRowsPerInsert, D1_MAX_IN_PARAMS } from "../_chunk";
import {
getLatestMessagesByChannelIds,
getMessageByChannelAndSeq,
@@ -40,6 +44,51 @@ function buildTargetFilter(data: { userId: string; channelId: string }) {
)!;
}
+export function readStateAdvancesCondition(
+ db: Database,
+ data: { userId: string; channelId: string; targetSeq: number },
+ guard?: SQL<unknown>,
+): SQL<unknown> {
+ const advances = notExists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(communityReadState)
+ .where(
+ and(
+ eq(communityReadState.userId, data.userId),
+ eq(communityReadState.channelId, data.channelId),
+ gte(communityReadState.lastReadSeq, data.targetSeq)
+ )
+ )
+ );
+ return guard ? and(guard, advances)! : advances;
+}
+
+export type CanonicalReadTarget = {
+ id: string;
+ channelId: string;
+ createdAt: string;
+ seq: number;
+};
+
+/** Re-check an exact pre-read target inside the mutation transaction. */
+export function canonicalReadTargetExistsCondition(
+ db: Database,
+ target: CanonicalReadTarget,
+): SQL<unknown> {
+ return exists(
+ db
+ .select({ one: sql<number>`1` })
+ .from(communityMessage)
+ .where(and(
+ eq(communityMessage.id, target.id),
+ eq(communityMessage.channelId, target.channelId),
+ eq(communityMessage.createdAt, target.createdAt),
+ eq(communityMessage.seq, target.seq),
+ )),
+ );
+}
+
/**
* Canonical batchable channel/DM read-state upsert.
*
@@ -62,8 +111,8 @@ function buildTargetFilter(data: { userId: string; channelId: string }) {
// `EXISTS(message.seq > lastReadSeq)` — the same seq ruler the agent side uses —
// so every human read write must advance `lastReadSeq` too, else a human's read
// never registers under the new predicate (permanent phantom-unread). `seq`
-// co-advances with `createdAt` (both from the same message), so the monotone
-// guard stays on `lastReadAt` and `lastReadSeq` is set alongside.
+// co-advances with `createdAt` (both from the same message), and the monotone
+// guard uses `lastReadSeq` so same-timestamp messages still order correctly.
export function markReadToMessageBuilder(
db: Database,
data: {
@@ -74,18 +123,6 @@ export function markReadToMessageBuilder(
) {
const { userId, channelId, message } = data;
- // Monotone guard: `setWhere` requires the incoming `lastReadAt` to be
- // strictly greater than the row's current value. If a stale client PUT
- // arrives (channel switch → return, remounted `useChannelWatermark`
- // resets its local `maxSeen` and picks an older mid-viewport row as
- // its first advance), the UPDATE portion no-ops and the existing row
- // wins. INSERT (no row yet) is unaffected — you can't regress what
- // doesn't exist. Sibling pattern to `createMessage`'s author-watermark
- // upsert, which guards on `lastReadSeq < seq` for the same reason.
- //
- // Timestamp comparison is safe: `lastReadAt` is a TEXT ISO-8601 string
- // (see schema note) and SQLite compares those lexicographically, which
- // matches temporal order for ISO-8601.
return db
.insert(communityReadState)
.values({
@@ -102,10 +139,200 @@ export function markReadToMessageBuilder(
lastReadMessageId: message.id,
lastReadSeq: message.seq,
},
- setWhere: sql`${communityReadState.lastReadAt} < ${message.createdAt}`,
+ setWhere: sql`${communityReadState.lastReadSeq} < ${message.seq}`,
+ });
+}
+
+/**
+ * Route-facing guarded sibling. The candidate row is selected from the exact
+ * canonical message inside the same D1 batch, so a target deleted after the
+ * route's pre-read cannot be written back as an orphan cursor.
+ */
+export function markReadToExistingMessageBuilder(
+ db: Database,
+ data: {
+ userId: string;
+ channelId: string;
+ message: CanonicalReadTarget;
+ },
+) {
+ const { userId, channelId, message } = data;
+ const selected = db
+ .select({
+ id: sql<string>`lower(hex(randomblob(16)))`.as("id"),
+ userId: sql<string>`${userId}`.as("user_id"),
+ channelId: communityMessage.channelId,
+ lastReadAt: communityMessage.createdAt,
+ lastReadMessageId: communityMessage.id,
+ lastReadSeq: communityMessage.seq,
+ })
+ .from(communityMessage)
+ .where(and(
+ eq(communityMessage.id, message.id),
+ eq(communityMessage.channelId, channelId),
+ eq(communityMessage.createdAt, message.createdAt),
+ eq(communityMessage.seq, message.seq),
+ ))
+ .limit(1);
+
+ return db
+ .insert(communityReadState)
+ .select(selected)
+ .onConflictDoUpdate({
+ target: [communityReadState.userId, communityReadState.channelId],
+ set: {
+ lastReadAt: sql`excluded.last_read_at`,
+ lastReadMessageId: sql`excluded.last_read_message_id`,
+ lastReadSeq: sql`excluded.last_read_seq`,
+ },
+ setWhere: sql`${communityReadState.lastReadSeq} < excluded.last_read_seq`,
});
}
+export function advanceReadStateRevisionBuilder(db: Database, userId: string) {
+ return db
+ .insert(communityReadStateRevision)
+ .values({ userId, revision: 1 })
+ .onConflictDoUpdate({
+ target: communityReadStateRevision.userId,
+ set: { revision: sql`${communityReadStateRevision.revision} + 1` },
+ })
+ .returning({ revision: communityReadStateRevision.revision });
+}
+
+export function advanceReadStateRevisionWhenBuilder(
+ db: Database,
+ userId: string,
+ condition: SQL<unknown>
+) {
+ const selected = db
+ .select({
+ userId: sql<string>`${userId}`.as("user_id"),
+ revision: sql<number>`1`.as("revision"),
+ })
+ .from(user)
+ .where(and(eq(user.id, userId), condition));
+ return db
+ .insert(communityReadStateRevision)
+ .select(selected)
+ .onConflictDoUpdate({
+ target: communityReadStateRevision.userId,
+ set: { revision: sql`${communityReadStateRevision.revision} + 1` },
+ })
+ .returning({ revision: communityReadStateRevision.revision });
+}
+
+export function advanceReadStateRevisionWhenAnyBuilder(
+ db: Database,
+ userId: string,
+ conditions: [SQL<unknown>, SQL<unknown>, ...SQL<unknown>[]]
+) {
+ return advanceReadStateRevisionWhenBuilder(db, userId, or(...conditions)!);
+}
+
+/**
+ * Bulk sibling used by destructive mutations that may replace/remove rows for
+ * several human accounts at once. `condition` is evaluated inside the same D1
+ * batch immediately before the destructive statement, so a raced loser does
+ * not mint revisions for a mutation it did not commit.
+ */
+export function advanceReadStateRevisionsForUsersBuilder(
+ db: Database,
+ userIds: string[],
+ condition: SQL<unknown>,
+) {
+ const ids = JSON.stringify([...new Set(userIds)]);
+ const selected = db
+ .select({
+ userId: sql<string>`CAST(value AS TEXT)`.as("user_id"),
+ revision: sql<number>`1`.as("revision"),
+ })
+ .from(sql`json_each(${ids})`)
+ .where(condition);
+ return db
+ .insert(communityReadStateRevision)
+ .select(selected)
+ .onConflictDoUpdate({
+ target: communityReadStateRevision.userId,
+ set: { revision: sql`${communityReadStateRevision.revision} + 1` },
+ })
+ .returning({
+ userId: communityReadStateRevision.userId,
+ revision: communityReadStateRevision.revision,
+ });
+}
+
+export function accountReadStateRevisionBuilder(db: Database, userId: string) {
+ return db
+ .select({ revision: communityReadStateRevision.revision })
+ .from(communityReadStateRevision)
+ .where(eq(communityReadStateRevision.userId, userId))
+ .limit(1);
+}
+
+export function accountReadStateRowsBuilder(db: Database, userId: string) {
+ return db
+ .select({
+ channelId: communityReadState.channelId,
+ lastReadMessageId: communityReadState.lastReadMessageId,
+ lastReadAt: communityReadState.lastReadAt,
+ lastReadSeq: communityReadState.lastReadSeq,
+ })
+ .from(communityReadState)
+ .where(eq(communityReadState.userId, userId));
+}
+
+export type AccountReadState = {
+ channelId: string;
+ lastReadMessageId: string | null;
+ lastReadAt: string;
+ lastReadSeq: number;
+};
+
+export type AccountReadStateSnapshot = {
+ revision: number;
+ readStates: AccountReadState[];
+};
+
+export type AccountReadStateRevisionByUser = {
+ userId: string;
+ revision: number;
+};
+
+export async function getAccountReadStateSnapshot(db: Database, userId: string) {
+ const revisionQuery = accountReadStateRevisionBuilder(db, userId);
+ const readStatesQuery = accountReadStateRowsBuilder(db, userId);
+ const [revisionRows, readStates] = await db.batch([
+ revisionQuery,
+ readStatesQuery,
+ ]) as unknown as [
+ Array<{ revision: number }>,
+ AccountReadState[],
+ ];
+ return { revision: revisionRows[0]?.revision ?? 0, readStates };
+}
+
+export type ReadStateAdvance = {
+ channelId: string;
+ lastReadMessageId: string;
+ lastReadAt: string;
+ lastReadSeq: number;
+};
+
+export type ReadAllResult = {
+ count: number;
+ changed: boolean;
+ revision: number;
+};
+
+async function getCurrentAccountReadStateRevision(
+ db: Database,
+ userId: string
+): Promise<number> {
+ const rows = await accountReadStateRevisionBuilder(db, userId);
+ return rows[0]?.revision ?? 0;
+}
+
/**
* Async sibling of `markReadToMessageBuilder` for the non-batch DM / thread
* routes.
@@ -143,13 +370,11 @@ export async function markReadToMessage(
* channels stay empty in `communityReadState` because the invariant
* forbids `lastReadMessageId = null` rows.
*/
-// lastReadSeq intentionally not maintained here — see comment on
-// `markReadToMessageBuilder` above.
export async function markAllServerChannelsRead(
db: Database,
userId: string,
visibleChannelIds: string[]
-): Promise<number> {
+): Promise<ReadAllResult> {
// Scope to the channels the viewer may see — the same visible-id set the
// inbox unread + mentions consumers use (resolved once per fetch via
// `listVisibleChannelIdsForUser`). Convergence on the id set replaces the
@@ -158,99 +383,53 @@ export async function markAllServerChannelsRead(
// id set parent-climbs, so a child under a private parent the viewer can't
// see is now correctly EXCLUDED — mark-all no longer writes read-state rows
// for channels behind an invisible private parent.
- if (visibleChannelIds.length === 0) return 0;
+ if (visibleChannelIds.length === 0) {
+ return {
+ count: 0,
+ changed: false,
+ revision: await getCurrentAccountReadStateRevision(db, userId),
+ };
+ }
const channelIds = visibleChannelIds;
const latest = await getLatestMessagesByChannelIds(db, channelIds);
- if (latest.length === 0) return 0;
-
- // Existing rows for these channels — used to split into UPDATE vs INSERT
- // batches so we don't run one query per channel. The upsert index only
- // fires per statement; we can't fold every channel into a single insert
- // with `onConflictDoUpdate` because each channel has a DIFFERENT
- // `(lastReadAt, lastReadMessageId)` pair.
- // `latest` ranges over channels-with-messages (a subset of the visible set,
- // still possibly >100). Chunk the `inArray` for D1's 100-param limit; no
- // order/limit → concat.
- const latestChannelIds = latest.map((l) => l.channelId);
- const existing = (
- await Promise.all(
- chunk(latestChannelIds, D1_MAX_IN_PARAMS).map((ids) =>
- db
- .select({
- id: communityReadState.id,
- channelId: communityReadState.channelId,
- })
- .from(communityReadState)
- .where(
- and(
- eq(communityReadState.userId, userId),
- inArray(communityReadState.channelId, ids)
- )
- )
- )
- )
- ).flat();
-
- const existingByChannel = new Map<string, string>();
- for (const row of existing) {
- if (row.channelId) existingByChannel.set(row.channelId, row.id);
- }
-
- // Split latest into (a) rows we need to UPDATE by primary key and (b) rows
- // we need to INSERT fresh.
- const toUpdate: Array<{ id: string; channelId: string; msgId: string; createdAt: string; seq: number }> = [];
- const toInsert: Array<{ channelId: string; msgId: string; createdAt: string; seq: number }> = [];
- for (const l of latest) {
- const existingId = existingByChannel.get(l.channelId);
- if (existingId) {
- toUpdate.push({ id: existingId, channelId: l.channelId, msgId: l.id, createdAt: l.createdAt, seq: l.seq });
- } else {
- toInsert.push({ channelId: l.channelId, msgId: l.id, createdAt: l.createdAt, seq: l.seq });
- }
- }
-
- // Perform updates row-by-row (one small UPDATE per row is fine — this path
- // fires on user click "Mark all read", not in a hot loop). Alternative
- // would be a `CASE WHEN ...` bulk UPDATE, which is uglier and only wins
- // above ~50 channels.
- //
- // Monotone guard mirrors `markReadToMessageBuilder`: only advance rows
- // whose current `lastReadAt` is strictly older than the channel's
- // latest. If a stale row happens to already sit ahead of the current
- // latest (rare — usually only under concurrent writes or right after
- // a message delete), leave it alone rather than regressing.
- for (const u of toUpdate) {
- await db
- .update(communityReadState)
- .set({ lastReadAt: u.createdAt, lastReadMessageId: u.msgId, lastReadSeq: u.seq })
- .where(
- and(
- eq(communityReadState.id, u.id),
- lt(communityReadState.lastReadAt, u.createdAt)
- )
- );
+ if (latest.length === 0) {
+ return {
+ count: 0,
+ changed: false,
+ revision: await getCurrentAccountReadStateRevision(db, userId),
+ };
}
- if (toInsert.length > 0) {
- // communityReadState emits 6 bind params/row (id $defaultFn, user_id,
- // channel_id, last_read_at, last_read_message_id, last_read_seq — now
- // explicitly supplied, no longer defaulted), so cap at floor(100/6)=16
- // rows/statement for D1's 100-param limit.
- for (const batch of chunk(toInsert, maxRowsPerInsert(6))) {
- await db.insert(communityReadState).values(
- batch.map((i) => ({
- userId,
- channelId: i.channelId,
- lastReadAt: i.createdAt,
- lastReadMessageId: i.msgId,
- lastReadSeq: i.seq,
- }))
- );
- }
- }
+ const statements = latest.map((message) => markReadToMessageBuilder(db, {
+ userId,
+ channelId: message.channelId,
+ message,
+ }));
+ const effectConditions = latest.map((message) =>
+ readStateAdvancesCondition(db, {
+ userId,
+ channelId: message.channelId,
+ targetSeq: message.seq,
+ })
+ );
+ const effectCondition = effectConditions.slice(1).reduce(
+ (combined, condition) => or(combined, condition)!,
+ effectConditions[0]!
+ );
+ const results = await db.batch([
+ advanceReadStateRevisionWhenBuilder(db, userId, effectCondition),
+ ...statements,
+ accountReadStateRevisionBuilder(db, userId),
+ ] as any) as unknown as unknown[][];
+ const changed = (results[0] as Array<{ revision: number }>).length > 0;
+ const revision = (results.at(-1) as Array<{ revision: number }> | undefined)?.[0]?.revision ?? 0;
- return latest.length;
+ return {
+ count: latest.length,
+ changed,
+ revision,
+ };
}
/**
@@ -260,15 +439,19 @@ export async function markAllServerChannelsRead(
* the same channel mark-read path. Same invariant, monotone guard, and
* "empty conversations are skipped" semantics.
*/
-// lastReadSeq intentionally not maintained here — see comment on
-// `markReadToMessageBuilder` above.
export async function markAllDmsRead(
db: Database,
userId: string
-): Promise<number> {
+): Promise<ReadAllResult> {
const dms = await listDMs(db, userId);
const dmChannelIds = dms.map((d) => d.id);
- if (dmChannelIds.length === 0) return 0;
+ if (dmChannelIds.length === 0) {
+ return {
+ count: 0,
+ changed: false,
+ revision: await getCurrentAccountReadStateRevision(db, userId),
+ };
+ }
return markAllServerChannelsRead(db, userId, dmChannelIds);
}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index f5edd5f88..76896cc4d 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -576,6 +576,8 @@ export type {
CommunityStatusUpdate,
CommunityMentionCreate,
CommunityUnreadBump,
+ CommunityReadStateAdvanced,
+ CommunityInboxChanged,
CommunityMachineCreated,
CommunityMachineStatus,
CommunityMachineUpdated,
diff --git a/src/shared/test/community-message-createMessage.test.ts b/src/shared/test/community-message-createMessage.test.ts
index 55add600a..974bdded6 100644
--- a/src/shared/test/community-message-createMessage.test.ts
+++ b/src/shared/test/community-message-createMessage.test.ts
@@ -8,8 +8,9 @@ import type { Database } from "../src/index";
*
* `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)
+ * (2) db.batch([insertMsg.returning(), scopeUpdate, authorWatermark]) —
+ * atomic author-send aggregate write. The message id is pre-minted so
+ * the watermark no longer needs a post-batch await.
*
* These tests mock the Database builder chain and assert the batch's
* contents, without needing a real D1 backend.
@@ -19,12 +20,15 @@ type BuilderTag =
| { kind: "insert-msg" }
| { kind: "update-channel" }
| { kind: "update-dm" }
+ | { kind: "insert-revision" }
+ | { kind: "select-readstates" }
| { kind: "insert-readstate"; values: Record<string, unknown> };
interface MockDb {
batchCalls: Array<BuilderTag[]>;
awaitedStatements: BuilderTag[];
seqReturned: number;
+ messageId?: string;
}
function makeMockDb(seq: number): { db: Database; state: MockDb } {
@@ -50,6 +54,9 @@ function makeMockDb(seq: number): { db: Database; state: MockDb } {
const db: any = {
insert: (table: any) => {
const name = getTableName(table);
+ if (name.includes("read_state_revision")) {
+ return makeReturningBuilder({ kind: "insert-revision" }, [{ revision: 3 }]);
+ }
if (name.includes("read_state")) {
// Read-state upsert captures its `values(...)` payload for assertions.
const b: any = { __tag: { kind: "insert-readstate", values: {} } };
@@ -66,8 +73,12 @@ function makeMockDb(seq: number): { db: Database; state: MockDb } {
}
// 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]);
+ const b = makeReturningBuilder({ kind: "insert-msg" }, []);
+ b.values = (values: { id: string }) => {
+ state.messageId = values.id;
+ return b;
+ };
+ return b;
},
update: (table: any) => {
const name = getTableName(table);
@@ -76,6 +87,17 @@ function makeMockDb(seq: number): { db: Database; state: MockDb } {
: { kind: "update-channel" };
return makeReturningBuilder(tag, undefined);
},
+ select: () => {
+ const row = {
+ channelId: "chan_1",
+ lastReadMessageId: state.messageId!,
+ lastReadAt: "2026-01-01T00:00:00.000Z",
+ lastReadSeq: state.seqReturned,
+ };
+ const b = makeReturningBuilder({ kind: "select-readstates" }, [row]);
+ b.from = () => b;
+ return b;
+ },
batch: (stmts: any[]) => {
const tags = stmts.map((s) => s.__tag as BuilderTag);
state.batchCalls.push(tags);
@@ -84,7 +106,16 @@ function makeMockDb(seq: number): { db: Database; state: MockDb } {
return Promise.resolve(
tags.map((t) =>
t.kind === "insert-msg"
- ? [{ id: "msg_test", seq: state.seqReturned, createdAt: "2026-01-01T00:00:00.000Z" }]
+ ? [{ id: state.messageId!, seq: state.seqReturned, createdAt: "2026-01-01T00:00:00.000Z" }]
+ : t.kind === "insert-revision"
+ ? [{ revision: 3 }]
+ : t.kind === "select-readstates"
+ ? [{
+ channelId: "chan_1",
+ lastReadMessageId: state.messageId!,
+ lastReadAt: "2026-01-01T00:00:00.000Z",
+ lastReadSeq: state.seqReturned,
+ }]
: undefined
)
);
@@ -113,7 +144,7 @@ describe("createMessage — batch composition", () => {
vi.clearAllMocks();
});
- it("channel send: batches (insert msg, update channel) and separately upserts author read-state with lastReadSeq", async () => {
+ it("channel send atomically batches message, channel, and author read-state watermark", async () => {
const { db, state } = makeMockDb(42);
const msg = await queries.communityMessage.createMessage(db, {
authorId: "user_1",
@@ -123,23 +154,21 @@ describe("createMessage — batch composition", () => {
expect(state.batchCalls).toHaveLength(1);
const batchTags = state.batchCalls[0]!.map((t) => t.kind);
- expect(batchTags).toEqual(["insert-msg", "update-channel"]);
+ expect(batchTags).toEqual(["insert-msg", "update-channel", "insert-readstate"]);
- // 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");
+ const readState = state.batchCalls[0]!.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.lastReadMessageId).toBe(msg.id);
expect(values.channelId).toBe("chan_1");
- expect(msg.id).toBe("msg_test");
+ expect(msg.id).toBe(state.messageId);
expect(msg.seq).toBe(42);
});
- it("DM send: a DM is a type=dm channel, so it batches (insert msg, update channel) and separately upserts author read-state with lastReadSeq", async () => {
+ it("DM send atomically batches message, channel, and author read-state watermark", async () => {
const { db, state } = makeMockDb(7);
const msg = await queries.communityMessage.createMessage(db, {
authorId: "user_1",
@@ -150,17 +179,64 @@ describe("createMessage — batch composition", () => {
expect(state.batchCalls).toHaveLength(1);
const batchTags = state.batchCalls[0]!.map((t) => t.kind);
// DMs are channels now — the scope bump always targets communityChannel.
- expect(batchTags).toEqual(["insert-msg", "update-channel"]);
+ expect(batchTags).toEqual(["insert-msg", "update-channel", "insert-readstate"]);
- const readState = state.awaitedStatements.find((s) => s.kind === "insert-readstate");
+ const readState = state.batchCalls[0]!.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.lastReadMessageId).toBe(msg.id);
expect(values.channelId).toBe("dm_chan_1");
- expect(msg.id).toBe("msg_test");
+ expect(msg.id).toBe(state.messageId);
expect(msg.seq).toBe(7);
});
+
+ it("human send atomically appends a revision without materializing account rows", async () => {
+ const { db, state } = makeMockDb(9);
+ const msg = await queries.communityMessage.createMessage(db, {
+ authorId: "human_1",
+ authorKind: "human",
+ content: "hello from another device",
+ channelId: "chan_1",
+ });
+
+ expect(state.batchCalls[0]!.map((statement) => statement.kind)).toEqual([
+ "insert-msg",
+ "update-channel",
+ "insert-readstate",
+ "insert-revision",
+ ]);
+ expect(msg.readStateRevision).toBe(3);
+ });
+
+ it("human forum opener uses the same ordinary author cursor as every channel type", async () => {
+ const { db, state } = makeMockDb(13);
+ const msg = await queries.communityMessage.createMessage(db, {
+ authorId: "human_1",
+ authorKind: "human",
+ content: "A new forum post",
+ channelId: "forum_1",
+ });
+
+ expect(state.batchCalls).toHaveLength(1);
+ expect(state.batchCalls[0]!.map((statement) => statement.kind)).toEqual([
+ "insert-msg",
+ "update-channel",
+ "insert-readstate",
+ "insert-revision",
+ ]);
+ const cursor = state.batchCalls[0]!.find(
+ (statement): statement is Extract<BuilderTag, { kind: "insert-readstate" }> =>
+ statement.kind === "insert-readstate",
+ );
+ expect(cursor?.values).toMatchObject({
+ userId: "human_1",
+ channelId: "forum_1",
+ lastReadMessageId: msg.id,
+ lastReadSeq: 13,
+ });
+ expect(msg.readStateRevision).toBe(3);
+ });
});
diff --git a/src/shared/test/community-message-hardDelete.test.ts b/src/shared/test/community-message-hardDelete.test.ts
index 3bbd0f1c1..6f8b893a9 100644
--- a/src/shared/test/community-message-hardDelete.test.ts
+++ b/src/shared/test/community-message-hardDelete.test.ts
@@ -7,13 +7,14 @@ import type { Database } from "../src/index";
* Tests for the cascading `hardDeleteMessage`. It:
* 1. SELECTs the message row (channelId/dmConversationId/authorId/seq/createdAt).
* 2. SELECTs the prior message in scope (id, seq, createdAt) for the read-state revert.
- * 3. Runs one `db.batch([delete-msg, update-scope, update-or-delete-readstate])`.
+ * 3. Runs one `db.batch([update-scope, update-or-delete-readstate, delete-msg])`.
* The batch composition varies by whether the target is a channel/DM and whether
* a prior message exists.
*/
type SelectShape = "message" | "prior";
type Tag =
+ | { kind: "revision" }
| { kind: "delete-msg" }
| { kind: "update-channel"; setValues?: Record<string, unknown> }
| { kind: "update-dm"; setValues?: Record<string, unknown> }
@@ -23,6 +24,9 @@ type Tag =
interface MockState {
batchCalls: Tag[][];
selectQueue: Array<{ shape: SelectShape; rows: unknown[] }>;
+ impactedQueue?: unknown[][];
+ revisionRows?: Array<{ userId: string; revision: number }>;
+ deletedRows?: Array<{ id: string }>;
}
function makeDb(state: MockState): Database {
@@ -37,6 +41,7 @@ function makeDb(state: MockState): Database {
b.where = () => b;
b.limit = () => b;
b.orderBy = () => b;
+ b.returning = () => b;
return b;
};
@@ -53,6 +58,13 @@ function makeDb(state: MockState): Database {
};
return b;
},
+ selectDistinct: () => {
+ const b: any = {};
+ b.from = () => b;
+ b.innerJoin = () => b;
+ b.where = () => Promise.resolve(state.impactedQueue?.shift() ?? []);
+ return b;
+ },
delete: (table: any) => {
const name = getTableName(table);
const tag: Tag = name.includes("read_state")
@@ -60,6 +72,12 @@ function makeDb(state: MockState): Database {
: { kind: "delete-msg" };
return mkBuilder(tag);
},
+ insert: () => {
+ const b = mkBuilder({ kind: "revision" });
+ b.select = () => b;
+ b.onConflictDoUpdate = () => b;
+ return b;
+ },
update: (table: any) => {
const name = getTableName(table);
const tag: Tag = name.includes("read_state")
@@ -71,14 +89,20 @@ function makeDb(state: MockState): Database {
},
batch: (stmts: any[]) => {
state.batchCalls.push(stmts.map((s) => s.__tag as Tag));
- return Promise.resolve(stmts.map(() => undefined));
+ return Promise.resolve(stmts.map((statement) => (
+ statement.__tag?.kind === "delete-msg"
+ ? state.deletedRows ?? [{ id: "msg_1" }]
+ : statement.__tag?.kind === "revision"
+ ? state.revisionRows ?? []
+ : []
+ )));
},
};
return db as Database;
}
describe("hardDeleteMessage — cascading rollback", () => {
- it("channel + prior message exists → batch(delete-msg, update-channel, update-readstate)", async () => {
+ it("channel + prior message exists → repairs pointers before deleting the message", async () => {
const state: MockState = {
batchCalls: [],
selectQueue: [
@@ -103,10 +127,10 @@ describe("hardDeleteMessage — cascading rollback", () => {
};
await queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1");
expect(state.batchCalls).toHaveLength(1);
- const [del, upChan, upRs] = state.batchCalls[0]!;
- expect(del.kind).toBe("delete-msg");
+ const [upChan, upRs, del] = state.batchCalls[0]!;
expect(upChan.kind).toBe("update-channel");
expect(upRs.kind).toBe("update-readstate");
+ expect(del.kind).toBe("delete-msg");
// Regression guard for the plan's "CRITICAL" rule: messageCount must be a
// SQL fragment / decrement expression, NOT a JS literal like `oldCount - 1`
// (a concurrent inbound insert between the SELECT and this UPDATE would
@@ -123,7 +147,7 @@ describe("hardDeleteMessage — cascading rollback", () => {
expect(rsSet.lastReadAt).toBe("2026-01-01T00:00:04Z");
});
- it("channel + NO prior message (first-ever sender) → batch(delete-msg, update-channel, DELETE-readstate)", async () => {
+ it("channel + NO prior message (first-ever sender) → removes pointers before deleting the message", async () => {
const state: MockState = {
batchCalls: [],
selectQueue: [
@@ -145,10 +169,10 @@ describe("hardDeleteMessage — cascading rollback", () => {
};
await queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1");
const kinds = state.batchCalls[0]!.map((t) => t.kind);
- expect(kinds).toEqual(["delete-msg", "update-channel", "delete-readstate"]);
+ expect(kinds).toEqual(["update-channel", "delete-readstate", "delete-msg"]);
});
- it("DM channel + prior message → batch(delete-msg, update-channel, update-readstate) — a DM is a channel now", async () => {
+ it("DM channel + prior message → repairs pointers before deleting the message", async () => {
const state: MockState = {
batchCalls: [],
selectQueue: [
@@ -171,11 +195,11 @@ describe("hardDeleteMessage — cascading rollback", () => {
],
};
await queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1");
- const [, upChan, upRs] = state.batchCalls[0]!;
+ const [upChan, upRs] = state.batchCalls[0]!;
const kinds = state.batchCalls[0]!.map((t) => t.kind);
// DMs are channels now — the scope revert always targets communityChannel,
// messageCount and all.
- expect(kinds).toEqual(["delete-msg", "update-channel", "update-readstate"]);
+ expect(kinds).toEqual(["update-channel", "update-readstate", "delete-msg"]);
const chanSet = (upChan as { setValues?: Record<string, unknown> }).setValues!;
expect(typeof chanSet.messageCount).toBe("object"); // Drizzle SQL fragment
expect(typeof chanSet.lastMessageAt).toBe("object"); // inline SQL subquery
@@ -192,4 +216,73 @@ describe("hardDeleteMessage — cascading rollback", () => {
await queries.communityMessage.hardDeleteMessage(makeDb(state), "missing");
expect(state.batchCalls).toHaveLength(0);
});
+
+ it("idempotent — target disappears after selection → no retry and no throw", async () => {
+ const state: MockState = {
+ batchCalls: [],
+ selectQueue: [
+ {
+ shape: "message",
+ rows: [{
+ id: "msg_1",
+ channelId: "chan_1",
+ authorId: "user_1",
+ seq: 1,
+ createdAt: "2026-01-01T00:00:01Z",
+ }],
+ },
+ { shape: "prior", rows: [] },
+ { shape: "message", rows: [] },
+ ],
+ deletedRows: [],
+ };
+
+ await expect(
+ queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1"),
+ ).resolves.toBeNull();
+ expect(state.batchCalls).toHaveLength(1);
+ });
+
+ it("versions the union of pointer, sparse-opener, and mention owners before deleting", async () => {
+ const state: MockState = {
+ batchCalls: [],
+ selectQueue: [
+ {
+ shape: "message",
+ rows: [{
+ id: "msg_1",
+ channelId: "chan_1",
+ authorId: "author_1",
+ seq: 5,
+ createdAt: "2026-01-01T00:00:05Z",
+ }],
+ },
+ {
+ shape: "prior",
+ rows: [{ id: "msg_0", seq: 4, createdAt: "2026-01-01T00:00:04Z" }],
+ },
+ ],
+ impactedQueue: [
+ [{ userId: "pointer-owner" }],
+ [{ userId: "sparse-owner" }, { userId: "shared-owner" }],
+ [{ userId: "mention-owner" }, { userId: "shared-owner" }],
+ ],
+ revisionRows: [
+ { userId: "pointer-owner", revision: 2 },
+ { userId: "sparse-owner", revision: 3 },
+ { userId: "shared-owner", revision: 4 },
+ { userId: "mention-owner", revision: 5 },
+ ],
+ };
+
+ await expect(
+ queries.communityMessage.hardDeleteMessage(makeDb(state), "msg_1")
+ ).resolves.toEqual({ readStateRevisions: state.revisionRows });
+ expect(state.batchCalls[0]!.map((tag) => tag.kind)).toEqual([
+ "revision",
+ "update-channel",
+ "update-readstate",
+ "delete-msg",
+ ]);
+ });
});
diff --git a/src/shared/test/community-ws-bundle.contract.test.ts b/src/shared/test/community-ws-bundle.contract.test.ts
index 45d019a83..523370676 100644
--- a/src/shared/test/community-ws-bundle.contract.test.ts
+++ b/src/shared/test/community-ws-bundle.contract.test.ts
@@ -88,7 +88,7 @@ describe("community WS batch transport contract", () => {
expect(isCommunityDeliveryDigest("a".repeat(63))).toBe(false)
})
- it("round-trips one strict outer frame without entering the 41-event union", async () => {
+ it("round-trips one strict outer frame without entering the 43-event union", async () => {
const operationId = await deriveCommunityDeliveryOperationId("message-1")
const prepared = await prepareCommunityDeliveryEvents(children)
expect(prepared.ok).toBe(true)
@@ -116,7 +116,7 @@ describe("community WS batch transport contract", () => {
})
expect(isCommunityBrowserEventBatchCandidate(encoded.batch)).toBe(true)
expect(Object.values(WS_EVENTS)).not.toContain(COMMUNITY_BROWSER_EVENT_BATCH_TYPE)
- expect(Object.values(WS_EVENTS)).toHaveLength(41)
+ expect(Object.values(WS_EVENTS)).toHaveLength(43)
})
it("rejects invalid count, child, operation metadata, digest mismatch, and strict outer keys", async () => {
diff --git a/src/shared/test/community-ws-events.contract.test.ts b/src/shared/test/community-ws-events.contract.test.ts
index 6f5b5918b..ea955f9f2 100644
--- a/src/shared/test/community-ws-events.contract.test.ts
+++ b/src/shared/test/community-ws-events.contract.test.ts
@@ -65,13 +65,13 @@ describe("Community browser event runtime contract", () => {
const fixtures = Object.values(communityWsEventFixtures)
const names = Object.values(WS_EVENTS).sort()
- it("locks the exact 41-event inventory", () => {
- expect(names).toHaveLength(41)
+ it("locks the exact 43-event inventory", () => {
+ expect(names).toHaveLength(43)
expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)
expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)
})
- it("decodes and canonically encodes all 41 current event fixtures", () => {
+ it("decodes and canonically encodes all 43 current event fixtures", () => {
for (const fixture of fixtures) {
expect(decodeCommunityBrowserEvent(fixture)).toEqual({ ok: true, event: fixture })
const encoded = encodeCommunityBrowserEvent(fixture)
@@ -95,6 +95,43 @@ describe("Community browser event runtime contract", () => {
}
})
+ it("uses a bounded read-state dirty hint instead of an account-sized frame", () => {
+ expect(decodeCommunityBrowserEvent({
+ type: "community:read_state.advanced",
+ revision: 4,
+ inboxChanged: true,
+ })).toMatchObject({ ok: true })
+ expect(decodeCommunityBrowserEvent({
+ type: "community:inbox.changed",
+ revision: 5,
+ inboxChanged: true,
+ reason: "read_all",
+ })).toMatchObject({ ok: true })
+
+ const accountSizedFrame = {
+ type: "community:read_state.advanced",
+ revision: 4,
+ readStates: Array.from({ length: 500 }, (_, index) => ({
+ channelId: `channel-${index}-${"c".repeat(72)}`,
+ lastReadMessageId: `message-${index}-${"m".repeat(72)}`,
+ lastReadAt: "2026-08-24T00:00:00.000Z",
+ lastReadSeq: index,
+ })),
+ inboxChanged: true,
+ }
+ expect(utf8ByteLength(JSON.stringify(accountSizedFrame)))
+ .toBeGreaterThan(COMMUNITY_BROWSER_EVENT_MAX_BYTES)
+ expect(decodeCommunityBrowserEvent(accountSizedFrame))
+ .toMatchObject({ ok: false, reason: "invalid-payload" })
+ const encodedHint = encodeCommunityBrowserEvent({
+ type: "community:read_state.advanced",
+ revision: 4,
+ inboxChanged: true,
+ })
+ expect(encodedHint).toMatchObject({ ok: true })
+ if (encodedHint.ok) expect(encodedHint.byteLength).toBeLessThan(128)
+ })
+
it("fails closed for family, removed-version, shape, and strict-key errors", () => {
expect(decodeCommunityBrowserEvent(null)).toMatchObject({ reason: "non-object" })
expect(decodeCommunityBrowserEvent([])).toMatchObject({ reason: "non-object" })
diff --git a/src/shared/test/community-ws-events.fixtures.ts b/src/shared/test/community-ws-events.fixtures.ts
index 39c2bb80e..04e6481cc 100644
--- a/src/shared/test/community-ws-events.fixtures.ts
+++ b/src/shared/test/community-ws-events.fixtures.ts
@@ -226,6 +226,17 @@ export const communityWsEventFixtures = {
userId: "user-1",
channelId: "channel-1",
},
+ "community:read_state.advanced": {
+ type: "community:read_state.advanced",
+ revision: 1,
+ inboxChanged: true,
+ },
+ "community:inbox.changed": {
+ type: "community:inbox.changed",
+ revision: 2,
+ inboxChanged: true,
+ reason: "read_all",
+ },
"community:presence.update": {
type: "community:presence.update",
userId: "user-1",
@@ -297,6 +308,8 @@ export const requiredFixturePaths = {
"community:invite.create": ["invite"],
"community:mention.create": ["messageId"],
"community:unread.bump": ["channelId"],
+ "community:read_state.advanced": ["revision"],
+ "community:inbox.changed": ["reason"],
"community:presence.update": ["online"],
"community:status.update": ["statusText"],
"community:machine.created": ["machine"],
diff --git a/src/shared/test/community-ws-events.test.ts b/src/shared/test/community-ws-events.test.ts
index 0fb32a3ef..e79db3511 100644
--- a/src/shared/test/community-ws-events.test.ts
+++ b/src/shared/test/community-ws-events.test.ts
@@ -64,7 +64,7 @@ describe("CommunityMessageEdited address contract", () => {
describe("isCommunityEvent", () => {
it("accepts every exact event declared by WS_EVENTS", () => {
- expect(Object.values(WS_EVENTS)).toHaveLength(41);
+ expect(Object.values(WS_EVENTS)).toHaveLength(43);
for (const type of Object.values(WS_EVENTS)) {
expect(isCommunityEvent({ type })).toBe(true);
}
diff --git a/src/shared/test/queries/community-mention-revision.test.ts b/src/shared/test/queries/community-mention-revision.test.ts
new file mode 100644
index 000000000..c6bde1985
--- /dev/null
+++ b/src/shared/test/queries/community-mention-revision.test.ts
@@ -0,0 +1,91 @@
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { eq } from "drizzle-orm"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import type { Database } from "../../src/db"
+import { user } from "../../src/db/schema"
+import {
+ dismissMentionWithRevision,
+ markAllMentionsReadWithRevision,
+ markMessageMentionsReadBuilder,
+ unreadChannelMentionThroughSeqCondition,
+ unreadMessageMentionCondition,
+} from "../../src/db/queries/community/mention"
+
+describe("community mention revision effects", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE user (id TEXT PRIMARY KEY);
+ CREATE TABLE community_message (
+ id TEXT PRIMARY KEY,
+ channel_id TEXT NOT NULL,
+ seq INTEGER NOT NULL
+ );
+ CREATE TABLE community_mention (
+ id TEXT PRIMARY KEY,
+ message_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ read INTEGER NOT NULL DEFAULT 0
+ );
+ CREATE TABLE community_read_state_revision (
+ user_id TEXT PRIMARY KEY,
+ revision INTEGER NOT NULL DEFAULT 0
+ );
+ INSERT INTO user (id) VALUES ('u1');
+ INSERT INTO community_message (id, channel_id, seq) VALUES
+ ('m1', 'c1', 1),
+ ('m5', 'c1', 5);
+ INSERT INTO community_mention (id, message_id, user_id, read) VALUES
+ ('mention-1', 'm1', 'u1', 0),
+ ('mention-5', 'm5', 'u1', 0);
+ `)
+ const betterDb = drizzle(sqlite)
+ ;(betterDb as any).batch = async (statements: any[]) =>
+ sqlite.transaction(() => statements.map((statement) => {
+ try {
+ return statement.all()
+ } catch (error) {
+ if (error instanceof TypeError && error.message.includes("does not return data")) {
+ return statement.run()
+ }
+ throw error
+ }
+ }))()
+ db = betterDb as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ function conditions() {
+ return (db as any)
+ .select({
+ throughOne: unreadChannelMentionThroughSeqCondition(db, "u1", "c1", 1),
+ exactFive: unreadMessageMentionCondition(db, "u1", "m5"),
+ })
+ .from(user)
+ .where(eq(user.id, "u1"))
+ .get()
+ }
+
+ it("guards bounded mention repairs and versions only real mark-all or dismiss effects", async () => {
+ expect(conditions()).toEqual({ throughOne: 1, exactFive: 1 })
+
+ ;(markMessageMentionsReadBuilder(db, "u1", "m5") as any).run()
+ expect(conditions()).toEqual({ throughOne: 1, exactFive: 0 })
+
+ await expect(markAllMentionsReadWithRevision(db, "u1"))
+ .resolves.toEqual({ changed: true, revision: 1 })
+ await expect(markAllMentionsReadWithRevision(db, "u1"))
+ .resolves.toEqual({ changed: false, revision: 1 })
+
+ sqlite.prepare("UPDATE community_mention SET read = 0 WHERE id = 'mention-1'").run()
+ await expect(dismissMentionWithRevision(db, "u1", "mention-1"))
+ .resolves.toEqual({ changed: true, revision: 2 })
+ await expect(dismissMentionWithRevision(db, "u1", "mention-1"))
+ .resolves.toEqual({ changed: false, revision: 2 })
+ })
+})
diff --git a/src/shared/test/queries/community-message.test.ts b/src/shared/test/queries/community-message.test.ts
index f44927949..44c3b2d28 100644
--- a/src/shared/test/queries/community-message.test.ts
+++ b/src/shared/test/queries/community-message.test.ts
@@ -961,8 +961,8 @@ describe("getLatestMessagesByChannelIds", () => {
describe("read-state invariant property — every write path", () => {
// Fixture message tuples used across paths.
- const CHANNEL_MSG = { id: "m_ch_latest", createdAt: "2026-07-05T10:00:00.000Z" };
- const DM_MSG = { id: "m_dm_latest", createdAt: "2026-07-05T11:00:00.000Z" };
+ const CHANNEL_MSG = { id: "m_ch_latest", createdAt: "2026-07-05T10:00:00.000Z", seq: 10 };
+ const DM_MSG = { id: "m_dm_latest", createdAt: "2026-07-05T11:00:00.000Z", seq: 11 };
// Capture every insert/onConflict/update `set` payload that touches
// communityReadState.
@@ -975,8 +975,9 @@ describe("read-state invariant property — every write path", () => {
function makePropertyDb() {
let seqCounter = 0;
const db: any = {
- insert: vi.fn((table: unknown) => ({
- values: vi.fn((v: any) => {
+ insert: vi.fn((table: unknown) => {
+ const insert: any = {
+ values: vi.fn((v: any) => {
if (table === communityMessageSeq) {
// `claimNextSeq`'s counter row — not a read-state write, doesn't
// carry lastReadAt/lastReadMessageId, so it's a no-op for `writes`.
@@ -994,27 +995,37 @@ describe("read-state invariant property — every write path", () => {
} else {
writes.push({ lastReadAt: v.lastReadAt, lastReadMessageId: v.lastReadMessageId });
}
- const chain: any = {
- returning: vi.fn(() =>
- Promise.resolve([{ ...v, id: v.id ?? "m_generated" }])
- ),
- onConflictDoUpdate: vi.fn((cfg: any) => {
+ const chain: any = {};
+ chain.returning = vi.fn(() =>
+ Promise.resolve([{ ...v, id: v.id ?? "m_generated", revision: 1 }])
+ );
+ chain.onConflictDoUpdate = vi.fn((cfg: any) => {
writes.push({
lastReadAt: cfg.set.lastReadAt,
lastReadMessageId: cfg.set.lastReadMessageId,
});
- return { __builder: "insert-onconflict" };
- }),
- };
- return chain;
- }),
- })),
+ return chain;
+ });
+ return chain;
+ }),
+ select: vi.fn(() => {
+ const chain: any = {};
+ chain.onConflictDoUpdate = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([]));
+ return chain;
+ }),
+ };
+ return insert;
+ }),
update: vi.fn(() => ({
set: vi.fn((s: any) => {
writes.push({ lastReadAt: s.lastReadAt, lastReadMessageId: s.lastReadMessageId });
return { where: vi.fn(() => Promise.resolve()) };
}),
})),
+ delete: vi.fn(() => ({
+ where: vi.fn(() => Promise.resolve()),
+ })),
select: vi.fn(() => {
const chain: any = {};
chain.from = vi.fn(() => chain);
@@ -1023,7 +1034,9 @@ describe("read-state invariant property — every write path", () => {
chain.as = vi.fn(() => chain);
chain.orderBy = vi.fn(() => chain);
chain.limit = vi.fn(() => Promise.resolve([]));
- chain.where = vi.fn(() => Promise.resolve([]));
+ chain.where = vi.fn(() => chain);
+ chain.then = (resolve: (value: unknown[]) => unknown) =>
+ Promise.resolve([]).then(resolve);
return chain;
}),
// `createMessage` composes (insert msg, update scope) into a single
@@ -1093,13 +1106,15 @@ describe("read-state invariant property — every write path", () => {
chain.as = vi.fn(() => chain);
chain.orderBy = vi.fn(() => chain);
chain.limit = vi.fn(() => Promise.resolve([]));
- chain.where = vi.fn(() => Promise.resolve([]));
+ chain.where = vi.fn(() => chain);
+ chain.then = (resolve: (value: unknown[]) => unknown) =>
+ Promise.resolve([]).then(resolve);
return chain;
});
const spy = vi
.spyOn(msg, "getLatestMessagesByChannelIds")
.mockResolvedValue([
- { channelId: "c_mass", id: "m_mass_latest", createdAt: "2026-07-06T00:00:00.000Z" },
+ { channelId: "c_mass", id: "m_mass_latest", createdAt: "2026-07-06T00:00:00.000Z", seq: 12 },
]);
await readState.markAllServerChannelsRead(dbF, "u_1", ["c_mass"]);
spy.mockRestore();
diff --git a/src/shared/test/queries/community-notification-cursor-clear.test.ts b/src/shared/test/queries/community-notification-cursor-clear.test.ts
index 4c8d25871..ad08fef83 100644
--- a/src/shared/test/queries/community-notification-cursor-clear.test.ts
+++ b/src/shared/test/queries/community-notification-cursor-clear.test.ts
@@ -97,6 +97,10 @@ describe("notification setting cursor-clear contract", () => {
last_read_seq INTEGER NOT NULL DEFAULT 0,
UNIQUE(user_id, channel_id)
);
+ CREATE TABLE community_read_state_revision (
+ user_id TEXT PRIMARY KEY,
+ revision INTEGER NOT NULL DEFAULT 0
+ );
CREATE TABLE community_channel_member (
channel_id TEXT NOT NULL,
user_id TEXT NOT NULL,
@@ -148,7 +152,16 @@ describe("notification setting cursor-clear contract", () => {
`);
const betterDb = drizzle(sqlite);
(betterDb as any).batch = async (statements: any[]) =>
- sqlite.transaction(() => statements.map((statement) => statement.run()))();
+ sqlite.transaction(() => statements.map((statement) => {
+ try {
+ return statement.all();
+ } catch (error) {
+ if (error instanceof TypeError && error.message.includes("does not return data")) {
+ return statement.run();
+ }
+ throw error;
+ }
+ }))();
db = betterDb as unknown as Database;
});
@@ -162,7 +175,7 @@ describe("notification setting cursor-clear contract", () => {
`).all();
it("atomically sets a server level and clears every non-empty channel in that server", async () => {
- await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" });
+ await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" });
expect(cursors()).toEqual([
{ channel_id: "child", last_read_message_id: "child-3", last_read_at: "2026-01-01T00:00:03Z", last_read_seq: 3 },
@@ -173,18 +186,62 @@ describe("notification setting cursor-clear contract", () => {
.toEqual({ level: "nothing" });
});
+ it("keeps bot policy writes outside the human revision stream", async () => {
+ const result = await setChannelLevel(db, {
+ userId: "u",
+ channelId: "parent",
+ level: "nothing",
+ actorKind: "bot",
+ });
+
+ expect(result.readStateRevision).toBeNull();
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_read_state_revision").get())
+ .toEqual({ count: 0 });
+ });
+
+ it("advances a forum's ordinary cursor and versions only an effective policy change", async () => {
+ sqlite.exec(`
+ UPDATE community_channel SET type = 'forum' WHERE id = 'parent';
+ `);
+
+ const first = await setChannelLevel(db, {
+ userId: "u",
+ channelId: "parent",
+ level: "nothing",
+ actorKind: "human",
+ });
+ expect(first.readStateRevision).toBe(1);
+ expect(cursors()).toContainEqual({
+ channel_id: "parent",
+ last_read_message_id: "parent-2",
+ last_read_at: "2026-01-01T00:00:02Z",
+ last_read_seq: 2,
+ });
+
+ const duplicate = await setChannelLevel(db, {
+ userId: "u",
+ channelId: "parent",
+ level: "nothing",
+ actorKind: "human",
+ });
+ expect(duplicate.readStateRevision).toBeNull();
+ expect(sqlite.prepare(`
+ SELECT revision FROM community_read_state_revision WHERE user_id = 'u'
+ `).get()).toEqual({ revision: 1 });
+ });
+
it("does not clear a private channel the target identity cannot access", async () => {
sqlite.exec(`
INSERT INTO community_category (id, server_id, private) VALUES ('private', 'server', 1);
UPDATE community_channel SET category_id = 'private', creator_id = 'author' WHERE id = 'sibling';
`);
- await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" });
+ await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" });
expect(cursors().map((row: any) => row.channel_id)).toEqual(["child", "parent"]);
});
it("a parent override clears the parent and its children, but not a sibling", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions" });
+ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions", actorKind: "human" });
expect(cursors().map((row: any) => row.channel_id)).toEqual(["child", "parent"]);
});
@@ -194,27 +251,27 @@ describe("notification setting cursor-clear contract", () => {
VALUES ('child-own', 'u', 'child', 'all')
`).run();
- await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" });
+ await setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" });
expect(cursors().map((row: any) => row.channel_id)).toEqual(["parent", "sibling"]);
});
it("does not clear when an explicit override leaves the effective level unchanged", async () => {
- await setServerLevel(db, { userId: "u", serverId: "server", level: "mentions" });
+ await setServerLevel(db, { userId: "u", serverId: "server", level: "mentions", actorKind: "human" });
sqlite.prepare("DELETE FROM community_read_state").run();
- await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions" });
+ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "mentions", actorKind: "human" });
expect(cursors()).toEqual([]);
});
it("an idempotent retry preserves messages that arrived after the successful change", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing" });
+ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing", actorKind: "human" });
sqlite.exec(`
INSERT INTO community_message (id, channel_id, created_at, seq) VALUES
('parent-6', 'parent', '2026-01-01T00:00:06Z', 6),
('child-7', 'child', '2026-01-01T00:00:07Z', 7);
`);
- await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing" });
+ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "nothing", actorKind: "human" });
expect(cursors()).toEqual([
{ channel_id: "child", last_read_message_id: "child-3", last_read_at: "2026-01-01T00:00:03Z", last_read_seq: 3 },
{ channel_id: "parent", last_read_message_id: "parent-2", last_read_at: "2026-01-01T00:00:02Z", last_read_seq: 2 },
@@ -222,14 +279,14 @@ describe("notification setting cursor-clear contract", () => {
});
it("a DM uses the same channel-scope setting and only clears that DM", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing" });
+ await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing", actorKind: "human" });
expect(cursors()).toEqual([
{ channel_id: "dm", last_read_message_id: "dm-5", last_read_at: "2026-01-01T00:00:05Z", last_read_seq: 5 },
]);
});
it("empty channels never manufacture a read-state row", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "empty", level: "nothing" });
+ await setChannelLevel(db, { userId: "u", channelId: "empty", level: "nothing", actorKind: "human" });
expect(cursors()).toEqual([]);
});
@@ -243,7 +300,7 @@ describe("notification setting cursor-clear contract", () => {
DELETE FROM community_message WHERE id = 'parent-9';
`);
- await setChannelLevel(db, { userId: "u", channelId: "parent", level: "all" });
+ await setChannelLevel(db, { userId: "u", channelId: "parent", level: "all", actorKind: "human" });
expect(sqlite.prepare("SELECT last_read_message_id, last_read_seq FROM community_read_state WHERE id='rs'").get())
.toEqual({ last_read_message_id: "parent-9", last_read_seq: 9 });
});
@@ -254,16 +311,16 @@ describe("notification setting cursor-clear contract", () => {
BEGIN SELECT RAISE(ABORT, 'cursor rejected'); END;
`);
- await expect(setServerLevel(db, { userId: "u", serverId: "server", level: "nothing" }))
+ await expect(setServerLevel(db, { userId: "u", serverId: "server", level: "nothing", actorKind: "human" }))
.rejects.toThrow("cursor rejected");
expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting").get())
.toEqual({ count: 0 });
});
it("override removal also clears old unread before inheriting again", async () => {
- await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing" });
+ await setChannelLevel(db, { userId: "u", channelId: "dm", level: "nothing", actorKind: "human" });
sqlite.prepare("DELETE FROM community_read_state").run();
- await removeChannelOverride(db, { userId: "u", channelId: "dm" });
+ await removeChannelOverride(db, { userId: "u", channelId: "dm", actorKind: "human" });
expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_notification_setting WHERE channel_id='dm'").get())
.toEqual({ count: 0 });
@@ -271,7 +328,7 @@ describe("notification setting cursor-clear contract", () => {
});
it("a no-op override removal preserves unread and creates no cursor", async () => {
- expect(await removeChannelOverride(db, { userId: "u", channelId: "dm" })).toBeNull();
+ expect((await removeChannelOverride(db, { userId: "u", channelId: "dm", actorKind: "human" })).setting).toBeNull();
expect(cursors()).toEqual([]);
});
@@ -307,7 +364,7 @@ describe("notification setting cursor-clear contract", () => {
const railCount = async () => (await listUserServers(db, "u"))[0]?.mentions;
await expect(railCount()).resolves.toBe(1);
- await setChannelLevel(db, { userId: "u", channelId: "child", level: "nothing" });
+ await setChannelLevel(db, { userId: "u", channelId: "child", level: "nothing", actorKind: "human" });
await expect(railCount()).resolves.toBe(0);
sqlite.exec(`
@@ -318,7 +375,7 @@ describe("notification setting cursor-clear contract", () => {
`);
await expect(railCount()).resolves.toBe(0);
- await setChannelLevel(db, { userId: "u", channelId: "child", level: "mentions" });
+ await setChannelLevel(db, { userId: "u", channelId: "child", level: "mentions", actorKind: "human" });
await expect(railCount()).resolves.toBe(0);
sqlite.exec(`
INSERT INTO community_message (id, channel_id, created_at, seq)
@@ -393,7 +450,7 @@ describe("notification setting cursor-clear contract", () => {
INSERT INTO community_channel_member (channel_id, user_id, relation, added_at)
VALUES ('forum-child', 'u', 'notify', '2025-01-01T00:00:00Z');
`);
- await setChannelLevel(db, { userId: "u", channelId: "forum-child", level: "mentions" });
+ await setChannelLevel(db, { userId: "u", channelId: "forum-child", level: "mentions", actorKind: "human" });
sqlite.exec(`
INSERT INTO community_message (id, channel_id, created_at, seq, content)
VALUES ('forum-normal', 'forum-child', '2026-01-01T00:00:01Z', 1, 'normal');
diff --git a/src/shared/test/queries/community-read-state-sqlite.test.ts b/src/shared/test/queries/community-read-state-sqlite.test.ts
new file mode 100644
index 000000000..e73435d5b
--- /dev/null
+++ b/src/shared/test/queries/community-read-state-sqlite.test.ts
@@ -0,0 +1,72 @@
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import type { Database } from "../../src/db"
+import {
+ advanceReadStateRevisionBuilder,
+ markReadToMessageBuilder,
+} from "../../src/db/queries/community/read-state"
+
+describe("community read-state SQLite monotonicity", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE community_read_state (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ last_read_at TEXT NOT NULL,
+ last_read_message_id TEXT,
+ last_read_seq INTEGER NOT NULL DEFAULT 0,
+ UNIQUE(user_id, channel_id)
+ );
+ CREATE TABLE community_read_state_revision (
+ user_id TEXT PRIMARY KEY,
+ revision INTEGER NOT NULL DEFAULT 0
+ );
+ `)
+ db = drizzle(sqlite) as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("orders equal-timestamp messages by seq and never regresses the aligned triple", () => {
+ ;(markReadToMessageBuilder(db, {
+ userId: "u1",
+ channelId: "c1",
+ message: { id: "m5", createdAt: "2026-08-24T00:00:00.000Z", seq: 5 },
+ }) as any).run()
+ ;(markReadToMessageBuilder(db, {
+ userId: "u1",
+ channelId: "c1",
+ message: { id: "m6", createdAt: "2026-08-24T00:00:00.000Z", seq: 6 },
+ }) as any).run()
+ ;(markReadToMessageBuilder(db, {
+ userId: "u1",
+ channelId: "c1",
+ message: { id: "m4", createdAt: "2026-08-24T00:01:00.000Z", seq: 4 },
+ }) as any).run()
+
+ expect(sqlite.prepare(`
+ SELECT last_read_message_id AS id, last_read_at AS at, last_read_seq AS seq
+ FROM community_read_state WHERE user_id = 'u1' AND channel_id = 'c1'
+ `).get()).toEqual({
+ id: "m6",
+ at: "2026-08-24T00:00:00.000Z",
+ seq: 6,
+ })
+ })
+
+ it("upserts one durable account revision and increments it atomically", () => {
+ const first = (advanceReadStateRevisionBuilder(db, "u1") as any).all()
+ const second = (advanceReadStateRevisionBuilder(db, "u1") as any).all()
+ expect(first).toEqual([{ revision: 1 }])
+ expect(second).toEqual([{ revision: 2 }])
+ expect(sqlite.prepare(`
+ SELECT user_id AS userId, revision FROM community_read_state_revision
+ `).all()).toEqual([{ userId: "u1", revision: 2 }])
+ })
+})
diff --git a/src/shared/test/queries/community-read-state.test.ts b/src/shared/test/queries/community-read-state.test.ts
index ee0842fac..047fceb33 100644
--- a/src/shared/test/queries/community-read-state.test.ts
+++ b/src/shared/test/queries/community-read-state.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi } from "vitest";
import * as readStateQueries from "../../src/db/queries/community/read-state";
import { communityReadState } from "../../src/db/community-schema";
+import { sql } from "drizzle-orm";
// `markReadToMessageBuilder` is the canonical channel/DM read-state upsert
// under the invariant unification (plan #4). It's used both stand-alone (DM
@@ -25,6 +26,71 @@ describe("community/read-state exports", () => {
it("exports markAllServerChannelsRead", () => {
expect(typeof readStateQueries.markAllServerChannelsRead).toBe("function");
});
+
+ it("builds one revision guard from multiple canonical effects", () => {
+ const db = makeMassMarkDbMock();
+ expect(readStateQueries.advanceReadStateRevisionWhenAnyBuilder(
+ db,
+ "u_1",
+ [sql`1`, sql`0`],
+ )).toBeDefined();
+ });
+});
+
+describe("getAccountReadStateSnapshot", () => {
+ it("keeps revision and rows aligned when a mutation races the snapshot", async () => {
+ const builders = [
+ { kind: "revision" },
+ { kind: "rows" },
+ ];
+ let selectIndex = 0;
+ let state = {
+ revision: 4,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m2",
+ lastReadAt: "2026-08-24T00:00:02.000Z",
+ lastReadSeq: 2,
+ }],
+ };
+ const db: any = {
+ select: vi.fn(() => {
+ const builder: any = builders[selectIndex++];
+ builder.from = vi.fn(() => builder);
+ builder.where = vi.fn(() => builder);
+ builder.limit = vi.fn(() => builder);
+ return builder;
+ }),
+ batch: vi.fn(async () => {
+ const captured = structuredClone(state);
+ state = {
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m3",
+ lastReadAt: "2026-08-24T00:00:03.000Z",
+ lastReadSeq: 3,
+ }],
+ };
+ return [
+ [{ revision: captured.revision }],
+ captured.readStates,
+ ];
+ }),
+ };
+
+ await expect(readStateQueries.getAccountReadStateSnapshot(db, "u1")).resolves.toEqual({
+ revision: 4,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m2",
+ lastReadAt: "2026-08-24T00:00:02.000Z",
+ lastReadSeq: 2,
+ }],
+ });
+ expect(db.batch).toHaveBeenCalledOnce();
+ expect(db.batch.mock.calls[0]![0]).toEqual(builders);
+ });
});
describe("markReadToMessageBuilder — channel branch", () => {
@@ -146,104 +212,82 @@ describe("markReadToMessageBuilder — DM is a channel", () => {
// return the count of channels that got a write (not the reachable-channel
// count).
-function makeMassMarkDbMock(opts: {
- memberChannelIds: string[];
- latestByChannel: Record<string, { id: string; createdAt: string } | undefined>;
- existingReadStateChannels: string[]; // channelIds that already have a row
-}) {
- const updates: Array<{ id: string; set: any }> = [];
+function makeMassMarkDbMock(revision = 7) {
const inserts: any[] = [];
-
- // Post-id-set convergence, `markAllServerChannelsRead` takes the visible
- // channel id set as an ARGUMENT (no member-channel select of its own). The
- // only select it now issues is the existing-read-state-rows lookup:
- // select({id, channelId}).from(communityReadState).where(...) → existing rows.
- // (`getLatestMessagesByChannelIds` is intercepted via vi.spyOn.)
-
+ const conflicts: any[] = [];
+ const deletes: any[] = [];
const db: any = {
- select: vi.fn(() => {
+ insert: vi.fn(() => {
const chain: any = {};
+ chain.values = vi.fn((value: any) => {
+ inserts.push(value);
+ return chain;
+ });
+ chain.onConflictDoUpdate = vi.fn((value: any) => {
+ conflicts.push(value);
+ return chain;
+ });
+ chain.select = vi.fn(() => chain);
+ chain.returning = vi.fn(() => chain);
+ return chain;
+ }),
+ select: vi.fn(() => {
+ const chain: any = { __snapshot: true };
chain.from = vi.fn(() => chain);
chain.innerJoin = vi.fn(() => chain);
- chain.leftJoin = vi.fn(() => chain);
- chain.groupBy = vi.fn(() => chain);
- chain.as = vi.fn(() => chain);
- chain.where = vi.fn(() =>
- Promise.resolve(
- opts.existingReadStateChannels.map((c, i) => ({
- id: `rs_${i}_${c}`,
- channelId: c,
- }))
- )
- );
+ chain.where = vi.fn(() => chain);
+ chain.limit = vi.fn(() => chain);
+ chain.then = (resolve: (value: unknown) => unknown) => resolve([{ revision }]);
return chain;
}),
- update: vi.fn(() => ({
- set: vi.fn((s: any) => ({
- where: vi.fn((w: any) => {
- // where clause is `and(eq(readState.id, u.id), lt(readState.lastReadAt, u.createdAt))`
- // — we can't inspect its structure without evaluating the SQL
- // fragment, but the mere presence of a non-null argument lets
- // downstream tests assert that a guard was passed at all.
- updates.push({ id: "unknown", set: s, where: w });
- return Promise.resolve();
- }),
- })),
- })),
- insert: vi.fn(() => ({
- values: vi.fn((v: any) => {
- inserts.push(v);
- return Promise.resolve();
- }),
+ delete: vi.fn((table: unknown) => {
+ const chain: any = { __delete: table };
+ chain.where = vi.fn((condition: unknown) => {
+ deletes.push({ table, condition });
+ return chain;
+ });
+ return chain;
+ }),
+ batch: vi.fn(async (statements: any[]) => statements.map((_statement, index) => {
+ if (index === 0) return [{ revision }];
+ if (index === statements.length - 1) return [{ revision }];
+ return [];
})),
- __updates: updates,
__inserts: inserts,
+ __conflicts: conflicts,
+ __deletes: deletes,
};
-
return db;
}
describe("markAllServerChannelsRead", () => {
it("returns 0 and does nothing when the user has no member channels", async () => {
- const db = makeMassMarkDbMock({
- memberChannelIds: [],
- latestByChannel: {},
- existingReadStateChannels: [],
- });
+ const db = makeMassMarkDbMock();
const messageModule = await import("../../src/db/queries/community/message");
const spy = vi.spyOn(messageModule, "getLatestMessagesByChannelIds").mockResolvedValue([]);
- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", []);
- expect(count).toBe(0);
- expect(db.__updates).toHaveLength(0);
+ const result = await readStateQueries.markAllServerChannelsRead(db, "u_1", []);
+ expect(result).toEqual({ count: 0, changed: false, revision: 7 });
expect(db.__inserts).toHaveLength(0);
+ expect(db.batch).not.toHaveBeenCalled();
spy.mockRestore();
});
it("returns 0 and skips writes when NONE of the member channels have messages", async () => {
- const db = makeMassMarkDbMock({
- memberChannelIds: ["c_a", "c_b"],
- latestByChannel: {},
- existingReadStateChannels: [],
- });
+ const db = makeMassMarkDbMock();
const messageModule = await import("../../src/db/queries/community/message");
// Every channel is empty — the batched helper returns nothing.
const spy = vi.spyOn(messageModule, "getLatestMessagesByChannelIds").mockResolvedValue([]);
- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b"]);
- expect(count).toBe(0);
- // The invariant: empty channels get no row.
- expect(db.__updates).toHaveLength(0);
+ const result = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b"]);
+ expect(result).toEqual({ count: 0, changed: false, revision: 7 });
expect(db.__inserts).toHaveLength(0);
+ expect(db.batch).not.toHaveBeenCalled();
spy.mockRestore();
});
it("returns the count of non-empty channels; inserts aligned rows for channels with no existing read state", async () => {
- const db = makeMassMarkDbMock({
- memberChannelIds: ["c_a", "c_b", "c_c_empty"],
- latestByChannel: {},
- existingReadStateChannels: [],
- });
+ const db = makeMassMarkDbMock(11);
const messageModule = await import("../../src/db/queries/community/message");
// c_a and c_b have messages; c_c_empty has none.
const spy = vi.spyOn(messageModule, "getLatestMessagesByChannelIds").mockResolvedValue([
@@ -251,12 +295,16 @@ describe("markAllServerChannelsRead", () => {
{ channelId: "c_b", id: "m_b_latest", createdAt: "2026-07-05T11:00:00Z", seq: 11 },
]);
- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b", "c_c_empty"]);
- expect(count).toBe(2);
- expect(db.__updates).toHaveLength(0);
- // One batched insert containing both rows.
- expect(db.__inserts).toHaveLength(1);
- const rows = db.__inserts[0] as Array<any>;
+ const result = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b", "c_c_empty"]);
+ expect(result).toEqual({
+ count: 2,
+ changed: true,
+ revision: 11,
+ });
+ expect(db.batch).toHaveBeenCalledTimes(1);
+ expect(db.batch.mock.calls[0]![0]).toHaveLength(4);
+ expect(db.__deletes).toHaveLength(0);
+ const rows = db.__inserts.filter((row: any) => row.channelId);
expect(rows).toHaveLength(2);
// The invariant per-row: lastReadAt === message.createdAt, lastReadMessageId === message.id.
const byChannel = Object.fromEntries(rows.map((r) => [r.channelId, r]));
@@ -277,32 +325,17 @@ describe("markAllServerChannelsRead", () => {
spy.mockRestore();
});
- it("updates existing rows in place, aligned to the latest message per channel", async () => {
- const db = makeMassMarkDbMock({
- memberChannelIds: ["c_a", "c_b"],
- latestByChannel: {},
- existingReadStateChannels: ["c_a", "c_b"],
- });
+ it("uses the same guarded upsert for existing rows and fresh rows", async () => {
+ const db = makeMassMarkDbMock();
const messageModule = await import("../../src/db/queries/community/message");
const spy = vi.spyOn(messageModule, "getLatestMessagesByChannelIds").mockResolvedValue([
{ channelId: "c_a", id: "m_a_new", createdAt: "2026-07-05T10:00:00Z", seq: 20 },
{ channelId: "c_b", id: "m_b_new", createdAt: "2026-07-05T11:00:00Z", seq: 21 },
]);
- const count = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b"]);
- expect(count).toBe(2);
- // Two UPDATEs, no INSERT.
- expect(db.__updates).toHaveLength(2);
- expect(db.__inserts).toHaveLength(0);
-
- // Each update's `set` carries an ALIGNED tuple — never `lastReadMessageId: null`.
- for (const u of db.__updates) {
- expect(u.set.lastReadMessageId).not.toBeNull();
- expect(typeof u.set.lastReadAt).toBe("string");
- expect(typeof u.set.lastReadMessageId).toBe("string");
- }
- // The two sets, combined, cover c_a's and c_b's aligned tuples in some order.
- const sets = db.__updates.map((u) => u.set);
+ const result = await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a", "c_b"]);
+ expect(result).toMatchObject({ count: 2, changed: true, revision: 7 });
+ const sets = db.__conflicts.slice(0, 2).map((conflict: any) => conflict.set);
const aTuple = sets.find((s) => s.lastReadMessageId === "m_a_new");
const bTuple = sets.find((s) => s.lastReadMessageId === "m_b_new");
expect(aTuple).toBeDefined();
@@ -314,27 +347,29 @@ describe("markAllServerChannelsRead", () => {
spy.mockRestore();
});
- it("each UPDATE carries a monotone guard in its WHERE so a stale row cannot be regressed", async () => {
- const db = makeMassMarkDbMock({
- memberChannelIds: ["c_a"],
- latestByChannel: {},
- existingReadStateChannels: ["c_a"],
- });
+ it("each upsert carries a seq monotone guard", async () => {
+ const db = makeMassMarkDbMock();
const messageModule = await import("../../src/db/queries/community/message");
const spy = vi.spyOn(messageModule, "getLatestMessagesByChannelIds").mockResolvedValue([
{ channelId: "c_a", id: "m_a_new", createdAt: "2026-07-05T10:00:00Z", seq: 20 },
]);
await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a"]);
- // A raw eq(id, ...) is a Drizzle SQL fragment; a guarded and(eq(...), lt(...))
- // is a distinct fragment. We can't evaluate them structurally without
- // spinning up SQLite, but the WHERE clause is definitely not undefined
- // AND (post-refactor) is now an `and(...)` compound rather than a bare
- // eq. Presence is the load-bearing bit — absence would silently allow
- // "mark all read" to regress a channel whose stale read-state row is
- // ahead of its current latest message.
- expect(db.__updates).toHaveLength(1);
- expect(db.__updates[0].where).toBeDefined();
+ expect(db.__conflicts[0].setWhere).toBeDefined();
+ expect(db.batch).toHaveBeenCalledTimes(1);
+ spy.mockRestore();
+ });
+
+ it("returns the current revision when the account has no DMs", async () => {
+ const db = makeMassMarkDbMock(13);
+ const dmModule = await import("../../src/db/queries/community/dm");
+ const spy = vi.spyOn(dmModule, "listDMs").mockResolvedValue([]);
+
+ await expect(readStateQueries.markAllDmsRead(db, "u_1")).resolves.toEqual({
+ count: 0,
+ changed: false,
+ revision: 13,
+ });
spy.mockRestore();
});
});
diff --git a/src/web/migrations/0090_community_read_state_revision.sql b/src/web/migrations/0090_community_read_state_revision.sql
new file mode 100644
index 000000000..81b94f2d8
--- /dev/null
+++ b/src/web/migrations/0090_community_read_state_revision.sql
@@ -0,0 +1,5 @@
+CREATE TABLE `community_read_state_revision` (
+ `user_id` text PRIMARY KEY NOT NULL,
+ `revision` integer DEFAULT 0 NOT NULL,
+ FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
+);
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts
index 4034fc768..f5bfd6d0e 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.test.ts
@@ -41,7 +41,8 @@ describe("owner bot channel notification settings", () => {
vi.clearAllMocks()
getBotOwnedBy.mockResolvedValue({ id: "bot_1", ownerUserId: "owner" })
requireMessageSurfaceAccess.mockResolvedValue({ ok: true, value: { surface: "dm" } })
- setChannelLevel.mockResolvedValue({ level: "mentions" })
+ setChannelLevel.mockResolvedValue({ setting: { level: "mentions" }, readStateRevision: null })
+ removeChannelOverride.mockResolvedValue({ setting: null, readStateRevision: null })
})
it("writes the owned bot identity after checking the bot's DM access", async () => {
@@ -50,7 +51,7 @@ describe("owner bot channel notification settings", () => {
expect(getBotOwnedBy).toHaveBeenCalledWith({}, "bot_1", "owner")
expect(requireMessageSurfaceAccess).toHaveBeenCalledWith({}, "dm_1", "bot_1")
expect(setChannelLevel).toHaveBeenCalledWith({}, {
- userId: "bot_1", channelId: "dm_1", level: "mentions",
+ userId: "bot_1", channelId: "dm_1", level: "mentions", actorKind: "bot",
})
})
@@ -73,6 +74,8 @@ describe("owner bot channel notification settings", () => {
const response = await DELETE(new NextRequest("http://local", { method: "DELETE" }), ctx)
expect(response.status).toBe(204)
expect(requireMessageSurfaceAccess).toHaveBeenCalledWith({}, "dm_1", "bot_1")
- expect(removeChannelOverride).toHaveBeenCalledWith({}, { userId: "bot_1", channelId: "dm_1" })
+ expect(removeChannelOverride).toHaveBeenCalledWith({}, {
+ userId: "bot_1", channelId: "dm_1", actorKind: "bot",
+ })
})
})
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts
index 386539a75..92b87b497 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/channel/[scopeId]/route.ts
@@ -34,12 +34,13 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
if (!body.level || !(NOTIFICATION_LEVEL_VALUES as readonly string[]).includes(body.level)) {
return writeError(`level must be one of: ${NOTIFICATION_LEVEL_VALUES.join(", ")}`, 400)
}
- const setting = await queries.communityNotificationSetting.setChannelLevel(auth.db, {
+ const result = await queries.communityNotificationSetting.setChannelLevel(auth.db, {
userId: auth.botId,
channelId: auth.channelId,
level: body.level,
+ actorKind: "bot",
})
- return writeJSON(setting)
+ return writeJSON(result.setting)
})
export const DELETE = withAuth(async (_req, ctx) => {
@@ -48,6 +49,7 @@ export const DELETE = withAuth(async (_req, ctx) => {
await queries.communityNotificationSetting.removeChannelOverride(auth.db, {
userId: auth.botId,
channelId: auth.channelId,
+ actorKind: "bot",
})
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts
index 4fed947e8..b3b7404c9 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.test.ts
@@ -38,7 +38,7 @@ describe("owner bot server notification settings", () => {
vi.clearAllMocks()
getBotOwnedBy.mockResolvedValue({ id: "bot_1", ownerUserId: "owner" })
requireServerMember.mockResolvedValue({ ok: true, value: { role: "member" } })
- setServerLevel.mockResolvedValue({ level: "nothing" })
+ setServerLevel.mockResolvedValue({ setting: { level: "nothing" }, readStateRevision: null })
})
it("checks bot membership and writes the bot user id", async () => {
@@ -46,7 +46,7 @@ describe("owner bot server notification settings", () => {
expect(response.status).toBe(200)
expect(requireServerMember).toHaveBeenCalledWith({}, "server_1", "bot_1")
expect(setServerLevel).toHaveBeenCalledWith({}, {
- userId: "bot_1", serverId: "server_1", level: "nothing",
+ userId: "bot_1", serverId: "server_1", level: "nothing", actorKind: "bot",
})
})
diff --git a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts
index a099a9c55..b4865254f 100644
--- a/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/notifications/server/[scopeId]/route.ts
@@ -34,10 +34,11 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
if (!body.level || !(NOTIFICATION_LEVEL_VALUES as readonly string[]).includes(body.level)) {
return writeError(`level must be one of: ${NOTIFICATION_LEVEL_VALUES.join(", ")}`, 400)
}
- const setting = await queries.communityNotificationSetting.setServerLevel(auth.db, {
+ const result = await queries.communityNotificationSetting.setServerLevel(auth.db, {
userId: auth.botId,
serverId: auth.serverId,
level: body.level,
+ actorKind: "bot",
})
- return writeJSON(setting)
+ return writeJSON(result.setting)
})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index e82a7ff57..f57a207a8 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
@@ -255,6 +255,7 @@ async function handleHumanSend(
const created = await createMessageWithThread({
db,
authorId: userId,
+ authorKind: "human",
parentChannelId: target.channelId,
serverId: target.serverId,
body: { content, mentionType: forumBody.mentionType },
@@ -294,6 +295,7 @@ async function handleHumanSend(
const result = await createCommunityMessage({
db,
authorId: userId,
+ authorKind: "human",
target,
body: raw as Record<string, unknown>,
source: "web",
@@ -353,6 +355,7 @@ async function handleBotSend(
const created = await createMessageWithThread({
db,
authorId: botUserId,
+ authorKind: "bot",
parentChannelId: channelId,
serverId: target.serverId,
body: { content: body.content.text },
@@ -423,6 +426,7 @@ async function handleBotSend(
const result = await createCommunityMessage({
db,
authorId: botUserId,
+ authorKind: "bot",
target,
body: { content: body.content.text, replyToId },
source: "cli",
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.test.ts b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
index 562dcf7a4..6ba916d9a 100644
--- a/src/web/src/app/api/community/channels/[id]/read/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/read/route.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
+import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
vi.mock("@opennextjs/cloudflare", () => ({
@@ -7,14 +7,23 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetChannel = vi.fn()
const mockGetChannelForMember = vi.fn()
+const mockGetDM = vi.fn()
+const mockGetDMPeer = vi.fn()
+const mockIsBlocked = vi.fn()
const mockGetMessage = vi.fn()
-const mockGetLatestMessage = vi.fn()
-const mockMarkReadToMessageBuilder = vi.fn()
+const mockCanonicalReadTargetExistsCondition = vi.fn()
+const mockMarkReadToExistingMessageBuilder = vi.fn()
+const mockReadStateAdvancesCondition = vi.fn()
+const mockAdvanceReadStateRevisionWhenAnyBuilder = vi.fn()
+const mockAccountReadStateRevisionBuilder = vi.fn()
+const mockUnreadChannelMentionThroughSeqCondition = vi.fn()
const mockMarkChannelMentionsReadBuilder = vi.fn()
const mockBatch = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
+const mockGetPrimaryDb = vi.fn(() => ({ batch: (...args: unknown[]) => mockBatch(...args) }))
vi.mock("@/lib/db", () => ({
- getDb: vi.fn(() => ({ batch: (...a: unknown[]) => mockBatch(...a) })),
+ getPrimaryDb: (...args: unknown[]) => mockGetPrimaryDb(...args),
}))
vi.mock("@alook/shared", async () => {
@@ -23,19 +32,35 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: {
communityChannel: {
- getChannel: (...a: unknown[]) => mockGetChannel(...a),
- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),
+ getChannel: (...args: unknown[]) => mockGetChannel(...args),
+ getChannelForMember: (...args: unknown[]) => mockGetChannelForMember(...args),
+ },
+ communityDm: {
+ getDM: (...args: unknown[]) => mockGetDM(...args),
+ getDMPeer: (...args: unknown[]) => mockGetDMPeer(...args),
+ },
+ communityFriendship: {
+ isBlocked: (...args: unknown[]) => mockIsBlocked(...args),
},
communityMessage: {
- getMessage: (...a: unknown[]) => mockGetMessage(...a),
- getLatestMessage: (...a: unknown[]) => mockGetLatestMessage(...a),
+ getMessage: (...args: unknown[]) => mockGetMessage(...args),
},
communityReadState: {
- markReadToMessageBuilder: (...a: unknown[]) => mockMarkReadToMessageBuilder(...a),
+ canonicalReadTargetExistsCondition: (...args: unknown[]) =>
+ mockCanonicalReadTargetExistsCondition(...args),
+ markReadToExistingMessageBuilder: (...args: unknown[]) =>
+ mockMarkReadToExistingMessageBuilder(...args),
+ readStateAdvancesCondition: (...args: unknown[]) => mockReadStateAdvancesCondition(...args),
+ advanceReadStateRevisionWhenAnyBuilder: (...args: unknown[]) =>
+ mockAdvanceReadStateRevisionWhenAnyBuilder(...args),
+ accountReadStateRevisionBuilder: (...args: unknown[]) =>
+ mockAccountReadStateRevisionBuilder(...args),
},
communityMention: {
- markChannelMentionsReadBuilder: (...a: unknown[]) =>
- mockMarkChannelMentionsReadBuilder(...a),
+ unreadChannelMentionThroughSeqCondition: (...args: unknown[]) =>
+ mockUnreadChannelMentionThroughSeqCondition(...args),
+ markChannelMentionsReadBuilder: (...args: unknown[]) =>
+ mockMarkChannelMentionsReadBuilder(...args),
},
},
}
@@ -48,12 +73,15 @@ vi.mock("@/lib/middleware/auth", () => ({
}),
}))
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => mockBroadcastToUserSafe(...args),
+}))
+
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 }),
+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),
}
})
@@ -62,214 +90,180 @@ import { PUT } from "./route"
function putReq(body?: unknown) {
return new NextRequest("http://localhost/api/community/channels/c1/read", {
method: "PUT",
- ...(body !== undefined ? { body: typeof body === "string" ? body : JSON.stringify(body) } : {}),
+ ...(body !== undefined
+ ? { body: typeof body === "string" ? body : JSON.stringify(body) }
+ : {}),
})
}
+function allow(type = "text") {
+ mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type })
+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type })
+}
+
describe("PUT /api/community/channels/[id]/read", () => {
beforeEach(() => {
vi.clearAllMocks()
- // Each builder returns an opaque token so the route body can pass it to
- // db.batch — the batch call is what we actually assert on.
- mockMarkReadToMessageBuilder.mockReturnValue({ __builder: "markReadToMessage" })
- mockMarkChannelMentionsReadBuilder.mockReturnValue({
- __builder: "markChannelMentionsRead",
- })
- mockBatch.mockResolvedValue(undefined)
+ mockCanonicalReadTargetExistsCondition.mockReturnValue({ __condition: "target" })
+ mockMarkReadToExistingMessageBuilder.mockReturnValue({ __builder: "mark" })
+ mockMarkChannelMentionsReadBuilder.mockReturnValue({ __builder: "mentions" })
+ mockReadStateAdvancesCondition.mockReturnValue({ __condition: "pointer" })
+ mockUnreadChannelMentionThroughSeqCondition.mockReturnValue({ __condition: "mention" })
+ mockAdvanceReadStateRevisionWhenAnyBuilder.mockReturnValue({ __builder: "revision" })
+ mockAccountReadStateRevisionBuilder.mockReturnValue({ __builder: "current" })
+ mockBatch.mockResolvedValue([[{ revision: 7 }], [], [], [{ revision: 7 }]])
+ mockBroadcastToUserSafe.mockResolvedValue(undefined)
+ mockGetDM.mockResolvedValue({ id: "c1", lastMessageAt: null, createdAt: "t" })
+ mockGetDMPeer.mockResolvedValue({ otherUserId: "u2" })
+ mockIsBlocked.mockResolvedValue(false)
})
- it("no-body call on non-empty channel: uses latest message and issues one batch with both builders", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetLatestMessage.mockResolvedValue({
- id: "m_latest",
- createdAt: "2026-07-05T10:00:00.000Z",
- })
-
- const res = await PUT(putReq(), { params: { id: "c1" } } as any)
- expect(res.status).toBe(200)
-
- // Builder invoked with the latest message tuple — that's the invariant.
- expect(mockMarkReadToMessageBuilder).toHaveBeenCalledWith(expect.anything(), {
- userId: "u1",
- channelId: "c1",
- message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z" },
- })
-
- // Exactly one batch call carrying both statements in order.
- expect(mockBatch).toHaveBeenCalledTimes(1)
- const batchArg = mockBatch.mock.calls[0]![0]
- expect(Array.isArray(batchArg)).toBe(true)
- expect(batchArg).toHaveLength(2)
- expect(batchArg[0]).toEqual({ __builder: "markReadToMessage" })
- expect(batchArg[1]).toEqual({ __builder: "markChannelMentionsRead" })
- })
+ it.each(["text", "forum", "thread", "dm"])(
+ "uses the same exact-target cursor path for %s channels",
+ async (type) => {
+ allow(type)
+ mockGetMessage.mockResolvedValue({
+ id: "m42",
+ channelId: "c1",
+ createdAt: "2026-08-24T01:02:03.000Z",
+ seq: 42,
+ })
+
+ const res = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
+
+ expect(res.status).toBe(200)
+ expect(mockGetMessage).toHaveBeenCalledWith(expect.anything(), "m42")
+ const targetGuard = { __condition: "target" }
+ expect(mockCanonicalReadTargetExistsCondition).toHaveBeenCalledWith(expect.anything(), {
+ id: "m42",
+ channelId: "c1",
+ createdAt: "2026-08-24T01:02:03.000Z",
+ seq: 42,
+ })
+ expect(mockReadStateAdvancesCondition).toHaveBeenCalledWith(expect.anything(), {
+ userId: "u1",
+ channelId: "c1",
+ targetSeq: 42,
+ }, targetGuard)
+ expect(mockUnreadChannelMentionThroughSeqCondition).toHaveBeenCalledWith(
+ expect.anything(), "u1", "c1", 42, targetGuard,
+ )
+ expect(mockMarkReadToExistingMessageBuilder).toHaveBeenCalledWith(expect.anything(), {
+ userId: "u1",
+ channelId: "c1",
+ message: {
+ id: "m42",
+ channelId: "c1",
+ createdAt: "2026-08-24T01:02:03.000Z",
+ seq: 42,
+ },
+ })
+ expect(mockMarkChannelMentionsReadBuilder).toHaveBeenCalledWith(
+ expect.anything(), "u1", "c1", 42, targetGuard,
+ )
+ expect(mockBatch.mock.calls[0]![0]).toEqual([
+ { __builder: "revision" },
+ { __builder: "mark" },
+ { __builder: "mentions" },
+ { __builder: "current" },
+ ])
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledTimes(1)
+ await expect(res.json()).resolves.toEqual({ changed: true, targetSeq: 42, revision: 7 })
+ },
+ )
- it("no-body call on EMPTY channel: no writes at all, returns 200 { ok: true }", async () => {
- // This is the invariant's most load-bearing consequence: mass mark-read
- // on an empty channel writes nothing rather than inserting a
- // lastReadMessageId=null row.
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetLatestMessage.mockResolvedValue(null)
+ it("returns current revision with no frame for an equivalent no-op", async () => {
+ allow()
+ mockGetMessage.mockResolvedValue({ id: "m42", channelId: "c1", createdAt: "t", seq: 42 })
+ mockBatch.mockResolvedValue([[], [], [], [{ revision: 9 }]])
- const res = await PUT(putReq(), { params: { id: "c1" } } as any)
- expect(res.status).toBe(200)
- expect(await res.json()).toEqual({ ok: true })
+ const res = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
- expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()
- expect(mockMarkChannelMentionsReadBuilder).not.toHaveBeenCalled()
- expect(mockBatch).not.toHaveBeenCalled()
+ await expect(res.json()).resolves.toEqual({ changed: false, targetSeq: 42, revision: 9 })
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
- it("propagates a batch failure so callers see the error (all writes roll back)", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetLatestMessage.mockResolvedValue({
- id: "m_latest",
- createdAt: "2026-07-05T10:00:00.000Z",
- })
- // D1 batches are atomic: if the batch rejects, the whole transaction
- // rolls back. We verify the route surfaces that failure rather than
- // silently returning 200.
- mockBatch.mockRejectedValue(new Error("d1 batch failed"))
+ it("returns no effect and emits no hint when the in-batch target guard loses a delete race", async () => {
+ allow()
+ mockGetMessage.mockResolvedValue({ id: "m42", channelId: "c1", createdAt: "t", seq: 42 })
+ mockBatch.mockResolvedValue([[], [], [], [{ revision: 9 }]])
- await expect(PUT(putReq(), { params: { id: "c1" } } as any)).rejects.toThrow(
- "d1 batch failed"
- )
- expect(mockBatch).toHaveBeenCalledTimes(1)
- })
+ const res = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
- it("retries a transient BUSY from the atomic batch with the same monotonic target", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetLatestMessage.mockResolvedValue({
- id: "m_latest",
- createdAt: "2026-07-05T10:00:00.000Z",
- seq: 42,
- })
- mockBatch
- .mockRejectedValueOnce(new Error("SQLITE_BUSY: database is locked"))
- .mockResolvedValueOnce(undefined)
-
- const res = await PUT(putReq(), { params: { id: "c1" } } as any)
-
- expect(res.status).toBe(200)
- expect(mockBatch).toHaveBeenCalledTimes(2)
- expect(mockMarkReadToMessageBuilder).toHaveBeenNthCalledWith(1, expect.anything(), {
- userId: "u1",
- channelId: "c1",
- message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z", seq: 42 },
- })
- expect(mockMarkReadToMessageBuilder).toHaveBeenNthCalledWith(2, expect.anything(), {
- userId: "u1",
- channelId: "c1",
- message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z", seq: 42 },
- })
+ await expect(res.json()).resolves.toEqual({ changed: false, targetSeq: 42, revision: 9 })
+ expect(mockCanonicalReadTargetExistsCondition).toHaveBeenCalledOnce()
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
- it("returns 400 when the channel id is missing", async () => {
- const res = await PUT(putReq(), { params: {} } as any)
+ it.each([
+ ["omitted", undefined],
+ ["empty", ""],
+ ["malformed", "{"],
+ ["object without target", {}],
+ ["alternative target key", { targetMessageId: "m42" }],
+ ["additional key", { lastReadMessageId: "m42", extra: true }],
+ ["empty target", { lastReadMessageId: "" }],
+ ["non-string target", { lastReadMessageId: 42 }],
+ ["null", null],
+ ["array", [{ lastReadMessageId: "m42" }]],
+ ])("rejects %s body without reading latest", async (_label, body) => {
+ allow()
+
+ const res = await PUT(putReq(body), { params: { id: "c1" } } as any)
+
expect(res.status).toBe(400)
- expect(mockGetChannel).not.toHaveBeenCalled()
- expect(mockGetChannelForMember).not.toHaveBeenCalled()
+ expect(mockGetMessage).not.toHaveBeenCalled()
expect(mockBatch).not.toHaveBeenCalled()
})
- it("returns 404 when the channel does not exist", async () => {
- mockGetChannel.mockResolvedValue(null)
-
- const res = await PUT(putReq(), { params: { id: "c1" } } as any)
+ it("returns 404 for an unknown target", async () => {
+ allow()
+ mockGetMessage.mockResolvedValue(null)
+ const res = await PUT(putReq({ lastReadMessageId: "missing" }), { params: { id: "c1" } } as any)
expect(res.status).toBe(404)
- expect(mockGetChannelForMember).not.toHaveBeenCalled()
- expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()
- expect(mockMarkChannelMentionsReadBuilder).not.toHaveBeenCalled()
expect(mockBatch).not.toHaveBeenCalled()
})
- it("returns 403 when the channel exists but the caller is not a member", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- // requireChannelMember short-circuits to 403 when the member/channel join is empty.
- mockGetChannelForMember.mockResolvedValue(null)
+ it("returns 400 for a target in another channel", async () => {
+ allow()
+ mockGetMessage.mockResolvedValue({ id: "m42", channelId: "other", createdAt: "t", seq: 42 })
+ const res = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
+ expect(res.status).toBe(400)
+ expect(mockBatch).not.toHaveBeenCalled()
+ })
+
+ it("does not disclose an existing target in an inaccessible channel", async () => {
+ mockGetChannel
+ .mockResolvedValueOnce({ id: "c1", serverId: "s1", type: "text" })
+ .mockResolvedValueOnce(null)
+ mockGetChannelForMember
+ .mockResolvedValueOnce({ id: "c1", serverId: "s1", type: "text" })
+ mockGetMessage.mockResolvedValue({ id: "m42", channelId: "private", createdAt: "t", seq: 42 })
- const res = await PUT(putReq(), { params: { id: "c1" } } as any)
- expect(res.status).toBe(403)
- expect(mockMarkReadToMessageBuilder).not.toHaveBeenCalled()
- expect(mockMarkChannelMentionsReadBuilder).not.toHaveBeenCalled()
+ const res = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
+
+ expect(res.status).toBe(404)
expect(mockBatch).not.toHaveBeenCalled()
})
- // ── #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" })
- mockGetMessage.mockResolvedValue({
- id: "m_42",
- channelId: "c1",
- createdAt: "2026-07-01T12:00:00.000Z",
- })
+ it("preserves unknown-channel 404 and known-nonmember 403 before target lookup", async () => {
+ mockGetChannel.mockResolvedValueOnce(null)
+ const missing = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
+ expect(missing.status).toBe(404)
- 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
- // the whole point of the progressive watermark.
- expect(mockMarkReadToMessageBuilder).toHaveBeenCalledWith(expect.anything(), {
- userId: "u1",
- channelId: "c1",
- message: { id: "m_42", createdAt: "2026-07-01T12:00:00.000Z" },
- })
- // Body path never consults getLatestMessage.
- expect(mockGetLatestMessage).not.toHaveBeenCalled()
- })
-
- it("rejects with 400 when the message belongs to a different channel", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- // Scope-violation: the message is real but lives in c_other.
- mockGetMessage.mockResolvedValue({
- id: "m_42",
- channelId: "c_other",
- createdAt: "2026-07-01T12:00:00.000Z",
- })
+ mockGetChannel.mockResolvedValueOnce({ id: "c1", serverId: "s1", type: "forum" })
+ mockGetChannelForMember.mockResolvedValueOnce(null)
+ const forbidden = await PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any)
+ expect(forbidden.status).toBe(403)
+ expect(mockGetMessage).not.toHaveBeenCalled()
+ })
- 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()
- })
-
- it("returns 404 when the message id doesn't exist at all", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetMessage.mockResolvedValue(null)
-
- 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()
- })
-
- it("empty body falls back to latest-message no-body path", async () => {
- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })
- mockGetLatestMessage.mockResolvedValue({
- id: "m_latest",
- createdAt: "2026-07-05T10:00:00.000Z",
- })
+ it("surfaces an atomic batch failure", async () => {
+ allow()
+ mockGetMessage.mockResolvedValue({ id: "m42", channelId: "c1", createdAt: "t", seq: 42 })
+ mockBatch.mockRejectedValue(new Error("d1 batch failed"))
- // 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.
- expect(mockGetMessage).not.toHaveBeenCalled()
- // Builder aligned to the LATEST message, not "now".
- expect(mockMarkReadToMessageBuilder).toHaveBeenCalledWith(expect.anything(), {
- userId: "u1",
- channelId: "c1",
- message: { id: "m_latest", createdAt: "2026-07-05T10:00:00.000Z" },
- })
- })
+ await expect(PUT(putReq({ lastReadMessageId: "m42" }), { params: { id: "c1" } } as any))
+ .rejects.toThrow("d1 batch failed")
})
})
diff --git a/src/web/src/app/api/community/channels/[id]/read/route.ts b/src/web/src/app/api/community/channels/[id]/read/route.ts
index f1c77fc59..cd6d05c05 100644
--- a/src/web/src/app/api/community/channels/[id]/read/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/read/route.ts
@@ -1,37 +1,24 @@
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, withD1Retry } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { queries, WS_EVENTS, withD1Retry } from "@alook/shared"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
/**
* PUT /api/community/channels/:id/read
*
- * Marks the channel read for the current viewer. Two shapes:
- * - Body omitted or `{}` → mass mark-read. Server picks the latest message
- * in the channel and writes both `lastReadAt = msg.createdAt` and
- * `lastReadMessageId = msg.id`. Empty channels are a no-op — no row
- * written — because the read-state invariant forbids
- * `lastReadMessageId = null` rows.
- * - 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.
+ * The sole accepted body is the strict object `{ lastReadMessageId: string }`.
+ * Every channel type uses the same ordinary `(userId, channelId)` cursor.
+ * The server re-reads the canonical target row, rejects an unknown id (404)
+ * or a row from another channel (400), and never falls back to the latest row.
*/
export const PUT = withAuth(async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
// Unified id-in-path access gate: preserves the 404-vs-403 human split
// (unknown → 404, known non-member → 403) AND, for a DM id, runs the DM block
@@ -43,63 +30,96 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
{ route: "community/channel-read:access" }
)
if (!auth.ok) return writeError(auth.error, auth.status)
-
- // Parse the body — best-effort. An empty body is legal (mass mark-read).
- let lastReadMessageId: string | undefined
+ let body: unknown
try {
- // 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 { lastReadMessageId?: unknown }
- if (typeof body?.lastReadMessageId === "string" && body.lastReadMessageId.length > 0) {
- lastReadMessageId = body.lastReadMessageId
- }
- }
+ body = await req.json()
} catch {
- // Malformed JSON — fall through with `lastReadMessageId` unset. The mass
- // mark-read semantics are the safe fallback.
+ return writeError("invalid read target", 400)
}
+ if (
+ body === null
+ || typeof body !== "object"
+ || Array.isArray(body)
+ || Object.keys(body).length !== 1
+ || !("lastReadMessageId" in body)
+ || typeof body.lastReadMessageId !== "string"
+ || body.lastReadMessageId.length === 0
+ ) return writeError("invalid read target", 400)
+ const lastReadMessageId = body.lastReadMessageId
- // 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; seq: number } | null
- if (lastReadMessageId) {
- const msg = await withD1Retry(
- () => queries.communityMessage.getMessage(db, lastReadMessageId),
- { route: "community/channel-read:message" }
- )
- if (!msg) return writeError("message not found", 404)
- // Scope check — a message from another channel MUST NOT advance THIS
- // channel's watermark.
- if (msg.channelId !== channelId) {
- return writeError("message not in channel", 400)
- }
- target = { id: msg.id, createdAt: msg.createdAt, seq: msg.seq }
- } else {
- target = await withD1Retry(
- () => queries.communityMessage.getLatestMessage(db, { channelId }),
- { route: "community/channel-read:latest" }
+ const message = await withD1Retry(
+ () => queries.communityMessage.getMessage(db, lastReadMessageId),
+ { route: "community/channel-read:message" }
+ )
+ if (!message) return writeError("message not found", 404)
+ if (message.channelId !== channelId) {
+ const targetAccess = await withD1Retry(
+ () => requireMessageSurfaceAccess(db, message.channelId, ctx.userId),
+ { route: "community/channel-read:target-access" },
)
- // Empty channel: no row can be written under the invariant. Nothing to
- // clear either (mentions/for-you require messages to exist first), so
- // short-circuit with a successful no-op.
- if (!target) return writeJSON({ ok: true })
+ if (!targetAccess.ok) return writeError(targetAccess.error, targetAccess.status)
+ return writeError("message not in channel", 400)
+ }
+ const target = {
+ id: message.id,
+ channelId: message.channelId,
+ createdAt: message.createdAt,
+ seq: message.seq,
}
// Fire both writes in one D1 batch so partial failure can't leave the
// inbox inconsistent (mark-read succeeded but the mention clear didn't, or
// vice versa). D1 batches are atomic per SQLite guarantees.
- await withD1Retry(
+ const canonicalTargetExists = queries.communityReadState.canonicalReadTargetExistsCondition(
+ db,
+ target,
+ )
+ const pointerAdvances = queries.communityReadState.readStateAdvancesCondition(db, {
+ userId: ctx.userId,
+ channelId,
+ targetSeq: target.seq,
+ }, canonicalTargetExists)
+ const eligibleMentionChanges = queries.communityMention.unreadChannelMentionThroughSeqCondition(
+ db,
+ ctx.userId,
+ channelId,
+ target.seq,
+ canonicalTargetExists,
+ )
+ const results = await withD1Retry(
() => db.batch([
- queries.communityReadState.markReadToMessageBuilder(db, {
+ queries.communityReadState.advanceReadStateRevisionWhenAnyBuilder(
+ db,
+ ctx.userId,
+ [pointerAdvances, eligibleMentionChanges],
+ ),
+ queries.communityReadState.markReadToExistingMessageBuilder(db, {
userId: ctx.userId,
channelId,
message: target,
}),
- queries.communityMention.markChannelMentionsReadBuilder(db, ctx.userId, channelId),
+ queries.communityMention.markChannelMentionsReadBuilder(
+ db,
+ ctx.userId,
+ channelId,
+ target.seq,
+ canonicalTargetExists,
+ ),
+ queries.communityReadState.accountReadStateRevisionBuilder(db, ctx.userId),
]),
{ route: "community/channel-read:commit" }
)
- return writeJSON({ ok: true })
+ const changed = (results[0] as Array<{ revision: number }>).length > 0
+ const revision = (results[3] as Array<{ revision: number }> | undefined)?.[0]?.revision ?? 0
+
+ if (changed) {
+ await broadcastToUserSafe(ctx.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision,
+ inboxChanged: true,
+ })
+ }
+
+ return writeJSON({ changed, targetSeq: target.seq, revision })
})
diff --git a/src/web/src/app/api/community/channels/[id]/route.test.ts b/src/web/src/app/api/community/channels/[id]/route.test.ts
index 34c1dcc2d..6bb963cba 100644
--- a/src/web/src/app/api/community/channels/[id]/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.test.ts
@@ -21,7 +21,7 @@ const mockFanOutToChannel = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
const mockScheduleMediaCleanup = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -360,7 +360,7 @@ describe("DELETE /channels/[id]", () => {
env: { DB: {}, COMMUNITY_MEDIA: { delete: vi.fn() } },
ctx: { waitUntil: mockWaitUntil },
})
- mockDeleteChannelWithMedia.mockResolvedValue({ deleted: true, mediaKeys: [] })
+ mockDeleteChannelWithMedia.mockResolvedValue({ deleted: true, mediaKeys: [], readStateRevisions: [] })
mockIsChannelPrivate.mockResolvedValue(false)
mockGetChannelType.mockResolvedValue("forum")
})
@@ -397,7 +397,7 @@ describe("DELETE /channels/[id]", () => {
it("keeps the winner 204 and fanout when waitUntil throws synchronously", async () => {
mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))
- mockDeleteChannelWithMedia.mockResolvedValue({ deleted: true, mediaKeys: ["original"] })
+ mockDeleteChannelWithMedia.mockResolvedValue({ deleted: true, mediaKeys: ["original"], readStateRevisions: [] })
mockWaitUntil.mockImplementationOnce(() => {
throw new TypeError("secret registration detail")
})
@@ -466,7 +466,7 @@ describe("DELETE /channels/[id]", () => {
mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))
mockDeleteChannelWithMedia.mockImplementation(async () => {
order.push("delete")
- return { deleted: true, mediaKeys: ["original", "thumbnail"] }
+ return { deleted: true, mediaKeys: ["original", "thumbnail"], readStateRevisions: [] }
})
mockScheduleMediaCleanup.mockImplementation(() => order.push("cleanup"))
mockFanOutToServerMembers.mockImplementation(async () => {
@@ -492,7 +492,7 @@ describe("DELETE /channels/[id]", () => {
it("returns 404 and never schedules or broadcasts when the D1 delete loses", async () => {
mockResolveChannelAccessContext.mockResolvedValue(accessCtx({ role: "admin", canManage: true }))
- mockDeleteChannelWithMedia.mockResolvedValue({ deleted: false, mediaKeys: [] })
+ mockDeleteChannelWithMedia.mockResolvedValue({ deleted: false, mediaKeys: [], readStateRevisions: [] })
const res = await DELETE(delReq(), ctx)
diff --git a/src/web/src/app/api/community/channels/[id]/route.ts b/src/web/src/app/api/community/channels/[id]/route.ts
index 00e3b733d..f6d07cf46 100644
--- a/src/web/src/app/api/community/channels/[id]/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/route.ts
@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import {
queries,
canManageServer,
@@ -161,7 +161,7 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const access = await requireChannelAccess(db, channelId, ctx.userId)
if (!access.ok) return writeError(access.error, access.status)
const channel = access.value.channel
@@ -197,6 +197,12 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {
})
if (!result.deleted) return writeError("channel not found", 404)
+ await Promise.all(result.readStateRevisions.map((revision) => broadcastToUserSafe(revision.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: revision.revision,
+ inboxChanged: true,
+ })))
+
if (result.mediaKeys.length > 0) {
scheduleCommunityMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {
keys: result.mediaKeys,
diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.ts
index 004f6f111..1c31ade25 100644
--- a/src/web/src/app/api/community/messages/[id]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts
@@ -38,7 +38,7 @@ const mockFanOutToChannel = vi.fn()
const mockFanOutToServerMembers = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }))
vi.mock("@/lib/community/resolve-ref", () => ({
resolveTargetForMember: (...a: unknown[]) => mockResolveTargetForMember(...a),
@@ -512,6 +512,7 @@ describe("DELETE /api/community/messages/[id]", () => {
mockDeleteForumPost.mockResolvedValue({
deleted: true,
mediaKeys: ["opener/original", "opener/thumb"],
+ readStateRevisions: [],
})
mockFanOutToServerMembers.mockResolvedValue(undefined)
mockBroadcastToUserSafe.mockResolvedValue(undefined)
@@ -606,7 +607,7 @@ describe("DELETE /api/community/messages/[id]", () => {
})
it("treats a concurrently-resolved losing batch as idempotent without duplicate side effects", async () => {
- mockDeleteForumPost.mockResolvedValue({ deleted: false, mediaKeys: [] })
+ mockDeleteForumPost.mockResolvedValue({ deleted: false, mediaKeys: [], readStateRevisions: [] })
const res = await DELETE(deleteReq(), { params: { id: "opener_1" } } as any)
@@ -616,6 +617,21 @@ describe("DELETE /api/community/messages/[id]", () => {
expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
+ it.each(["parent statement", "child statement"])(
+ "emits no read-state or channel hint when the %s fails and the D1 batch rolls back",
+ async (failureScope) => {
+ mockDeleteForumPost.mockRejectedValue(new Error(`forced ${failureScope} failure`))
+
+ await expect(DELETE(deleteReq(), { params: { id: "opener_1" } } as any))
+ .rejects.toThrow(`forced ${failureScope} failure`)
+
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
+ expect(mockFanOutToServerMembers).not.toHaveBeenCalled()
+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()
+ expect(cloudflareMocks.mediaDelete).not.toHaveBeenCalled()
+ },
+ )
+
it("returns 404 for a missing opener and 409 for a forum message without a unique child", async () => {
mockGetMessage.mockResolvedValueOnce(null)
expect((await DELETE(deleteReq(), { params: { id: "missing" } } as any)).status).toBe(404)
diff --git a/src/web/src/app/api/community/messages/[id]/route.ts b/src/web/src/app/api/community/messages/[id]/route.ts
index 4a51bffda..69df08c7f 100644
--- a/src/web/src/app/api/community/messages/[id]/route.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.ts
@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import { canManageServer, queries, MAX_MESSAGE_CONTENT_LENGTH, WS_EVENTS } from "@alook/shared"
import {
requireChannelMember,
@@ -134,7 +134,7 @@ export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {
const openerId = ctx.params?.id
if (!openerId || openerId === REF_PLACEHOLDER_ID) return writeError("missing message id", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const opener = await queries.communityMessage.getMessage(db, openerId)
if (!opener) return writeError("message not found", 404)
@@ -183,6 +183,11 @@ export const DELETE = withCommunityActor(async (_req: NextRequest, ctx) => {
})
if (result.deleted) {
+ await Promise.all(result.readStateRevisions.map((revision) => broadcastToUserSafe(revision.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: revision.revision,
+ inboxChanged: true,
+ })))
if (result.mediaKeys.length > 0) {
const { ctx: executionContext } = await getCloudflareContext({ async: true })
scheduleForumPostMediaCleanup(ctx.env.COMMUNITY_MEDIA, executionContext, {
diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.ts
index 5e479a3ed..982eae4ee 100644
--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts
@@ -102,6 +102,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const created = await createCommunityMessage({
db,
authorId: botId,
+ authorKind: "bot",
target: { kind: "dm", channelId: dm.id, otherUserId: ownerId },
body: { content: `${requesterLabel} wants to add me to a server. Approve?` },
skipMentions: true,
diff --git a/src/web/src/app/api/community/servers/[id]/route.test.ts b/src/web/src/app/api/community/servers/[id]/route.test.ts
index c11572579..dee7a209c 100644
--- a/src/web/src/app/api/community/servers/[id]/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.test.ts
@@ -17,6 +17,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
vi.mock("@/lib/db", () => ({
getDb: vi.fn(() => ({})),
+ getPrimaryDb: vi.fn(() => ({})),
}))
vi.mock("@alook/shared", async () => {
@@ -135,7 +136,7 @@ describe("DELETE /api/community/servers/[id]", () => {
})
mockGetMember.mockResolvedValue({ id: "mem_1", userId: "u1", role: "owner" })
mockListMemberUserIds.mockResolvedValue(["u1", "u2"])
- mockDeleteServerWithMedia.mockResolvedValue({ deleted: true, mediaKeys: [], iconKey: null })
+ mockDeleteServerWithMedia.mockResolvedValue({ deleted: true, mediaKeys: [], iconKey: null, readStateRevisions: [] })
mockFanOutToUsers.mockResolvedValue(undefined)
})
@@ -147,7 +148,7 @@ describe("DELETE /api/community/servers/[id]", () => {
})
mockDeleteServerWithMedia.mockImplementation(async () => {
order.push("delete")
- return { deleted: true, mediaKeys: [], iconKey: null }
+ return { deleted: true, mediaKeys: [], iconKey: null, readStateRevisions: [] }
})
mockFanOutToUsers.mockImplementation(async () => {
order.push("fanout")
@@ -178,6 +179,7 @@ describe("DELETE /api/community/servers/[id]", () => {
deleted: true,
mediaKeys: ["channel/s1/a"],
iconKey: null,
+ readStateRevisions: [],
})
mockWaitUntil.mockImplementationOnce(() => {
throw new TypeError("secret registration detail")
@@ -198,6 +200,7 @@ describe("DELETE /api/community/servers/[id]", () => {
deleted: true,
mediaKeys: ["channel/s1/a", "channel/s1/a.thumbnail.jpg"],
iconKey: "server-icon/s1/icon-a",
+ readStateRevisions: [],
}
})
mockScheduleMediaCleanup.mockImplementation(() => order.push("cleanup"))
@@ -229,6 +232,7 @@ describe("DELETE /api/community/servers/[id]", () => {
deleted: true,
mediaKeys: ["channel/s1/a"],
iconKey: "server-icon/other/icon-a",
+ readStateRevisions: [],
})
const res = await DELETE(deleteReq(), ctx)
@@ -242,7 +246,7 @@ describe("DELETE /api/community/servers/[id]", () => {
})
it("returns 404 without cleanup or fanout when the owner-scoped delete loses", async () => {
- mockDeleteServerWithMedia.mockResolvedValue({ deleted: false, mediaKeys: [], iconKey: null })
+ mockDeleteServerWithMedia.mockResolvedValue({ deleted: false, mediaKeys: [], iconKey: null, readStateRevisions: [] })
const res = await DELETE(deleteReq(), ctx)
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index 8123e9b29..b015a997d 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -2,7 +2,7 @@ import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import {
queries,
isServerOwner,
@@ -11,7 +11,7 @@ import {
WS_EVENTS,
slugify,
} from "@alook/shared"
-import { fanOutToServerMembers, fanOutToUsers } from "@/lib/community/fanout"
+import { broadcastToUserSafe, fanOutToServerMembers, fanOutToUsers } from "@/lib/community/fanout"
import { requireServerAdmin } from "@/lib/community/permissions"
import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cleanup"
import { isOwnedServerIconKey } from "@/lib/community/storage"
@@ -77,7 +77,7 @@ export const DELETE = withAuth(async (_req, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const member = await queries.communityMember.getMember(db, serverId, ctx.userId)
if (!member) return writeError("not a member of this server", 403)
@@ -100,6 +100,12 @@ export const DELETE = withAuth(async (_req, ctx) => {
})
if (!result.deleted) return writeError("server not found", 404)
+ await Promise.all(result.readStateRevisions.map((revision) => broadcastToUserSafe(revision.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: revision.revision,
+ inboxChanged: true,
+ })))
+
const mediaKeys = [
...result.mediaKeys,
...(result.iconKey && isOwnedServerIconKey(result.iconKey, serverId)
diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
index 4376868c6..b774274a3 100644
--- a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts
@@ -4,6 +4,7 @@ import { NextRequest } from "next/server"
const mockGetMember = vi.fn()
const mockListVisibleChannelIds = vi.fn()
const mockListEligibleUnreadChannels = vi.fn()
+const mockListUnreadForumOpeners = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
vi.mock("@alook/shared", async () => {
@@ -20,6 +21,7 @@ vi.mock("@alook/shared", async () => {
communityInbox: {
...actual.queries.communityInbox,
listEligibleUnreadChannels: (...args: unknown[]) => mockListEligibleUnreadChannels(...args),
+ listUnreadForumOpeners: (...args: unknown[]) => mockListUnreadForumOpeners(...args),
},
},
}
@@ -44,6 +46,7 @@ describe("GET /api/community/servers/[id]/unreads", () => {
{ serverId: "server_1", channelId: "channel_2", parentChannelId: "channel_1" },
{ serverId: "server_2", channelId: "other_1" },
])
+ mockListUnreadForumOpeners.mockResolvedValue([])
})
it("returns the complete viewer-visible unread id set scoped to the server", async () => {
@@ -71,6 +74,25 @@ describe("GET /api/community/servers/[id]/unreads", () => {
expect(mockListEligibleUnreadChannels).toHaveBeenCalledOnce()
})
+ it("keeps a forum parent only while its hybrid projection has an unread opener", async () => {
+ mockListEligibleUnreadChannels.mockResolvedValue([
+ { serverId: "server_1", channelId: "forum_1", parentChannelId: null, type: "forum" },
+ ])
+ mockListUnreadForumOpeners.mockResolvedValue([{ forumChannelId: "forum_1" }])
+
+ const response = await GET(
+ new NextRequest("http://localhost/api/community/servers/server_1/unreads"),
+ { params: { id: "server_1" } } as never,
+ )
+
+ expect(await response.json()).toMatchObject({ channelIds: ["forum_1"] })
+ expect(mockListUnreadForumOpeners).toHaveBeenCalledWith(
+ expect.anything(),
+ "user_1",
+ ["forum_1"],
+ )
+ })
+
it("fails closed when the viewer is not a server member", async () => {
mockGetMember.mockResolvedValue(null)
const response = await GET(
diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.ts
index 32543a549..7c5411057 100644
--- a/src/web/src/app/api/community/servers/[id]/unreads/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/unreads/route.ts
@@ -18,15 +18,33 @@ export const GET = withAuth(async (_req, ctx) => {
const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)
const unread = (await queries.communityInbox.listEligibleUnreadChannels(db, ctx.userId, visibleChannelIds))
.filter((row) => row.serverId === serverId)
+ const forumParentIds = unread
+ .filter((row) => !row.parentChannelId && row.type === "forum")
+ .map((row) => row.channelId)
+ const unreadOpeners = await queries.communityInbox.listUnreadForumOpeners(
+ db,
+ ctx.userId,
+ forumParentIds,
+ )
+ const forumParentsWithUnread = new Set([
+ ...unreadOpeners.map((row) => row.forumChannelId),
+ ...unread.flatMap((row) => row.parentChannelId ? [row.parentChannelId] : []),
+ ])
+ const projectedUnread = unread.filter(
+ (row) =>
+ row.parentChannelId ||
+ row.type !== "forum" ||
+ forumParentsWithUnread.has(row.channelId),
+ )
return {
- channelIds: unread.map((row) => row.channelId),
+ channelIds: projectedUnread.map((row) => row.channelId),
// Preserve the canonical child → parent attribution. The client needs
// this even when a participating forum post is outside the sidebar's
// 72h / top-five projection, otherwise a cold boot loses its unread
// signal entirely. `listEligibleUnreadChannels` has already applied
// access, archive, participant, read-cursor, and policy filtering;
// the client narrows them to parents whose canonical type is `forum`.
- childChannels: unread.flatMap((row) => row.parentChannelId
+ childChannels: projectedUnread.flatMap((row) => row.parentChannelId
? [{ id: row.channelId, parentChannelId: row.parentChannelId }]
: []),
}
diff --git a/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.test.ts
new file mode 100644
index 000000000..9dc97c957
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ markAll: vi.fn(),
+ broadcast: vi.fn(),
+ getPrimaryDb: vi.fn(() => ({ kind: "primary-db" })),
+}))
+
+vi.mock("@/lib/db", () => ({
+ getPrimaryDb: (...args: unknown[]) => mocks.getPrimaryDb(...args),
+}))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityReadState: {
+ ...actual.queries.communityReadState,
+ markAllDmsRead: (...args: unknown[]) => mocks.markAll(...args),
+ },
+ },
+ }
+})
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => mocks.broadcast(...args),
+}))
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => (req: any) => handler(req, {
+ env: { DB: {} },
+ userId: "u1",
+ email: "[email protected]",
+ }),
+}))
+vi.mock("@/lib/middleware/helpers", () => ({
+ writeJSON: (data: unknown) => Response.json(data),
+}))
+
+import { POST } from "./route"
+
+describe("POST /api/community/users/me/inbox/dms/read-all", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.broadcast.mockResolvedValue(undefined)
+ })
+
+ it("broadcasts the committed revision to every same-account socket", async () => {
+ mocks.markAll.mockResolvedValue({ count: 3, changed: true, revision: 8 })
+ const response = await POST(new Request("http://localhost", { method: "POST" }) as any)
+ await expect(response.json()).resolves.toEqual({ ok: true, count: 3, changed: true, revision: 8 })
+ expect(mocks.broadcast).toHaveBeenCalledWith("u1", {
+ type: "community:inbox.changed",
+ revision: 8,
+ inboxChanged: true,
+ reason: "read_all",
+ })
+ expect(mocks.markAll).toHaveBeenCalledWith({ kind: "primary-db" }, "u1")
+ })
+
+ it("does not broadcast an empty read-all no-op", async () => {
+ mocks.markAll.mockResolvedValue({ count: 0, changed: false, revision: 8 })
+ const response = await POST(new Request("http://localhost", { method: "POST" }) as any)
+ await expect(response.json()).resolves.toEqual({ ok: true, count: 0, changed: false, revision: 8 })
+ expect(mocks.broadcast).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts
index f0707c3c4..2e5db89b6 100644
--- a/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/dms/read-all/route.ts
@@ -1,7 +1,8 @@
-import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { queries, WS_EVENTS } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
/**
* POST /api/community/users/me/inbox/dms/read-all
@@ -12,7 +13,15 @@ import { writeJSON } from "@/lib/middleware/helpers"
* channel-unreads + dms — each idempotent and independently retryable.
*/
export const POST = withAuth(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
- const count = await queries.communityReadState.markAllDmsRead(db, ctx.userId)
- return writeJSON({ ok: true, count })
+ const db = getPrimaryDb(ctx.env.DB)
+ const { count, changed, revision } = await queries.communityReadState.markAllDmsRead(db, ctx.userId)
+ if (changed) {
+ await broadcastToUserSafe(ctx.userId, {
+ type: WS_EVENTS.INBOX_CHANGED,
+ revision,
+ inboxChanged: true,
+ reason: "read_all",
+ })
+ }
+ return writeJSON({ ok: true, count, changed, revision })
})
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts
index ce52fcf3f..50757ed32 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.test.ts
@@ -1,21 +1,31 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
-const mockDeleteMention = vi.fn()
+const mockDismissMentionWithRevision = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
-vi.mock("@alook/shared", () => ({
- createDb: vi.fn(() => ({})),
- queries: {
- communityMention: {
- deleteMention: (...args: unknown[]) => mockDeleteMention(...args),
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityMention: {
+ ...actual.queries.communityMention,
+ dismissMentionWithRevision: (...args: unknown[]) => mockDismissMentionWithRevision(...args),
+ },
},
- },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => mockBroadcastToUserSafe(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
@@ -40,16 +50,21 @@ describe("DELETE /api/community/users/me/inbox/mentions/{id}", () => {
it("deletes the mention scoped to the current user", async () => {
// The query returns the number of rows affected; a real hit returns 1.
- mockDeleteMention.mockResolvedValue(1)
+ mockDismissMentionWithRevision.mockResolvedValue({ changed: true, revision: 4 })
const res = await DELETE(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/mn1", { method: "DELETE" }), {
params: { id: "mn1" },
} as never)
expect(res.status).toBe(200)
- expect(mockDeleteMention).toHaveBeenCalledWith({}, "u1", "mn1")
+ expect(mockDismissMentionWithRevision).toHaveBeenCalledWith({}, "u1", "mn1")
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", expect.objectContaining({
+ reason: "mention_dismiss",
+ revision: 4,
+ }))
+ await expect(res.json()).resolves.toEqual({ ok: true, changed: true, revision: 4 })
})
it("404 when the mention does not exist or belongs to another user", async () => {
- mockDeleteMention.mockResolvedValue(0)
+ mockDismissMentionWithRevision.mockResolvedValue({ changed: false, revision: 4 })
const res = await DELETE(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/mn1", { method: "DELETE" }), {
params: { id: "mn1" },
} as never)
@@ -61,6 +76,6 @@ describe("DELETE /api/community/users/me/inbox/mentions/{id}", () => {
params: {},
} as never)
expect(res.status).toBe(400)
- expect(mockDeleteMention).not.toHaveBeenCalled()
+ expect(mockDismissMentionWithRevision).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts
index 8f0b73c62..58dadb708 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/[id]/route.ts
@@ -1,15 +1,26 @@
-import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { queries, WS_EVENTS } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
export const DELETE = withAuth(async (_req, ctx) => {
const mentionId = ctx.params?.id
if (!mentionId) return writeError("missing mention id", 400)
- const db = getDb(ctx.env.DB)
- const affected = await queries.communityMention.deleteMention(db, ctx.userId, mentionId)
- if (!affected) return writeError("mention not found", 404)
+ const db = getPrimaryDb(ctx.env.DB)
+ const result = await queries.communityMention.dismissMentionWithRevision(
+ db,
+ ctx.userId,
+ mentionId,
+ )
+ if (!result.changed) return writeError("mention not found", 404)
- return writeJSON({ ok: true })
+ await broadcastToUserSafe(ctx.userId, {
+ type: WS_EVENTS.INBOX_CHANGED,
+ reason: "mention_dismiss",
+ inboxChanged: true,
+ revision: result.revision,
+ })
+ return writeJSON({ ok: true, ...result })
})
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts
index b370c92ba..5865d6c7a 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.test.ts
@@ -1,21 +1,31 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
-const mockMarkAllMentionsRead = vi.fn()
+const mockMarkAllMentionsReadWithRevision = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: vi.fn(() => ({})) }))
-vi.mock("@alook/shared", () => ({
- createDb: vi.fn(() => ({})),
- queries: {
- communityMention: {
- markAllMentionsRead: (...args: unknown[]) => mockMarkAllMentionsRead(...args),
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityMention: {
+ ...actual.queries.communityMention,
+ markAllMentionsReadWithRevision: (...args: unknown[]) => mockMarkAllMentionsReadWithRevision(...args),
+ },
},
- },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => mockBroadcastToUserSafe(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
@@ -39,9 +49,21 @@ describe("POST /api/community/users/me/inbox/mentions/read-all", () => {
beforeEach(() => vi.clearAllMocks())
it("marks all mentions read for the current user", async () => {
- mockMarkAllMentionsRead.mockResolvedValue(undefined)
+ mockMarkAllMentionsReadWithRevision.mockResolvedValue({ count: 2, changed: true, revision: 7 })
const res = await POST(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/read-all", { method: "POST" }))
expect(res.status).toBe(200)
- expect(mockMarkAllMentionsRead).toHaveBeenCalledWith({}, "u1")
+ expect(mockMarkAllMentionsReadWithRevision).toHaveBeenCalledWith({}, "u1")
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", expect.objectContaining({
+ reason: "mention_read_all",
+ revision: 7,
+ }))
+ await expect(res.json()).resolves.toEqual({ ok: true, count: 2, changed: true, revision: 7 })
+ })
+
+ it("returns the current revision without broadcasting a duplicate no-op", async () => {
+ mockMarkAllMentionsReadWithRevision.mockResolvedValue({ count: 0, changed: false, revision: 7 })
+ const res = await POST(new NextRequest("http://localhost/api/community/users/me/inbox/mentions/read-all", { method: "POST" }))
+ await expect(res.json()).resolves.toEqual({ ok: true, count: 0, changed: false, revision: 7 })
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts
index 2daf41b16..ea2395bc4 100644
--- a/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/mentions/read-all/route.ts
@@ -1,10 +1,19 @@
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
-import { getDb } from "@/lib/db"
-import { queries } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { queries, WS_EVENTS } from "@alook/shared"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
export const POST = withAuth(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
- await queries.communityMention.markAllMentionsRead(db, ctx.userId)
- return writeJSON({ ok: true })
+ const db = getPrimaryDb(ctx.env.DB)
+ const result = await queries.communityMention.markAllMentionsReadWithRevision(db, ctx.userId)
+ if (result.changed) {
+ await broadcastToUserSafe(ctx.userId, {
+ type: WS_EVENTS.INBOX_CHANGED,
+ reason: "mention_read_all",
+ inboxChanged: true,
+ revision: result.revision,
+ })
+ }
+ return writeJSON({ ok: true, ...result })
})
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts
index 07a0cd099..4faf957b2 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.test.ts
@@ -3,23 +3,37 @@ import { NextRequest } from "next/server"
const mockMarkAllServerChannelsRead = vi.fn()
const mockListVisibleChannelIds = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
+const mockGetPrimaryDb = vi.fn(() => ({ kind: "primary-db" }))
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}))
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+vi.mock("@/lib/db", () => ({
+ getPrimaryDb: (...args: unknown[]) => mockGetPrimaryDb(...args),
+}))
-vi.mock("@alook/shared", () => ({
- createDb: vi.fn(() => ({})),
- queries: {
- communityReadState: {
- markAllServerChannelsRead: (...args: unknown[]) => mockMarkAllServerChannelsRead(...args),
- },
- communityChannel: {
- listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityReadState: {
+ ...actual.queries.communityReadState,
+ markAllServerChannelsRead: (...args: unknown[]) => mockMarkAllServerChannelsRead(...args),
+ },
+ communityChannel: {
+ ...actual.queries.communityChannel,
+ listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIds(...args),
+ },
},
- },
+ }
+})
+
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => mockBroadcastToUserSafe(...args),
}))
vi.mock("@/lib/middleware/auth", () => ({
@@ -43,25 +57,38 @@ describe("POST /api/community/users/me/inbox/unreads/read-all", () => {
beforeEach(() => {
vi.clearAllMocks()
mockListVisibleChannelIds.mockResolvedValue(["c1", "c2"])
+ mockBroadcastToUserSafe.mockResolvedValue(undefined)
})
it("returns the count of NON-EMPTY channels marked read (invariant: empty channels excluded)", async () => {
// Post-invariant: count == channels that actually received an aligned
// write. Empty channels are skipped, so this is <= reachable-channel count.
- mockMarkAllServerChannelsRead.mockResolvedValue(7)
+ mockMarkAllServerChannelsRead.mockResolvedValue({ count: 7, changed: true, revision: 3 })
const res = await POST(new NextRequest("http://localhost/api/community/users/me/inbox/unreads/read-all", { method: "POST" }))
const body = await res.json()
expect(res.status).toBe(200)
- expect(body).toEqual({ ok: true, count: 7 })
+ expect(body).toEqual({ ok: true, count: 7, changed: true, revision: 3 })
// Scoped to the viewer's visible channels (resolved once, passed through).
- expect(mockMarkAllServerChannelsRead).toHaveBeenCalledWith({}, "u1", ["c1", "c2"])
+ expect(mockMarkAllServerChannelsRead).toHaveBeenCalledWith(
+ { kind: "primary-db" },
+ "u1",
+ ["c1", "c2"],
+ )
+ expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("u1", {
+ type: "community:inbox.changed",
+ revision: 3,
+ inboxChanged: true,
+ reason: "read_all",
+ })
+ expect(mockGetPrimaryDb).toHaveBeenCalledOnce()
})
it("returns count 0 when every channel is empty (nothing to write)", async () => {
- mockMarkAllServerChannelsRead.mockResolvedValue(0)
+ mockMarkAllServerChannelsRead.mockResolvedValue({ count: 0, changed: false, revision: 3 })
const res = await POST(new NextRequest("http://localhost/api/community/users/me/inbox/unreads/read-all", { method: "POST" }))
const body = await res.json()
expect(res.status).toBe(200)
- expect(body).toEqual({ ok: true, count: 0 })
+ expect(body).toEqual({ ok: true, count: 0, changed: false, revision: 3 })
+ expect(mockBroadcastToUserSafe).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts
index c9b2749cc..b03989cae 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/read-all/route.ts
@@ -1,14 +1,23 @@
-import { queries } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { queries, WS_EVENTS } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON } from "@/lib/middleware/helpers"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
export const POST = withAuth(async (_req, ctx) => {
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
// Resolve the viewer's visible channels once (top-level + child threads,
// parent-climbed) and scope the mark-all to them — a private thread under an
// invisible parent is excluded.
const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)
- const count = await queries.communityReadState.markAllServerChannelsRead(db, ctx.userId, visibleChannelIds)
- return writeJSON({ ok: true, count })
+ const { count, changed, revision } = await queries.communityReadState.markAllServerChannelsRead(db, ctx.userId, visibleChannelIds)
+ if (changed) {
+ await broadcastToUserSafe(ctx.userId, {
+ type: WS_EVENTS.INBOX_CHANGED,
+ revision,
+ inboxChanged: true,
+ reason: "read_all",
+ })
+ }
+ return writeJSON({ ok: true, count, changed, revision })
})
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
index 5ca93b3a2..96bfac530 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.test.ts
@@ -269,6 +269,9 @@ describe("GET /api/community/users/me/inbox/unreads", () => {
row({ channelId: "c1", channelName: "general", type: "text" }),
row({ channelId: "c2", channelName: "help-forum", type: "forum", lastMessageAt: "2026-06-25T09:00:00Z" }),
])
+ mockListUnreadForumOpeners.mockResolvedValue([
+ opener({ forumChannelId: "c2", childChannelId: "p2", openerMessageId: "m2" }),
+ ])
const res = await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))
const body = await res.json()
const byId = Object.fromEntries(
@@ -395,14 +398,14 @@ describe("GET /api/community/users/me/inbox/unreads", () => {
expect(mockListForumOpenersByChildIds).toHaveBeenCalledWith(expect.anything(), ["post_ok"])
})
- it("renders no opener children when the eligible opener query returns none", async () => {
+ it("removes a phantom forum parent when no unread opener or child remains", async () => {
mockListEligibleUnreadChannels.mockResolvedValue([
row({ channelId: "f1", channelName: "Forum", type: "forum" }),
])
mockListUnreadForumOpeners.mockResolvedValue([])
const body = await (await GET(new NextRequest("http://localhost/api/community/users/me/inbox/unreads"))).json()
- expect(body.servers[0].channels[0].children).toEqual([])
+ expect(body.servers).toEqual([])
})
it("uses opener seq/id as deterministic tie-breaks before child cap truncation", async () => {
diff --git a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
index d12e4a0de..6b96e6839 100644
--- a/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
+++ b/src/web/src/app/api/community/users/me/inbox/unreads/route.ts
@@ -64,7 +64,17 @@ export const GET = withAuth(async (req, ctx) => {
const forumOpeners = [...new Map(
[...directForumOpeners, ...childForumOpeners].map((row) => [row.childChannelId, row]),
).values()]
- return { unread, unreadDms, forumOpeners }
+ const forumParentsWithUnread = new Set([
+ ...forumOpeners.map((row) => row.forumChannelId),
+ ...unread.flatMap((row) => row.parentChannelId ? [row.parentChannelId] : []),
+ ])
+ const withoutPhantomForumParents = unread.filter(
+ (row) =>
+ row.parentChannelId ||
+ row.type !== "forum" ||
+ forumParentsWithUnread.has(row.channelId),
+ )
+ return { unread: withoutPhantomForumParents, unreadDms, forumOpeners }
},
{ unread: [], unreadDms: [], forumOpeners: [] },
{ route: "community/inbox/unreads" },
diff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts
index 3373efa42..fe54761f2 100644
--- a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts
+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.test.ts
@@ -3,8 +3,13 @@ import { NextRequest } from "next/server"
const requireMessageSurfaceAccess = vi.fn()
const setChannelLevel = vi.fn()
+const removeChannelOverride = vi.fn()
+const broadcastToUserSafe = vi.fn()
-vi.mock("@/lib/db", () => ({ getDb: () => ({}) }))
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({}) }))
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => broadcastToUserSafe(...args),
+}))
vi.mock("@/lib/community/permissions", () => ({
requireMessageSurfaceAccess: (...args: unknown[]) => requireMessageSurfaceAccess(...args),
}))
@@ -14,7 +19,7 @@ vi.mock("@alook/shared", async () => {
...actual,
queries: { communityNotificationSetting: {
setChannelLevel: (...args: unknown[]) => setChannelLevel(...args),
- removeChannelOverride: vi.fn(),
+ removeChannelOverride: (...args: unknown[]) => removeChannelOverride(...args),
} },
}
})
@@ -24,13 +29,21 @@ vi.mock("@/lib/middleware/auth", () => ({
}),
}))
-import { PUT } from "./route"
+import { DELETE, PUT } from "./route"
describe("human DM notification settings", () => {
beforeEach(() => {
vi.clearAllMocks()
requireMessageSurfaceAccess.mockResolvedValue({ ok: true, value: { surface: "dm" } })
- setChannelLevel.mockResolvedValue({ level: "mentions" })
+ setChannelLevel.mockResolvedValue({
+ setting: { level: "mentions" },
+ readStateRevision: 2,
+ })
+ broadcastToUserSafe.mockResolvedValue(undefined)
+ removeChannelOverride.mockResolvedValue({
+ setting: null,
+ readStateRevision: 3,
+ })
})
it("uses the unified message-surface gate so DM block and participant checks apply", async () => {
@@ -42,7 +55,31 @@ describe("human DM notification settings", () => {
expect(response.status).toBe(200)
expect(requireMessageSurfaceAccess).toHaveBeenCalledWith({}, "dm_1", "user_1")
expect(setChannelLevel).toHaveBeenCalledWith({}, {
- userId: "user_1", channelId: "dm_1", level: "mentions",
+ userId: "user_1", channelId: "dm_1", level: "mentions", actorKind: "human",
+ })
+ expect(broadcastToUserSafe).toHaveBeenCalledWith("user_1", {
+ type: "community:read_state.advanced",
+ revision: 2,
+ inboxChanged: true,
+ })
+ })
+
+ it("removes a human override through the same gate and broadcasts its revision", async () => {
+ const response = await DELETE(
+ new NextRequest("http://local", { method: "DELETE" }),
+ { params: { id: "dm_1" } } as any,
+ )
+
+ expect(response.status).toBe(204)
+ expect(removeChannelOverride).toHaveBeenCalledWith({}, {
+ userId: "user_1",
+ channelId: "dm_1",
+ actorKind: "human",
+ })
+ expect(broadcastToUserSafe).toHaveBeenCalledWith("user_1", {
+ type: "community:read_state.advanced",
+ revision: 3,
+ inboxChanged: true,
})
})
})
diff --git a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts
index 58a60c3bf..5e097a0a0 100644
--- a/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts
+++ b/src/web/src/app/api/community/users/me/notifications/channel/[id]/route.ts
@@ -1,15 +1,24 @@
import { NextRequest } from "next/server"
-import { queries, NOTIFICATION_LEVEL_VALUES } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { queries, NOTIFICATION_LEVEL_VALUES, WS_EVENTS } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { requireMessageSurfaceAccess } from "@/lib/community/permissions"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
+
+async function broadcastRevision(userId: string, revision: number) {
+ await broadcastToUserSafe(userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision,
+ inboxChanged: true,
+ })
+}
export const PUT = withAuth(async (req: NextRequest, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const auth = await requireMessageSurfaceAccess(db, channelId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
@@ -24,27 +33,31 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
return writeError(`level must be one of: ${NOTIFICATION_LEVEL_VALUES.join(", ")}`, 400)
}
- const setting = await queries.communityNotificationSetting.setChannelLevel(db, {
+ const result = await queries.communityNotificationSetting.setChannelLevel(db, {
userId: ctx.userId,
channelId,
level: body.level,
+ actorKind: "human",
})
+ if (result.readStateRevision !== null) await broadcastRevision(ctx.userId, result.readStateRevision)
- return writeJSON(setting)
+ return writeJSON(result.setting)
})
export const DELETE = withAuth(async (_req, ctx) => {
const channelId = ctx.params?.id
if (!channelId) return writeError("missing channel id", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const auth = await requireMessageSurfaceAccess(db, channelId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- await queries.communityNotificationSetting.removeChannelOverride(db, {
+ const result = await queries.communityNotificationSetting.removeChannelOverride(db, {
userId: ctx.userId,
channelId,
+ actorKind: "human",
})
+ if (result.readStateRevision !== null) await broadcastRevision(ctx.userId, result.readStateRevision)
return new Response(null, { status: 204 })
})
diff --git a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts
new file mode 100644
index 000000000..60ba448e6
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { NextRequest } from "next/server"
+
+const requireServerMember = vi.fn()
+const setServerLevel = vi.fn()
+const broadcastToUserSafe = vi.fn()
+
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => ({}) }))
+vi.mock("@/lib/community/fanout", () => ({
+ broadcastToUserSafe: (...args: unknown[]) => broadcastToUserSafe(...args),
+}))
+vi.mock("@/lib/community/permissions", () => ({
+ requireServerMember: (...args: unknown[]) => requireServerMember(...args),
+}))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ communityNotificationSetting: {
+ setServerLevel: (...args: unknown[]) => setServerLevel(...args),
+ },
+ },
+ }
+})
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => (req: NextRequest, ctx: any) => handler(req, {
+ env: { DB: {} },
+ userId: "user_1",
+ params: ctx.params,
+ }),
+}))
+
+import { PUT } from "./route"
+
+describe("human server notification settings", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ requireServerMember.mockResolvedValue({ ok: true, member: { id: "member_1" } })
+ setServerLevel.mockResolvedValue({
+ setting: { level: "nothing" },
+ readStateRevision: 7,
+ })
+ broadcastToUserSafe.mockResolvedValue(undefined)
+ })
+
+ it("writes the human policy and broadcasts its committed revision", async () => {
+ const response = await PUT(new NextRequest("http://local", {
+ method: "PUT",
+ body: JSON.stringify({ level: "nothing" }),
+ }), { params: { id: "server_1" } } as any)
+
+ expect(response.status).toBe(200)
+ expect(setServerLevel).toHaveBeenCalledWith({}, {
+ userId: "user_1",
+ serverId: "server_1",
+ level: "nothing",
+ actorKind: "human",
+ })
+ expect(broadcastToUserSafe).toHaveBeenCalledWith("user_1", {
+ type: "community:read_state.advanced",
+ revision: 7,
+ inboxChanged: true,
+ })
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts
index 4ea89fe13..cd836c56a 100644
--- a/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts
+++ b/src/web/src/app/api/community/users/me/notifications/server/[id]/route.ts
@@ -1,15 +1,16 @@
import { NextRequest } from "next/server"
-import { queries, NOTIFICATION_LEVEL_VALUES } from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { queries, NOTIFICATION_LEVEL_VALUES, WS_EVENTS } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { requireServerMember } from "@/lib/community/permissions"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
export const PUT = withAuth(async (req: NextRequest, ctx) => {
const serverId = ctx.params?.id
if (!serverId) return writeError("missing server id", 400)
- const db = getDb(ctx.env.DB)
+ const db = getPrimaryDb(ctx.env.DB)
const auth = await requireServerMember(db, serverId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
@@ -24,11 +25,19 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
return writeError(`level must be one of: ${NOTIFICATION_LEVEL_VALUES.join(", ")}`, 400)
}
- const setting = await queries.communityNotificationSetting.setServerLevel(db, {
+ const result = await queries.communityNotificationSetting.setServerLevel(db, {
userId: ctx.userId,
serverId,
level: body.level,
+ actorKind: "human",
})
+ if (result.readStateRevision !== null) {
+ await broadcastToUserSafe(ctx.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: result.readStateRevision,
+ inboxChanged: true,
+ })
+ }
- return writeJSON(setting)
+ return writeJSON(result.setting)
})
diff --git a/src/web/src/app/api/community/users/me/read-state/route.test.ts b/src/web/src/app/api/community/users/me/read-state/route.test.ts
new file mode 100644
index 000000000..d7bbf5db4
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/read-state/route.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ snapshot: vi.fn(),
+ getPrimaryDb: vi.fn(() => ({ kind: "primary-db" })),
+}))
+
+vi.mock("@/lib/db", () => ({
+ getPrimaryDb: (...args: unknown[]) => mocks.getPrimaryDb(...args),
+}))
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
+ return {
+ ...actual,
+ queries: {
+ ...actual.queries,
+ communityReadState: {
+ ...actual.queries.communityReadState,
+ getAccountReadStateSnapshot: (...args: unknown[]) => mocks.snapshot(...args),
+ },
+ },
+ withD1Retry: (operation: () => unknown) => operation(),
+ }
+})
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => (req: any) => handler(req, {
+ env: { DB: {} },
+ userId: "u1",
+ email: "[email protected]",
+ }),
+}))
+vi.mock("@/lib/middleware/helpers", () => ({
+ writeJSON: (data: unknown) => Response.json(data),
+}))
+
+import { GET } from "./route"
+
+describe("GET /api/community/users/me/read-state", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("returns the durable revision with the complete account read-state rows", async () => {
+ const readStates = [{
+ channelId: "c1",
+ lastReadMessageId: "m7",
+ lastReadAt: "2026-08-24T00:00:00.000Z",
+ lastReadSeq: 7,
+ }]
+ mocks.snapshot.mockResolvedValue({ revision: 12, readStates })
+
+ const response = await GET(new Request("http://localhost/api/community/users/me/read-state") as any)
+ await expect(response.json()).resolves.toEqual({ revision: 12, readStates })
+ expect(mocks.snapshot).toHaveBeenCalledWith({ kind: "primary-db" }, "u1")
+ expect(mocks.getPrimaryDb).toHaveBeenCalledOnce()
+ })
+
+ it("returns revision zero and no rows for a fresh account", async () => {
+ mocks.snapshot.mockResolvedValue({ revision: 0, readStates: [] })
+ const response = await GET(new Request("http://localhost/api/community/users/me/read-state") as any)
+ await expect(response.json()).resolves.toEqual({ revision: 0, readStates: [] })
+ })
+})
diff --git a/src/web/src/app/api/community/users/me/read-state/route.ts b/src/web/src/app/api/community/users/me/read-state/route.ts
new file mode 100644
index 000000000..91a3a8a80
--- /dev/null
+++ b/src/web/src/app/api/community/users/me/read-state/route.ts
@@ -0,0 +1,13 @@
+import { queries, withD1Retry } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth"
+import { writeJSON } from "@/lib/middleware/helpers"
+
+export const GET = withAuth(async (_req, ctx) => {
+ const db = getPrimaryDb(ctx.env.DB)
+ const snapshot = await withD1Retry(
+ () => queries.communityReadState.getAccountReadStateSnapshot(db, ctx.userId),
+ { route: "community/read-state-snapshot" },
+ )
+ return writeJSON(snapshot)
+})
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index df36462bc..74e8c24ad 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useState, type ReactNode } from "react"
+import { useEffect, useRef, useState, type ReactNode } from "react"
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"
import { createQueryClient } from "@/lib/query-client"
@@ -10,6 +10,8 @@ import {
PERSIST_MAX_AGE_MS,
shouldPersistQuery,
} from "@/lib/query-persister"
+import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"
+import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"
/**
* Owns the TanStack QueryClient for the community subtree.
@@ -38,6 +40,21 @@ export function QueryProvider({
// id, so we don't need to reactively rebuild the persister mid-session.
const [persister] = useState(() => createIdbPersister(userId))
const isDev = process.env.NODE_ENV !== "production"
+ const disposeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ useEffect(() => {
+ if (disposeTimer.current !== null) {
+ clearTimeout(disposeTimer.current)
+ disposeTimer.current = null
+ }
+ return () => {
+ disposeTimer.current = setTimeout(() => {
+ disposeTimer.current = null
+ disposeReadCoordinator(queryClient)
+ disposeAccountReadStateReconciliation(queryClient)
+ }, 0)
+ }
+ }, [queryClient])
return (
<PersistQueryClientProvider
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 58423aacb..79aeffbe8 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -294,8 +294,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
// mounted ChannelView sync the store in its own useEffect keeps skeleton
// type consistent with the target channel.
//
- // #3: also do NOT eagerly mark the channel read. The
- // IntersectionObserver in `useChannelWatermark` is authoritative — it
+ // Also do NOT eagerly mark the channel read. The visible-row read observer
// advances the pointer as the user actually looks at messages. Clicking
// the sidebar is not "I read everything"; it's just a navigation event.
// `channelTree.markRead(id)` is a client-only tint (unread flag on the
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsx
index e5b271f77..675eeef25 100644
--- a/src/web/src/app/c/community-shell.tsx
+++ b/src/web/src/app/c/community-shell.tsx
@@ -45,8 +45,8 @@ export function CommunityShell({
/**
* Mounted once beneath the QueryClient + CurrentUser providers. Owns:
* - The community WebSocket handler (`useCommunityWs`) — the module-scoped
- * Zustand stores + pending-reads map assume a single instance for the whole
- * session, so it lives here at the tree root.
+ * Zustand stores assume a single instance for the whole session, so it lives
+ * here at the tree root.
* - The `aboutMe` hydration that used to live in the God-context's mount
* effect — needed so the "Edit profile" dialog opens with the current value.
*/
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 376ec8cc7..3768df03b 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -27,7 +27,6 @@ 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 { useEagerDmRead } from "@/hooks/community/use-eager-dm-read"
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import { toChannelRefCandidate } from "@/lib/community/channel-ref-extension"
import {
@@ -183,12 +182,13 @@ function DmView() {
// 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 })
-
- // Eager mark-read on open — clears this DM from the inbox immediately while
- // the frozen `readSnapshot` above keeps the "New" divider anchored to the
- // pre-open pointer. Gated on the snapshot having settled.
- useEagerDmRead({ dmId, snapshotReady: !readSnapshotFetching })
+ useDmWatermark({
+ dmId,
+ messages,
+ scrollRootEl,
+ snapshotReady: !readSnapshotFetching,
+ confirmedSeq: readSnapshot?.lastReadSeq ?? 0,
+ })
// `↓ N` unread count. Same math as channel: server truth is
// `latestSeq - viewerLastReadSeq`. Clamp to 0 in case the read pointer
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index 431b5e0bd..5e308805a 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -94,8 +94,8 @@ export default function MeLayout({ children }: { children: ReactNode }) {
// `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
+ // fades on click (matches the pre-fix UX). The visible-row read observer
+ // 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.
diff --git a/src/web/src/components/community/channels/channel-header.tsx b/src/web/src/components/community/channels/channel-header.tsx
index b5ec1d019..adf3e8436 100644
--- a/src/web/src/components/community/channels/channel-header.tsx
+++ b/src/web/src/components/community/channels/channel-header.tsx
@@ -63,7 +63,12 @@ export function ChannelHeader({
onSetNotifLevel?: (l: ChannelNotifLevel) => void
onBack?: () => void
forum?: boolean
- breadcrumb?: { label: string; onRename?: (name: string) => void | Promise<void>; titleRename?: boolean; onNavigateBack?: () => void }
+ breadcrumb?: {
+ label: string
+ onRename?: (name: string) => void | Promise<void>
+ titleRename?: boolean
+ onNavigateBack?: () => void
+ }
server?: { id: string; name: string; icon: string | null }
tools?: { threads?: boolean; pinned?: boolean; members?: boolean }
}) {
@@ -96,7 +101,9 @@ export function ChannelHeader({
<span className="truncate text-base font-medium">{channel}</span>
</button>
<ChannelIcon className="shrink-0 text-base text-muted-foreground/60" />
- <span className="min-w-0 truncate text-base font-medium" title={breadcrumb.label}>{breadcrumb.label}</span>
+ <span className="min-w-0 truncate text-base font-medium" title={breadcrumb.label}>
+ {breadcrumb.label}
+ </span>
{breadcrumb.onRename && (
<BreadcrumbRename label={breadcrumb.label} onRename={breadcrumb.onRename} titleMode={breadcrumb.titleRename} />
)}
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 4076bfdef..cda1e77bc 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -143,9 +143,6 @@ export function ChannelRoute({ serverParam, channelId }: {
}, [])
const enterThread = useCallback((id: string) => {
- // No eager read PUT here — the thread page's `useEagerChannelRead` fires it
- // on mount AFTER its read-state snapshot latches, so the "New" divider
- // still anchors to the pre-open pointer. A PUT here would race the snapshot.
useCommunityStore.getState().uiHandlers.navigatePath?.(
channelHref(serverParam, id),
)
diff --git a/src/web/src/components/community/channels/forum-channel-surface.test.ts b/src/web/src/components/community/channels/forum-channel-surface.test.ts
index 736f7d28f..b51ee57d6 100644
--- a/src/web/src/components/community/channels/forum-channel-surface.test.ts
+++ b/src/web/src/components/community/channels/forum-channel-surface.test.ts
@@ -10,8 +10,6 @@ const mocks = vi.hoisted(() => ({
createForumThread: vi.fn(),
updatePostTags: vi.fn(),
deleteForumThread: vi.fn(),
- readState: vi.fn(() => ({ snapshot: null, isFetching: false })),
- eagerRead: vi.fn(),
activeMessageFeed: vi.fn(() => { throw new Error("forum must not initialize an active message feed") }),
}))
@@ -19,12 +17,6 @@ vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))
vi.mock("@/hooks/community/use-channel-message-feed", () => ({
useChannelMessageFeed: mocks.activeMessageFeed,
}))
-vi.mock("@/hooks/community/use-channel-read-state", () => ({
- useChannelReadStateSnapshot: mocks.readState,
-}))
-vi.mock("@/hooks/community/use-eager-channel-read", () => ({
- useEagerChannelRead: mocks.eagerRead,
-}))
vi.mock("@/hooks/community/mutations", () => ({
useCreateForumThread: () => ({ mutateAsync: mocks.createForumThread }),
useUpdatePostTags: () => ({
@@ -86,7 +78,6 @@ function surfaceProps(overrides: Record<string, unknown> = {}) {
describe("ForumChannelSurface ownership", () => {
beforeEach(() => {
mocks.createForumThread.mockResolvedValue({ threadId: "post_new" })
- mocks.readState.mockReturnValue({ snapshot: null, isFetching: false })
})
afterEach(() => {
@@ -167,48 +158,6 @@ describe("ForumChannelSurface ownership", () => {
expect(forumProps.canDeletePost?.(otherPost)).toBe(true)
})
- it("waits for the read snapshot and eagerly reads each forum without an active message feed", () => {
- mocks.readState.mockReturnValue({ snapshot: null, isFetching: true })
- let renderer: TestRenderer.ReactTestRenderer
- act(() => {
- renderer = TestRenderer.create(React.createElement(ForumChannelSurface, surfaceProps()))
- })
-
- expect(mocks.readState).toHaveBeenLastCalledWith("forum_1")
- expect(mocks.eagerRead).toHaveBeenLastCalledWith({
- channelId: "forum_1",
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: false,
- })
-
- mocks.readState.mockReturnValue({ snapshot: null, isFetching: false })
- act(() => {
- renderer!.update(React.createElement(ForumChannelSurface, surfaceProps()))
- })
- expect(mocks.eagerRead).toHaveBeenLastCalledWith({
- channelId: "forum_1",
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: true,
- })
-
- act(() => {
- renderer!.update(React.createElement(
- ForumChannelSurface,
- surfaceProps({ channelId: "forum_2", serverId: "srv_2" }),
- ))
- })
- expect(mocks.readState).toHaveBeenLastCalledWith("forum_2")
- expect(mocks.eagerRead).toHaveBeenLastCalledWith({
- channelId: "forum_2",
- serverId: "srv_2",
- isChildChannel: false,
- snapshotReady: true,
- })
- expect(mocks.activeMessageFeed).not.toHaveBeenCalled()
- })
-
it("resets the right panel when channelId changes without relying on an outer remount", () => {
const firstProps = surfaceProps()
let renderer: TestRenderer.ReactTestRenderer
diff --git a/src/web/src/components/community/channels/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsx
index 9028f4340..9f65b6a4b 100644
--- a/src/web/src/components/community/channels/forum-channel-surface.tsx
+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx
@@ -17,8 +17,6 @@ import {
useDeleteForumThread,
useUpdatePostTags,
} from "@/hooks/community/mutations"
-import { useChannelReadStateSnapshot } from "@/hooks/community/use-channel-read-state"
-import { useEagerChannelRead } from "@/hooks/community/use-eager-channel-read"
export function ForumChannelSurface({
serverId,
@@ -53,13 +51,6 @@ export function ForumChannelSurface({
onOpenPost: (postId: string) => void
onOpenProfile: OpenProfile
}) {
- const readState = useChannelReadStateSnapshot(channelId)
- useEagerChannelRead({
- channelId,
- serverId,
- isChildChannel: false,
- snapshotReady: !readState.isFetching,
- })
const [panelState, setPanelState] = useState<{ channelId: string; panel: RightPanel }>({
channelId,
panel: null,
diff --git a/src/web/src/components/community/channels/forum-surface.test.ts b/src/web/src/components/community/channels/forum-surface.test.ts
new file mode 100644
index 000000000..1a7feca28
--- /dev/null
+++ b/src/web/src/components/community/channels/forum-surface.test.ts
@@ -0,0 +1,99 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { ForumView } from "./forum-view"
+import { ForumSurface } from "./forum-surface"
+
+const mocks = vi.hoisted(() => ({
+ observe: vi.fn(),
+ feed: {
+ posts: [
+ {
+ id: "child-a",
+ name: "A",
+ messageCount: 0,
+ lastMessageAt: "t1",
+ parent: { authorName: "Alice", text: "" },
+ authorId: "alice",
+ authorAvatar: "A",
+ openerMessageId: "opener-a",
+ parentSeq: 3,
+ tags: [],
+ preview: "",
+ participants: [],
+ participantCount: 1,
+ },
+ {
+ id: "legacy-child",
+ name: "Legacy",
+ messageCount: 0,
+ lastMessageAt: "t0",
+ parent: { authorName: "", text: "" },
+ authorId: "",
+ authorAvatar: "",
+ openerMessageId: "",
+ tags: [],
+ preview: "",
+ participants: [],
+ participantCount: 0,
+ },
+ ],
+ isLoading: false,
+ tag: "All",
+ availableTags: [],
+ selectTag: vi.fn(),
+ hasMoreOlder: false,
+ isFetchingOlder: false,
+ fetchOlder: vi.fn(),
+ },
+}))
+
+vi.mock("@/hooks/community/use-forum-feed", () => ({
+ useForumFeed: () => mocks.feed,
+}))
+vi.mock("@/hooks/community/use-channel-read-state", () => ({
+ useChannelReadStateSnapshot: () => ({
+ snapshot: { lastReadMessageId: "opener-old", lastReadAt: "t", lastReadSeq: 2 },
+ isFetching: false,
+ }),
+}))
+vi.mock("@/hooks/community/use-read-observer", () => ({
+ useTimelineReadObserver: (value: unknown) => mocks.observe(value),
+}))
+vi.mock("./forum-view", () => ({
+ ForumView: vi.fn(() => null),
+}))
+
+describe("ForumSurface generic read-row adapter", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("projects canonical opener candidates and binds only the list viewport", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(ForumSurface, {
+ serverId: "server-1",
+ forumChannelId: "forum-1",
+ members: [],
+ onOpenPost: vi.fn(),
+ }))
+ })
+
+ expect(mocks.observe).toHaveBeenLastCalledWith({
+ channelId: "forum-1",
+ messages: [{ id: "opener-a", seq: 3, authorId: "alice" }],
+ scrollRootEl: null,
+ snapshotReady: true,
+ confirmedSeq: 2,
+ })
+
+ const root = {} as HTMLDivElement
+ const viewProps = vi.mocked(ForumView).mock.calls.at(-1)![0]
+ act(() => viewProps.onScrollRoot?.(root))
+ expect(mocks.observe).toHaveBeenLastCalledWith(expect.objectContaining({
+ channelId: "forum-1",
+ scrollRootEl: root,
+ }))
+
+ act(() => renderer!.unmount())
+ })
+})
diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsx
index c09f40f24..d0f31492f 100644
--- a/src/web/src/components/community/channels/forum-surface.tsx
+++ b/src/web/src/components/community/channels/forum-surface.tsx
@@ -1,10 +1,13 @@
"use client"
+import { useState } from "react"
import type { NewForumThread } from "../messages/create-forum-thread"
import type { ForumThread } from "@/lib/community/models/message"
import type { Member } from "@/lib/community/models/people"
import { ForumView } from "./forum-view"
import { useForumFeed } from "@/hooks/community/use-forum-feed"
+import { useChannelReadStateSnapshot } from "@/hooks/community/use-channel-read-state"
+import { useTimelineReadObserver } from "@/hooks/community/use-read-observer"
export function ForumSurface({ serverId, forumChannelId, ...props }: {
serverId: string
@@ -21,6 +24,19 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {
deletingPost?: string | null
}) {
const feed = useForumFeed(serverId, forumChannelId)
+ const readState = useChannelReadStateSnapshot(forumChannelId)
+ const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)
+ useTimelineReadObserver({
+ channelId: forumChannelId,
+ messages: feed.posts.flatMap((post) => (
+ post.openerMessageId && post.parentSeq
+ ? [{ id: post.openerMessageId, seq: post.parentSeq, authorId: post.authorId }]
+ : []
+ )),
+ scrollRootEl,
+ snapshotReady: !readState.isFetching,
+ confirmedSeq: readState.snapshot?.lastReadSeq ?? 0,
+ })
return <ForumView
forumChannelId={forumChannelId}
{...props}
@@ -32,6 +48,7 @@ export function ForumSurface({ serverId, forumChannelId, ...props }: {
hasMore={feed.hasMoreOlder}
loadingMore={feed.isFetchingOlder}
onLoadMore={feed.fetchOlder}
+ onScrollRoot={setScrollRootEl}
onEditPostTags={(threadId, tags) => {
const post = feed.posts.find((candidate) => candidate.id === threadId)
if (post) props.onEditPostTags?.(post, tags)
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index 34334d70e..a032a49da 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -187,6 +187,7 @@ export function ForumView({
posts, loading, tag, availableTags = [], onTagChange, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,
hasMore, loadingMore, onLoadMore,
onDeletePost, canDeletePost, deletingPost,
+ onScrollRoot,
}: {
forumChannelId: string
members: Member[]
@@ -216,6 +217,7 @@ export function ForumView({
canDeletePost?: (post: ForumThread) => boolean
// The post id whose delete is in flight, if any.
deletingPost?: string | null
+ onScrollRoot?: (node: HTMLDivElement | null) => void
}) {
const [composing, setComposing] = useState(false)
const [deletingFor, setDeletingFor] = useState<ForumThread | null>(null)
@@ -224,6 +226,10 @@ export function ForumView({
const activeFilterRef = useRef<HTMLButtonElement>(null)
const tagScrollerRef = useRef<HTMLDivElement>(null)
const scrollRef = useRef<HTMLDivElement>(null)
+ const bindScrollRoot = useCallback((node: HTMLDivElement | null) => {
+ scrollRef.current = node
+ onScrollRoot?.(node)
+ }, [onScrollRoot])
const alignedTagRef = useRef<string | null>(null)
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
const virtualizer = useVirtualizer({
@@ -388,7 +394,7 @@ export function ForumView({
)}
<div
- ref={scrollRef}
+ ref={bindScrollRoot}
role="main"
data-testid={tid.forumPostList}
className="flex-1 overflow-y-auto thin-scrollbar px-0 py-2 sm:px-4"
@@ -415,6 +421,7 @@ export function ForumView({
key={p.id}
role="button"
tabIndex={0}
+ data-msg-id={p.openerMessageId || undefined}
data-testid={tid.forumThreadCard(p.id)}
onClick={() => onOpenPost(p.id)}
onKeyDown={(event) => {
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index 37b4b6f27..4ab2b79a6 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -56,6 +56,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenForumThread, o
{s.channels.map((c) => (
<div key={c.channelId}>
<button
+ data-testid={tid.inboxUnreadChannel(c.channelId)}
onClick={() => onOpenChannel?.(s.serverId, c.channelId)}
className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"
>
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
index a0ba34154..ead4c4d94 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
@@ -10,7 +10,6 @@ const mocks = vi.hoisted(() => ({
markAll: vi.fn(),
deleteMention: vi.fn(),
unmark: vi.fn(),
- readForum: vi.fn(),
verifyDm: vi.fn(),
}))
@@ -42,7 +41,6 @@ vi.mock("@/hooks/community/mutations", () => ({
useMarkAllInboxRead: () => ({ mutate: mocks.markAll }),
useDeleteMention: () => ({ mutate: mocks.deleteMention }),
useUnmarkMessage: () => ({ mutate: mocks.unmark }),
- useReadForumThreadFromInbox: () => ({ mutate: mocks.readForum }),
}))
vi.mock("@/hooks/community/use-dm-route-verification", () => ({
startDmRouteVerification: (...args: unknown[]) => mocks.verifyDm(...args),
@@ -84,7 +82,6 @@ async function renderController(initialDmCache: DmCache = { conversations: [{
}
const cancelPendingNavigation = vi.fn(() => { order.push("cancel") })
mocks.watch.mockImplementation(() => { order.push("watch") })
- mocks.readForum.mockImplementation(() => { order.push("read") })
mocks.verifyDm.mockImplementation(() => {
order.push("verify")
return Promise.resolve("present")
@@ -110,7 +107,7 @@ async function renderController(initialDmCache: DmCache = { conversations: [{
describe("useShellInboxController", () => {
beforeEach(() => {
mocks.markedEnabled.length = 0
- for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.readForum, mocks.verifyDm]) {
+ for (const mock of [mocks.watch, mocks.markAll, mocks.deleteMention, mocks.unmark, mocks.verifyDm]) {
mock.mockReset()
}
})
@@ -171,9 +168,8 @@ describe("useShellInboxController", () => {
const hook = await renderController()
hook.order.length = 0
await act(async () => hook.current.popoverProps.onOpenForumThread("s1", "forum", "child", "opener"))
- expect(hook.order).toEqual(["watch", "read", "cancel", "push"])
+ expect(hook.order).toEqual(["watch", "cancel", "push"])
expect(mocks.watch).toHaveBeenCalledWith("channel:child")
- expect(mocks.readForum).toHaveBeenCalledWith({ parentChannelId: "forum", openerMessageId: "opener" })
expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child")
hook.order.length = 0
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index becb908c7..cb2b750c3 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
@@ -12,7 +12,6 @@ import {
useMarkAllInboxRead,
useDeleteMention,
useUnmarkMessage,
- useReadForumThreadFromInbox,
} from "@/hooks/community/mutations"
import type { InboxPopover } from "./community-inbox-popover"
import type { QueryClient } from "@tanstack/react-query"
@@ -40,7 +39,6 @@ export function useShellInboxController({
const { mutate: unmarkMessageMutate } = useUnmarkMessage()
const markAllInboxRead = useMarkAllInboxRead()
const deleteMention = useDeleteMention()
- const { mutate: readForumThreadFromInbox } = useReadForumThreadFromInbox()
const inbox = useInboxAutoCollapse({ unreads: unreadFeed, unreadDms, mentions })
const watchInboxItem = inbox.watchItem
@@ -59,13 +57,12 @@ export function useShellInboxController({
serverId: string,
parentChannelId: string,
childChannelId: string,
- openerMessageId: string,
+ _openerMessageId: string,
) => {
watchInboxItem(`channel:${childChannelId}`)
- readForumThreadFromInbox({ parentChannelId, openerMessageId })
cancelPendingNavigation()
router.push(channelHref(serverId, childChannelId))
- }, [cancelPendingNavigation, readForumThreadFromInbox, router, watchInboxItem])
+ }, [cancelPendingNavigation, router, watchInboxItem])
const openMarked = useCallback((marked: Marked) => {
watchInboxItem(`marked:${marked.id}`)
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.test.ts
index 1584ab47b..49fe67478 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.test.ts
@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => ({
toast: vi.fn(),
toastApiError: vi.fn(),
validate: vi.fn(),
+ disposeReconciliation: vi.fn(),
}))
vi.mock("sonner", () => ({ toast: mocks.toast }))
@@ -88,6 +89,9 @@ vi.mock("@/components/community/social/profile-lookup", () => ({
vi.mock("@/lib/community/presence", () => ({ resolveProfilePresence: () => "online" }))
vi.mock("@/lib/community/avatar", () => ({ avatarInitial: () => "?" }))
vi.mock("@/lib/query-persister", () => ({ clearPersistedCache: mocks.clearCache }))
+vi.mock("@/hooks/community/community-ws/read-state-reconciliation", () => ({
+ disposeAccountReadStateReconciliation: mocks.disposeReconciliation,
+}))
vi.mock("@/lib/auth-client", () => ({ signOut: mocks.signOut }))
type Result = ReturnType<typeof useShellProfileController>
@@ -280,12 +284,13 @@ describe("useShellProfileController", () => {
mocks.communityReset.mockImplementation(() => { order.push("community") })
mocks.wsReset.mockImplementation(() => { order.push("ws") })
mocks.streamReset.mockImplementation(() => { order.push("stream") })
+ mocks.disposeReconciliation.mockImplementation(() => { order.push("reconcile") })
hook.queryClient.clear.mockImplementation(() => { order.push("query") })
mocks.clearCache.mockImplementation(async () => { order.push("cache"); throw new Error("cache") })
mocks.signOut.mockImplementation(async () => { order.push("signOut") })
hook.router.push = (href: string) => { order.push(`push:${href}`) }
await act(async () => hook.current.userSettingsProps.onLogout())
- expect(order).toEqual(["cancel", "community", "ws", "stream", "query", "cache", "signOut", "push:/sign-in"])
+ expect(order).toEqual(["cancel", "community", "ws", "stream", "reconcile", "query", "cache", "signOut", "push:/sign-in"])
order.length = 0
mocks.clearCache.mockResolvedValue(undefined)
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index 592d783cf..c8fa273e3 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -19,6 +19,8 @@ import { resolveProfilePresence } from "@/lib/community/presence"
import { avatarInitial } from "@/lib/community/avatar"
import { signOut } from "@/lib/auth-client"
import { clearPersistedCache } from "@/lib/query-persister"
+import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"
+import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"
import { useCommunityStore } from "@/stores/community"
import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"
import { useMessageStreamStore } from "@/stores/community/message-stream"
@@ -250,6 +252,8 @@ export function useShellProfileController({
useCommunityStore.getState().reset()
useCommunityWsStore.getState().reset()
useMessageStreamStore.getState().resetAll()
+ disposeReadCoordinator(queryClient)
+ disposeAccountReadStateReconciliation(queryClient)
queryClient.clear()
await clearPersistedCache(currentUser.id).catch(() => {})
await signOut()
diff --git a/src/web/src/hooks/community/community-ws/read-state-events.test.ts b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
new file mode 100644
index 000000000..47b6c4ded
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
@@ -0,0 +1,149 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+
+const apiFetch = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetch(...args),
+}))
+
+import { dispatchCommunityWsEvent } from "./registry"
+import type { CommunityWsDispatchContext } from "./handler-context"
+
+function context(queryClient: QueryClient): CommunityWsDispatchContext {
+ return {
+ deliveryMode: "single",
+ queryClient,
+ communityStore: {} as CommunityWsDispatchContext["communityStore"],
+ wsStore: {} as CommunityWsDispatchContext["wsStore"],
+ sub: {},
+ viewerUserIdRef: { current: "u1" },
+ matchesFocus: () => false,
+ scheduleInboxInvalidate: vi.fn(),
+ }
+}
+
+describe("same-account read-state WS events", () => {
+ let queryClient: QueryClient
+
+ beforeEach(() => {
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ apiFetch.mockReset()
+ })
+
+ it("pulls and projects the authoritative replacement for an exact-next hint", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 2,
+ readStates: [],
+ })
+ queryClient.setQueryData(communityKeys.dmReadStateSnapshot("dm1"), {
+ lastReadMessageId: null,
+ lastReadAt: null,
+ lastReadSeq: 0,
+ })
+
+ apiFetch.mockResolvedValue({
+ revision: 3,
+ readStates: [{
+ channelId: "dm1",
+ lastReadMessageId: "m4",
+ lastReadAt: "2026-08-24T00:00:04.000Z",
+ lastReadSeq: 4,
+ }],
+ })
+ dispatchCommunityWsEvent({
+ type: "community:read_state.advanced",
+ revision: 3,
+ inboxChanged: true,
+ }, context(queryClient))
+
+ await vi.waitFor(() => expect(queryClient.getQueryData(
+ communityKeys.dmReadStateSnapshot("dm1"),
+ )).toMatchObject({
+ lastReadMessageId: "m4",
+ lastReadSeq: 4,
+ }))
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("repairs a revision gap from the authoritative snapshot", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 2,
+ readStates: [],
+ })
+ apiFetch.mockResolvedValue({
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m8",
+ lastReadAt: "2026-08-24T00:00:08.000Z",
+ lastReadSeq: 8,
+ }],
+ })
+
+ dispatchCommunityWsEvent({
+ type: "community:read_state.advanced",
+ revision: 5,
+ inboxChanged: true,
+ }, context(queryClient))
+
+ await vi.waitFor(() => expect(queryClient.getQueryData(
+ communityKeys.accountReadStateSnapshot(),
+ )).toMatchObject({ revision: 5 }))
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("pulls one full read-all replacement and ignores its stale replay", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 7,
+ readStates: [],
+ })
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), { lastReadSeq: 0 })
+
+ apiFetch.mockResolvedValue({
+ revision: 8,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m8",
+ lastReadAt: "2026-08-24T00:00:08.000Z",
+ lastReadSeq: 8,
+ }],
+ })
+
+ const event = {
+ type: "community:inbox.changed",
+ revision: 8,
+ inboxChanged: true,
+ reason: "read_all",
+ } as const
+ dispatchCommunityWsEvent(event, context(queryClient))
+ await vi.waitFor(() => expect(queryClient.getQueryData(
+ communityKeys.channelReadStateSnapshot("c1"),
+ )).toMatchObject({
+ lastReadSeq: 8,
+ }))
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+
+ dispatchCommunityWsEvent(event, context(queryClient))
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("absorbs an authoritative repair failure after receiving a newer hint", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 2,
+ readStates: [],
+ })
+ apiFetch.mockRejectedValue(new Error("temporary snapshot failure"))
+
+ dispatchCommunityWsEvent({
+ type: "community:read_state.advanced",
+ revision: 3,
+ inboxChanged: true,
+ }, context(queryClient))
+
+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ await Promise.resolve()
+ expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
+ .toMatchObject({ revision: 2 })
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
new file mode 100644
index 000000000..019e328b3
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
@@ -0,0 +1,444 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryClient, QueryObserver } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+
+const apiFetch = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetch(...args),
+}))
+
+import {
+ disposeAccountReadStateReconciliation,
+ projectReadStateEnvelope,
+ reconcileAccountReadState,
+ type AccountReadStateSnapshot,
+} from "./read-state-reconciliation"
+
+describe("account read-state reconciliation", () => {
+ let queryClient: QueryClient
+
+ beforeEach(() => {
+ vi.useRealTimers()
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ apiFetch.mockReset()
+ })
+
+ it("treats every newer bounded hint as an authoritative-snapshot gap", () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 6,
+ readStates: [],
+ })
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 6,
+ inboxChanged: true,
+ })).toBe("stale")
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 7,
+ inboxChanged: true,
+ })).toBe("gap")
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 8,
+ inboxChanged: true,
+ })).toBe("gap")
+ queryClient.removeQueries({ queryKey: communityKeys.accountReadStateSnapshot() })
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 1,
+ inboxChanged: true,
+ })).toBe("gap")
+ })
+
+ it("loads the authoritative full replacement, including regression and removal", async () => {
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), { lastReadSeq: 1 })
+ queryClient.setQueryData(communityKeys.dmReadStateSnapshot("dm1"), { lastReadSeq: 2 })
+ apiFetch.mockResolvedValue({
+ revision: 10,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m0",
+ lastReadAt: "2026-08-24T00:00:00.000Z",
+ lastReadSeq: 0,
+ }],
+ })
+
+ await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
+ expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/read-state", expect.objectContaining({ signal: expect.any(AbortSignal) }))
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1"))).toMatchObject({
+ lastReadMessageId: "m0",
+ lastReadSeq: 0,
+ })
+ expect(queryClient.getQueryData(communityKeys.dmReadStateSnapshot("dm1"))).toEqual({
+ lastReadMessageId: null,
+ lastReadAt: null,
+ lastReadSeq: 0,
+ })
+ })
+
+ it("reprojects leaf caches when a lifecycle read returns the current revision", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 10,
+ readStates: [],
+ })
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("late"), {
+ lastReadMessageId: null,
+ lastReadAt: null,
+ lastReadSeq: 0,
+ })
+ apiFetch.mockResolvedValue({
+ revision: 10,
+ readStates: [{
+ channelId: "late",
+ lastReadMessageId: "m3",
+ lastReadAt: "2026-08-24T00:00:03.000Z",
+ lastReadSeq: 3,
+ }],
+ })
+
+ await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
+
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("late")))
+ .toMatchObject({ lastReadMessageId: "m3", lastReadSeq: 3 })
+ })
+
+ it("invalidates every cached concrete server detail after applying a snapshot", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 1,
+ readStates: [],
+ })
+ queryClient.setQueryData(communityKeys.server("server-1"), { id: "server-1" })
+ apiFetch.mockResolvedValue({ revision: 2, readStates: [] })
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")
+
+ await reconcileAccountReadState(queryClient, { targetRevision: 2 })
+
+ expect(invalidate).toHaveBeenCalledWith(
+ { queryKey: communityKeys.server("server-1"), exact: true, refetchType: "active" },
+ { throwOnError: true, cancelRefetch: true },
+ )
+ })
+
+ it("deduplicates concurrent lifecycle and gap reconciliations per query client", async () => {
+ let release!: (snapshot: AccountReadStateSnapshot) => void
+ apiFetch.mockReturnValue(new Promise<AccountReadStateSnapshot>((resolve) => {
+ release = resolve
+ }))
+
+ const first = reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
+ const second = reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+
+ release({ revision: 3, readStates: [] })
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ { revision: 3, readStates: [] },
+ { revision: 3, readStates: [] },
+ ])
+ })
+
+ it("does not lose a live revision behind a cold auth snapshot in flight", async () => {
+ let releaseAuth!: (snapshot: AccountReadStateSnapshot) => void
+ let releaseFresh!: (snapshot: AccountReadStateSnapshot) => void
+ apiFetch
+ .mockReturnValueOnce(new Promise<AccountReadStateSnapshot>((resolve) => {
+ releaseAuth = resolve
+ }))
+ .mockReturnValueOnce(new Promise<AccountReadStateSnapshot>((resolve) => {
+ releaseFresh = resolve
+ }))
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), { lastReadSeq: 0 })
+ queryClient.setQueryData(communityKeys.dmReadStateSnapshot("removed"), { lastReadSeq: 4 })
+
+ const auth = reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 5,
+ inboxChanged: true,
+ })).toBe("gap")
+ const live = reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+
+ releaseAuth({ revision: 4, readStates: [] })
+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
+ releaseFresh({
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m5",
+ lastReadAt: "2026-08-24T00:00:05.000Z",
+ lastReadSeq: 5,
+ }],
+ })
+
+ await expect(Promise.all([auth, live])).resolves.toEqual([
+ {
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m5",
+ lastReadAt: "2026-08-24T00:00:05.000Z",
+ lastReadSeq: 5,
+ }],
+ },
+ {
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m5",
+ lastReadAt: "2026-08-24T00:00:05.000Z",
+ lastReadSeq: 5,
+ }],
+ },
+ ])
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1"))).toMatchObject({
+ lastReadMessageId: "m5",
+ lastReadSeq: 5,
+ })
+ expect(queryClient.getQueryData(communityKeys.dmReadStateSnapshot("removed"))).toEqual({
+ lastReadMessageId: null,
+ lastReadAt: null,
+ lastReadSeq: 0,
+ })
+ })
+
+ it("immediately refetches when a successful snapshot remains below the live target", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ apiFetch
+ .mockResolvedValueOnce({ revision: 4, readStates: [] })
+ .mockResolvedValueOnce({ revision: 5, readStates: [] })
+
+ await expect(reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })).resolves.toEqual({ revision: 5, readStates: [] })
+
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("retains a live target after a transient snapshot failure and lets a later caller take over", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), {
+ lastReadMessageId: null,
+ lastReadAt: null,
+ lastReadSeq: 0,
+ })
+ apiFetch
+ .mockRejectedValueOnce(new Error("temporary primary failure"))
+ .mockResolvedValueOnce({
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m5",
+ lastReadAt: "2026-08-24T00:00:05.000Z",
+ lastReadSeq: 5,
+ }],
+ })
+
+ await expect(reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })).rejects.toThrow("temporary primary failure")
+
+ await expect(reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })).resolves.toMatchObject({ revision: 5 })
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ .toMatchObject({ lastReadSeq: 5 })
+ })
+
+ it("automatically retries a retained target after the bounded initial backoff", async () => {
+ vi.useFakeTimers()
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ apiFetch
+ .mockRejectedValueOnce(new Error("temporary primary failure"))
+ .mockResolvedValueOnce({ revision: 5, readStates: [] })
+
+ await expect(reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })).rejects.toThrow("temporary primary failure")
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+
+ await vi.advanceTimersByTimeAsync(100)
+ await vi.waitFor(() => expect(queryClient.getQueryData(
+ communityKeys.accountReadStateSnapshot(),
+ )).toMatchObject({ revision: 5 }))
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ vi.useRealTimers()
+ })
+
+ it("cancels retained retry work on exit without another GET or projection", async () => {
+ vi.useFakeTimers()
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("c1"), {
+ lastReadMessageId: null,
+ lastReadAt: null,
+ lastReadSeq: 0,
+ })
+ apiFetch
+ .mockRejectedValueOnce(new Error("temporary primary failure"))
+ .mockResolvedValueOnce({
+ revision: 5,
+ readStates: [{
+ channelId: "c1",
+ lastReadMessageId: "m5",
+ lastReadAt: "2026-08-24T00:00:05.000Z",
+ lastReadSeq: 5,
+ }],
+ })
+
+ await expect(reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })).rejects.toThrow("temporary primary failure")
+ disposeAccountReadStateReconciliation(queryClient)
+ await vi.advanceTimersByTimeAsync(10_000)
+
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
+ .toMatchObject({ revision: 4 })
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("c1")))
+ .toMatchObject({ lastReadSeq: 0 })
+ await expect(reconcileAccountReadState(queryClient, {
+ targetRevision: 5,
+ })).rejects.toThrow("account read-state reconciliation disposed")
+ vi.useRealTimers()
+ })
+
+ it("aborts and fences an active primary request on exit", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ let release!: (snapshot: AccountReadStateSnapshot) => void
+ let requestSignal: AbortSignal | undefined
+ apiFetch.mockImplementationOnce((_path: string, options: { signal?: AbortSignal }) => {
+ requestSignal = options.signal
+ return new Promise<AccountReadStateSnapshot>((resolve) => {
+ release = resolve
+ })
+ })
+
+ const worker = reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })
+ expect(requestSignal?.aborted).toBe(false)
+ disposeAccountReadStateReconciliation(queryClient)
+ expect(requestSignal?.aborted).toBe(true)
+ release({ revision: 5, readStates: [] })
+
+ await expect(worker).rejects.toThrow("account read-state reconciliation disposed")
+ expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
+ .toMatchObject({ revision: 4 })
+ })
+
+ it("retains a real active-query refetch failure until same-revision takeover succeeds", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ apiFetch.mockResolvedValue({
+ revision: 5,
+ readStates: [],
+ })
+ let inboxFetches = 0
+ const inboxObserver = new QueryObserver(queryClient, {
+ queryKey: communityKeys.inbox(),
+ queryFn: async () => {
+ inboxFetches += 1
+ if (inboxFetches === 2) throw new Error("temporary inbox failure")
+ return []
+ },
+ })
+ const unsubscribe = inboxObserver.subscribe(() => undefined)
+ await vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success"))
+
+ await expect(reconcileAccountReadState(queryClient, {
+ targetRevision: 5,
+ })).rejects.toThrow("read-state surface reconciliation failed")
+ expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
+ .toMatchObject({ revision: 5 })
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 5,
+ inboxChanged: true,
+ })).toBe("gap")
+
+ await expect(reconcileAccountReadState(queryClient, {
+ targetRevision: 5,
+ })).resolves.toMatchObject({ revision: 5 })
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(inboxFetches).toBe(3)
+ expect(inboxObserver.getCurrentResult()).toMatchObject({
+ status: "success",
+ data: [],
+ })
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 5,
+ inboxChanged: true,
+ })).toBe("stale")
+ unsubscribe()
+ })
+
+ it("coalesces repeated live hints into one retry worker without a request storm", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ let release!: (snapshot: AccountReadStateSnapshot) => void
+ apiFetch.mockReturnValue(new Promise<AccountReadStateSnapshot>((resolve) => {
+ release = resolve
+ }))
+
+ const workers = Array.from({ length: 12 }, () => reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ }))
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ release({ revision: 5, readStates: [] })
+ await expect(Promise.all(workers)).resolves.toHaveLength(12)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("runs a second derived pass when a newer hint arrives during invalidation", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ apiFetch
+ .mockResolvedValueOnce({ revision: 5, readStates: [] })
+ .mockResolvedValueOnce({ revision: 6, readStates: [] })
+ let releaseSurface!: () => void
+ const surfaceGate = new Promise<void>((resolve) => {
+ releaseSurface = resolve
+ })
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")
+ invalidate.mockReturnValueOnce(surfaceGate).mockResolvedValue(undefined)
+
+ const first = reconcileAccountReadState(queryClient, { targetRevision: 5 })
+ await vi.waitFor(() => expect(invalidate).toHaveBeenCalledTimes(3))
+ const second = reconcileAccountReadState(queryClient, { targetRevision: 6 })
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+
+ releaseSurface()
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ { revision: 6, readStates: [] },
+ { revision: 6, readStates: [] },
+ ])
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(invalidate).toHaveBeenCalledTimes(6)
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
new file mode 100644
index 000000000..c4b44b943
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
@@ -0,0 +1,366 @@
+import { notifyManager, type QueryClient, type QueryKey } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import { projectReadCoordinatorSnapshot } from "@/hooks/community/read-coordinator-snapshot-projection"
+
+type AccountReadState = {
+ channelId: string
+ lastReadMessageId: string | null
+ lastReadAt: string
+ lastReadSeq: number
+}
+
+export type AccountReadStateSnapshot = {
+ revision: number
+ readStates: AccountReadState[]
+}
+
+export type ReadStateEnvelope = {
+ revision: number
+ inboxChanged: true
+}
+
+type ReconciliationState = {
+ highestPendingTargetRevision: number | null
+ snapshotRequestedGeneration: number
+ snapshotCompletedGeneration: number
+ surfaceRequestedGeneration: number
+ surfaceCompletedGeneration: number
+ worker: Promise<AccountReadStateSnapshot> | null
+ retryTimer: ReturnType<typeof setTimeout> | null
+ retryDelayMs: number
+ requestController: AbortController | null
+ epoch: number
+ disposed: boolean
+}
+
+const INITIAL_RETRY_DELAY_MS = 100
+const MAX_RETRY_DELAY_MS = 5_000
+const reconciliationStates = new WeakMap<QueryClient, ReconciliationState>()
+const disposedReconciliationClients = new WeakSet<QueryClient>()
+
+const emptyReadState = {
+ lastReadMessageId: null,
+ lastReadAt: null,
+ lastReadSeq: 0,
+}
+
+function cachedReadStateTarget(key: QueryKey) {
+ if (
+ key[0] === "community"
+ && (key[1] === "channel" || key[1] === "dm")
+ && typeof key[2] === "string"
+ && key[3] === "read-state-snapshot"
+ ) {
+ return { kind: key[1], channelId: key[2] }
+ }
+ return null
+}
+
+function projectReadStateRows(queryClient: QueryClient, snapshot: AccountReadStateSnapshot) {
+ const byChannel = new Map(snapshot.readStates.map((row) => [row.channelId, row]))
+ for (const query of queryClient.getQueryCache().getAll()) {
+ const target = cachedReadStateTarget(query.queryKey)
+ if (!target) continue
+ const row = byChannel.get(target.channelId)
+ queryClient.setQueryData(query.queryKey, row
+ ? {
+ lastReadMessageId: row.lastReadMessageId,
+ lastReadAt: row.lastReadAt,
+ lastReadSeq: row.lastReadSeq,
+ }
+ : emptyReadState)
+ }
+}
+
+function applyAccountReadStateSnapshot(
+ queryClient: QueryClient,
+ snapshot: AccountReadStateSnapshot,
+) {
+ const current = queryClient.getQueryData<AccountReadStateSnapshot>(
+ communityKeys.accountReadStateSnapshot(),
+ )
+ if (current && snapshot.revision < current.revision) return "stale" as const
+ if (current?.revision === snapshot.revision) {
+ // Same revision is the same authoritative account snapshot by contract.
+ // Re-project leaf caches in case one mounted after the first application,
+ // but do not trigger a second round of derived-surface refetches when
+ // concurrent auth/live reconciliations joined the same HTTP request.
+ projectReadStateRows(queryClient, snapshot)
+ projectReadCoordinatorSnapshot(queryClient, snapshot)
+ return "stale" as const
+ }
+ notifyManager.batch(() => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), snapshot)
+ projectReadStateRows(queryClient, snapshot)
+ projectReadCoordinatorSnapshot(queryClient, snapshot)
+ })
+ return "applied" as const
+}
+
+async function invalidateReadStateSurfaces(queryClient: QueryClient) {
+ const serverIds = new Set<string>()
+ for (const query of queryClient.getQueryCache().getAll()) {
+ const key = query.queryKey
+ if (
+ key[0] === "community"
+ && key[1] === "servers"
+ && typeof key[2] === "string"
+ && key[2] !== "__none__"
+ && key.length === 3
+ ) serverIds.add(key[2])
+ }
+ const refetchOptions = { throwOnError: true, cancelRefetch: true }
+ const settled = await Promise.allSettled([
+ queryClient.invalidateQueries(
+ { queryKey: communityKeys.inbox(), refetchType: "active" },
+ refetchOptions,
+ ),
+ queryClient.invalidateQueries(
+ { queryKey: communityKeys.dms(), refetchType: "active" },
+ refetchOptions,
+ ),
+ queryClient.invalidateQueries(
+ { queryKey: communityKeys.servers(), exact: true, refetchType: "active" },
+ refetchOptions,
+ ),
+ ...[...serverIds].map((serverId) => queryClient.invalidateQueries({
+ queryKey: communityKeys.server(serverId),
+ exact: true,
+ refetchType: "active",
+ }, refetchOptions)),
+ ])
+ if (settled.some((result) => result.status === "rejected")) {
+ throw new Error("read-state surface reconciliation failed")
+ }
+}
+
+export async function reconcileAccountReadState(
+ queryClient: QueryClient,
+ options: { invalidateSurfaces?: boolean; targetRevision?: number } = {},
+) {
+ if (disposedReconciliationClients.has(queryClient)) {
+ throw new Error("account read-state reconciliation disposed")
+ }
+ const state = getReconciliationState(queryClient)
+ const currentRevision = cachedAccountRevision(queryClient)
+ const targetRevision = options.targetRevision
+ const hadSnapshotWork = hasSnapshotWork(state, currentRevision)
+
+ if (targetRevision === undefined) {
+ // Coalesce concurrent lifecycle callers into the already-pending primary
+ // read, but make a later lifecycle event take ownership of a failed worker
+ // whose target/dirty state is still queued.
+ if (!hadSnapshotWork) state.snapshotRequestedGeneration += 1
+ } else if (
+ targetRevision > currentRevision
+ && (state.highestPendingTargetRevision === null
+ || targetRevision > state.highestPendingTargetRevision)
+ ) {
+ state.highestPendingTargetRevision = targetRevision
+ state.snapshotRequestedGeneration += 1
+ }
+
+ if (
+ options.invalidateSurfaces !== false
+ && state.snapshotRequestedGeneration > state.surfaceRequestedGeneration
+ ) {
+ // Bind derived work to the authoritative snapshot generation that caused
+ // it. Callers joining the same primary read coalesce, while a newer hint
+ // arriving during invalidation advances both generations and therefore
+ // receives a second surface pass after its newer snapshot lands.
+ state.surfaceRequestedGeneration = state.snapshotRequestedGeneration
+ }
+
+ if (state.retryTimer !== null) {
+ clearTimeout(state.retryTimer)
+ state.retryTimer = null
+ }
+ return ensureReconciliationWorker(queryClient, state)
+}
+
+function getReconciliationState(queryClient: QueryClient) {
+ const current = reconciliationStates.get(queryClient)
+ if (current) return current
+ const created: ReconciliationState = {
+ highestPendingTargetRevision: null,
+ snapshotRequestedGeneration: 0,
+ snapshotCompletedGeneration: 0,
+ surfaceRequestedGeneration: 0,
+ surfaceCompletedGeneration: 0,
+ worker: null,
+ retryTimer: null,
+ retryDelayMs: INITIAL_RETRY_DELAY_MS,
+ requestController: null,
+ epoch: 0,
+ disposed: false,
+ }
+ reconciliationStates.set(queryClient, created)
+ return created
+}
+
+function cachedAccountRevision(queryClient: QueryClient) {
+ return queryClient.getQueryData<AccountReadStateSnapshot>(
+ communityKeys.accountReadStateSnapshot(),
+ )?.revision ?? -1
+}
+
+function hasSnapshotWork(state: ReconciliationState, currentRevision: number) {
+ return (
+ state.snapshotCompletedGeneration < state.snapshotRequestedGeneration
+ || (state.highestPendingTargetRevision !== null
+ && currentRevision < state.highestPendingTargetRevision)
+ )
+}
+
+function hasSurfaceWork(state: ReconciliationState) {
+ return state.surfaceCompletedGeneration < state.surfaceRequestedGeneration
+}
+
+function hasReconciliationWork(queryClient: QueryClient, state: ReconciliationState) {
+ return hasSnapshotWork(state, cachedAccountRevision(queryClient)) || hasSurfaceWork(state)
+}
+
+function scheduleReconciliationRetry(queryClient: QueryClient, state: ReconciliationState) {
+ if (
+ state.disposed
+ || state.retryTimer !== null
+ || !hasReconciliationWork(queryClient, state)
+ ) return
+ const delay = state.retryDelayMs
+ state.retryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
+ state.retryTimer = setTimeout(() => {
+ state.retryTimer = null
+ void ensureReconciliationWorker(queryClient, state).catch(() => undefined)
+ }, delay)
+}
+
+function ensureReconciliationWorker(queryClient: QueryClient, state: ReconciliationState) {
+ if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
+ if (state.worker) return state.worker
+ const worker = runReconciliationWorker(queryClient, state).finally(() => {
+ if (state.worker === worker) state.worker = null
+ if (hasReconciliationWork(queryClient, state)) {
+ scheduleReconciliationRetry(queryClient, state)
+ }
+ })
+ state.worker = worker
+ return worker
+}
+
+async function runReconciliationWorker(
+ queryClient: QueryClient,
+ state: ReconciliationState,
+): Promise<AccountReadStateSnapshot> {
+ const epoch = state.epoch
+ while (true) {
+ assertReconciliationActive(queryClient, state, epoch)
+ const currentRevision = cachedAccountRevision(queryClient)
+ if (hasSnapshotWork(state, currentRevision)) {
+ const requestGeneration = state.snapshotRequestedGeneration
+ let snapshot: AccountReadStateSnapshot
+ try {
+ snapshot = await startAccountReadStateRequest(state)
+ } catch (error) {
+ scheduleReconciliationRetry(queryClient, state)
+ throw error
+ }
+ assertReconciliationActive(queryClient, state, epoch)
+ applyAccountReadStateSnapshot(queryClient, snapshot)
+ state.snapshotCompletedGeneration = Math.max(
+ state.snapshotCompletedGeneration,
+ requestGeneration,
+ )
+ const appliedRevision = cachedAccountRevision(queryClient)
+ if (
+ state.highestPendingTargetRevision !== null
+ && appliedRevision >= state.highestPendingTargetRevision
+ ) {
+ state.highestPendingTargetRevision = null
+ }
+ // If this primary read was older than a live target, or another caller
+ // arrived while it was in flight, loop immediately and issue a genuinely
+ // fresh request. No timer/backoff is needed for a successful stale read.
+ continue
+ }
+
+ if (hasSurfaceWork(state)) {
+ const surfaceGeneration = state.surfaceRequestedGeneration
+ try {
+ await invalidateReadStateSurfaces(queryClient)
+ } catch (error) {
+ scheduleReconciliationRetry(queryClient, state)
+ throw error
+ }
+ assertReconciliationActive(queryClient, state, epoch)
+ state.surfaceCompletedGeneration = Math.max(
+ state.surfaceCompletedGeneration,
+ surfaceGeneration,
+ )
+ continue
+ }
+
+ const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
+ communityKeys.accountReadStateSnapshot(),
+ )
+ if (!snapshot) throw new Error("account read-state reconciliation produced no snapshot")
+ state.retryDelayMs = INITIAL_RETRY_DELAY_MS
+ return snapshot
+ }
+}
+
+function assertReconciliationActive(
+ queryClient: QueryClient,
+ state: ReconciliationState,
+ epoch: number,
+) {
+ if (
+ state.disposed
+ || state.epoch !== epoch
+ || reconciliationStates.get(queryClient) !== state
+ ) throw new Error("account read-state reconciliation disposed")
+}
+
+function startAccountReadStateRequest(state: ReconciliationState) {
+ const controller = new AbortController()
+ state.requestController = controller
+ return apiFetch<AccountReadStateSnapshot>(
+ "/api/community/users/me/read-state",
+ { signal: controller.signal },
+ ).finally(() => {
+ if (state.requestController === controller) state.requestController = null
+ })
+}
+
+export function disposeAccountReadStateReconciliation(queryClient: QueryClient) {
+ disposedReconciliationClients.add(queryClient)
+ const state = reconciliationStates.get(queryClient)
+ if (!state || state.disposed) return
+ state.disposed = true
+ state.epoch += 1
+ state.highestPendingTargetRevision = null
+ state.snapshotCompletedGeneration = state.snapshotRequestedGeneration
+ state.surfaceCompletedGeneration = state.surfaceRequestedGeneration
+ if (state.retryTimer !== null) {
+ clearTimeout(state.retryTimer)
+ state.retryTimer = null
+ }
+ state.requestController?.abort()
+ state.requestController = null
+}
+
+export function projectReadStateEnvelope(
+ queryClient: QueryClient,
+ envelope: ReadStateEnvelope,
+) {
+ const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
+ communityKeys.accountReadStateSnapshot(),
+ )
+ if (!snapshot) return "gap" as const
+ const state = reconciliationStates.get(queryClient)
+ if (state && hasSurfaceWork(state) && envelope.revision <= snapshot.revision) {
+ return "gap" as const
+ }
+ if (envelope.revision <= snapshot.revision) return "stale" as const
+ return "gap" as const
+}
diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.ts
index b4af15178..80b004a64 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts
@@ -338,8 +338,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 900)
expect(summary).toMatchObject({
- policyCount: 13,
- successCount: 12,
+ policyCount: 14,
+ successCount: 13,
failureCount: 1,
reconnectDurationMs: 900,
})
@@ -369,7 +369,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 10)
useCommunityWsStore.setState({ resetPresence: originalResetPresence })
- expect(summary).toMatchObject({ policyCount: 13, successCount: 12, failureCount: 1 })
+ expect(summary).toMatchObject({ policyCount: 14, successCount: 13, failureCount: 1 })
expect(telemetry.failure).toHaveBeenCalledWith({
policy: "presence-overlay",
reason: "sync-throw",
@@ -461,13 +461,15 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(started).not.toContain(JSON.stringify([...communityKeys.all, "bot"]))
gates.get(JSON.stringify(communityKeys.friends()))!.resolve()
- await flushMicrotasks()
- expect(started).toContain(JSON.stringify(communityKeys.machines()))
+ await vi.waitFor(() => {
+ expect(started).toContain(JSON.stringify(communityKeys.machines()))
+ })
expect(started).not.toContain(JSON.stringify([...communityKeys.all, "bot"]))
gates.get(JSON.stringify(communityKeys.machines()))!.resolve()
- await flushMicrotasks()
- expect(started).toContain(JSON.stringify([...communityKeys.all, "bot"]))
+ await vi.waitFor(() => {
+ expect(started).toContain(JSON.stringify([...communityKeys.all, "bot"]))
+ })
for (const gate of gates.values()) gate.resolve()
await work
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index e70e3f447..32ed2b552 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -6,6 +6,7 @@ import { invalidateForumSidebarBaseExact } from "@/hooks/community/use-forum-sid
import { clearAllTypingIndicators } from "@/hooks/community/community-ws/typing"
import { communityWsReconnectPolicies } from "@/hooks/community/community-ws/registry"
import { reconcileFocusedMessageQueries } from "@/hooks/community/community-ws/reconnect-messages"
+import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"
import {
trackCommunityWsReconcileComplete,
trackCommunityWsReconcileFailure,
@@ -185,6 +186,9 @@ function policyExecutors(queryClient: QueryClient): Record<CommunityWsReconcileP
])
if (settled.some((result) => result.status === "rejected")) throw new Error("inbox reconciliation failed")
},
+ "cached-read-state": async () => {
+ await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
+ },
"all-cached-servers": async () => {
const serverIds = cachedServerIds(queryKeys)
const settled = await Promise.allSettled([
diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.ts
index ca2c932b2..3843dcac8 100644
--- a/src/web/src/hooks/community/community-ws/registry.test.ts
+++ b/src/web/src/hooks/community/community-ws/registry.test.ts
@@ -48,7 +48,9 @@ vi.mock("./membership-events", () => ({
}))
vi.mock("./social-events", () => ({
handleFriendEvent: handlers.handleFriendEvent,
+ handleInboxChanged: handlers.handleInboxChanged,
handleMentionCreate: handlers.handleMentionCreate,
+ handleReadStateAdvanced: handlers.handleReadStateAdvanced,
handleUnreadBump: handlers.handleUnreadBump,
}))
vi.mock("./presence-machine-events", () => ({
@@ -75,10 +77,10 @@ function dispatchContext(queryClient = new QueryClient()): CommunityWsDispatchCo
}
describe("community WebSocket registry", () => {
- it("has exactly one entry for each of the 41 runtime event types", () => {
+ it("has exactly one entry for each of the 43 runtime event types", () => {
const eventTypes = Object.values(WS_EVENTS).sort()
const registryTypes = Object.keys(communityWsRegistry).sort()
- expect(eventTypes).toHaveLength(41)
+ expect(eventTypes).toHaveLength(43)
expect(registryTypes).toEqual(eventTypes)
})
@@ -90,8 +92,8 @@ describe("community WebSocket registry", () => {
})
it("deduplicates the complete policy set", () => {
- expect(communityWsReconnectPolicies).toHaveLength(13)
- expect(new Set(communityWsReconnectPolicies).size).toBe(13)
+ expect(communityWsReconnectPolicies).toHaveLength(14)
+ expect(new Set(communityWsReconnectPolicies).size).toBe(14)
})
it.each([
diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.ts
index 40a342dac..819a854a1 100644
--- a/src/web/src/hooks/community/community-ws/registry.ts
+++ b/src/web/src/hooks/community/community-ws/registry.ts
@@ -30,7 +30,9 @@ import {
} from "@/hooks/community/community-ws/membership-events"
import {
handleFriendEvent,
+ handleInboxChanged,
handleMentionCreate,
+ handleReadStateAdvanced,
handleUnreadBump,
} from "@/hooks/community/community-ws/social-events"
import {
@@ -86,6 +88,8 @@ export const communityWsRegistry = {
"community:invite.create": { handler: handleInviteCreate, reconnectPolicies: ["all-cached-servers"] },
"community:mention.create": { handler: handleMentionCreate, reconnectPolicies: ["inbox-dms"] },
"community:unread.bump": { handler: handleUnreadBump, reconnectPolicies: ["inbox-dms", "all-cached-servers"] },
+ "community:read_state.advanced": { handler: handleReadStateAdvanced, reconnectPolicies: ["cached-read-state", "inbox-dms", "all-cached-servers"] },
+ "community:inbox.changed": { handler: handleInboxChanged, reconnectPolicies: ["cached-read-state", "inbox-dms", "all-cached-servers"] },
"community:presence.update": { handler: (event) => handlePresenceUpdate(event), reconnectPolicies: ["presence-overlay", "all-cached-servers"] },
"community:status.update": { handler: (event) => handleStatusUpdate(event), reconnectPolicies: ["status-overlay"] },
"community:machine.created": { handler: handleMachineCreated, reconnectPolicies: ["machines"] },
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index 4d0189867..001aa4dbd 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -5,6 +5,8 @@ import type {
CommunityFriendRemove,
CommunityFriendRequest,
CommunityMentionCreate,
+ CommunityInboxChanged,
+ CommunityReadStateAdvanced,
CommunityWsEvent,
} from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
@@ -23,6 +25,36 @@ import {
invalidateInbox,
invalidateServersList,
} from "./invalidation-projections"
+import {
+ projectReadStateEnvelope,
+ reconcileAccountReadState,
+} from "./read-state-reconciliation"
+
+export function handleReadStateAdvanced(
+ event: CommunityReadStateAdvanced,
+ context: SocialEventContext,
+) {
+ applyReadStateEnvelope(event, context)
+}
+
+function applyReadStateEnvelope(
+ event: CommunityReadStateAdvanced | CommunityInboxChanged,
+ context: SocialEventContext,
+) {
+ const outcome = projectReadStateEnvelope(context.queryClient, event)
+ if (outcome === "gap") {
+ void reconcileAccountReadState(context.queryClient, {
+ targetRevision: event.revision,
+ }).catch(() => undefined)
+ }
+}
+
+export function handleInboxChanged(
+ event: CommunityInboxChanged,
+ context: SocialEventContext,
+) {
+ applyReadStateEnvelope(event, context)
+}
type CommunityUnreadBump = Extract<
CommunityWsEvent,
diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.ts
index 427650c5d..c87268f88 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -4,6 +4,19 @@ import { vi } from "vitest"
import type { UseUserWsOptions, UserWsConnectionPhase } from "@/lib/use-user-ws"
import { useMessageStreamStore } from "@/stores/community/message-stream"
+const communityApiFetch = vi.hoisted(() => vi.fn(async (...args: unknown[]) => {
+ const url = args[0]
+ if (url === "/api/community/users/me/read-state") {
+ return { revision: 0, readStates: [] }
+ }
+ throw new Error(`unexpected API fetch: ${url}`)
+}))
+
+vi.mock("@/lib/api/client", async () => {
+ const actual = await vi.importActual<typeof import("@/lib/api/client")>("@/lib/api/client")
+ return { ...actual, apiFetch: (...args: unknown[]) => communityApiFetch(...args) }
+})
+
type ShimCallback = (...args: unknown[]) => unknown
let refs: Map<string, { current: unknown }> = new Map()
@@ -112,6 +125,14 @@ function resetHarnessState() {
stableReconnectNow = vi.fn()
useUserWsCallCount = 0
markReadMutate.mockClear()
+ communityApiFetch.mockReset()
+ communityApiFetch.mockImplementation(async (...args: unknown[]) => {
+ const url = args[0]
+ if (url === "/api/community/users/me/read-state") {
+ return { revision: 0, readStates: [] }
+ }
+ throw new Error(`unexpected API fetch: ${url}`)
+ })
}
export async function mountHook(options?: { viewerUserId?: string | null } & Record<string, unknown>) {
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index 90c27242e..4cb62537e 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -883,430 +883,6 @@ describe("useCreateThread — patches parent message + invalidates threads", ()
})
})
-// ── useMarkChannelRead — the #13 debounce ─────────────────────────────────
-
-describe("useMarkChannelRead — #13 debounced read stampede", () => {
- // Drive mutationFn directly (bypassing runMutation) so the test doesn't
- // have to await 9 pending promises that intentionally never resolve —
- // the debounce coalesces them into one that fires the timer callback.
- it("10 rapid triggers collapse into ONE PUT /read after the debounce window", async () => {
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.useMarkChannelRead()
- const cfg = capturedConfig!
- // Fire 10 rapid triggers — each schedules (and cancels the previous)
- // debounce timer. Only the last one survives.
- for (let i = 0; i < 10; i++) {
- void cfg.mutationFn!({ channelId: "ch_1" })
- }
- // Nothing before the debounce window closes.
- expect(apiFetchMock.mock.calls.filter((c) => (c[1] as { method?: string })?.method === "PUT")).toHaveLength(
- 0,
- )
- await vi.advanceTimersByTimeAsync(500)
- const puts = apiFetchMock.mock.calls.filter((c) => (c[1] as { method?: string })?.method === "PUT")
- expect(puts).toHaveLength(1)
- expect(puts[0][0]).toBe("/api/community/channels/ch_1/read")
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("flushPendingReads() fires any pending PUT synchronously", async () => {
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.useMarkChannelRead()
- const cfg = capturedConfig!
- // Kick the debounce.
- void cfg.mutationFn!({ channelId: "ch_1" })
- // Flush before the 500ms window elapses — should fire the PUT now.
- mod.flushPendingReads()
- const puts = apiFetchMock.mock.calls.filter((c) => (c[1] as { method?: string })?.method === "PUT")
- expect(puts).toHaveLength(1)
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("mutationFn resolves synchronously — never hangs when flushed or re-invoked", async () => {
- // Regression: the old implementation wrapped setTimeout inside the
- // mutation Promise. A same-channel re-invoke cleared the timer, which
- // meant the resolve() was unreachable and the Promise hung forever.
- // The new design decouples the debounce from mutationFn — the returned
- // Promise resolves immediately, and the debounced work fires
- // independently via `scheduleMarkRead`'s onDone.
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.useMarkChannelRead()
- const cfg = capturedConfig!
- // Fire the mutation, then flush before the debounce window closes.
- const first = cfg.mutationFn!({ channelId: "ch_1" }) as Promise<void>
- // Same-channel re-invoke — old bug would strand the first Promise.
- const second = cfg.mutationFn!({ channelId: "ch_1" }) as Promise<void>
- mod.flushPendingReads()
- // Both Promises must have resolved (not thrown, not hung).
- await expect(first).resolves.toBeUndefined()
- await expect(second).resolves.toBeUndefined()
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("onDone (inbox invalidate) fires exactly once per PUT — even under flush", async () => {
- // Real timers here — we need Promise microtasks to drain naturally
- // after `apiFetch` resolves, so `onDone` (invalidateQueries) runs.
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.useMarkChannelRead()
- const cfg = capturedConfig!
- const spy = vi.spyOn(capturedQc, "invalidateQueries")
- // One mutation, then flush. `fire()` runs apiFetch → onDone chain.
- void cfg.mutationFn!({ channelId: "ch_1" })
- mod.flushPendingReads()
- // Drain microtasks — the `.then(onDone)` after apiFetch resolves.
- await Promise.resolve()
- await Promise.resolve()
- const inboxInvalidates = spy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "inbox"
- })
- expect(inboxInvalidates).toHaveLength(1)
- })
-
- it("onDone also invalidates communityKeys.servers() so the rail badge drops", async () => {
- // Marking a channel read clears its unread mentions on the server; the
- // rail badge is derived from the same aggregate, so it must refresh.
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.useMarkChannelRead()
- const cfg = capturedConfig!
- const spy = vi.spyOn(capturedQc, "invalidateQueries")
- void cfg.mutationFn!({ channelId: "ch_1" })
- mod.flushPendingReads()
- await Promise.resolve()
- await Promise.resolve()
- const serversInvalidates = spy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "servers"
- })
- expect(serversInvalidates).toHaveLength(1)
- })
-
- it("same-channel re-invoke within window collapses to a single PUT — old scheduling is subsumed", async () => {
- // Regression companion to the Promise-hang bug: verify the debounce
- // behavior itself still holds. A rapid burst on the same channel must
- // collapse to ONE PUT, and the pending map must not leak entries.
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.useMarkChannelRead()
- const cfg = capturedConfig!
- void cfg.mutationFn!({ channelId: "ch_1" })
- void cfg.mutationFn!({ channelId: "ch_1" })
- void cfg.mutationFn!({ channelId: "ch_1" })
- expect(apiFetchMock).not.toHaveBeenCalled()
- await vi.advanceTimersByTimeAsync(500)
- const puts = apiFetchMock.mock.calls.filter((c) => (c[1] as { method?: string })?.method === "PUT")
- expect(puts).toHaveLength(1)
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("useMarkChannelRead fires PUT with NO body — the mass mark-read path", async () => {
- // The extended `scheduleMarkRead` accepts an optional messageId. The
- // no-messageId call site (useMarkChannelRead → useMarkAllInboxRead)
- // must NOT send a body — the server treats absence as "mark whole
- // channel read at now".
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.useMarkChannelRead()
- const cfg = capturedConfig!
- void cfg.mutationFn!({ channelId: "ch_1" })
- await vi.advanceTimersByTimeAsync(500)
- const put = apiFetchMock.mock.calls.find(
- (c) => (c[1] as { method?: string })?.method === "PUT",
- )
- expect(put).toBeDefined()
- // No `body` key on the init.
- expect((put![1] as RequestInit).body).toBeUndefined()
- } finally {
- vi.useRealTimers()
- }
- })
-})
-
-// ── scheduleMarkRead — extended signature (with messageId body) ──────────
-describe("scheduleMarkRead — with messageId body", () => {
- it("posts { lastReadMessageId } when a messageId is passed", async () => {
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.scheduleMarkRead("ch_1", { messageId: "m_42", onDone: () => { } })
- await vi.advanceTimersByTimeAsync(500)
- const put = apiFetchMock.mock.calls.find(
- (c) => (c[1] as { method?: string })?.method === "PUT",
- )
- expect(put).toBeDefined()
- expect((put![1] as RequestInit).body).toBe(JSON.stringify({ lastReadMessageId: "m_42" }))
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("supersedes the pending messageId when a newer one arrives mid-window", async () => {
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.scheduleMarkRead("ch_1", { messageId: "m_stale", onDone: () => { } })
- // Fresh call within the window — the latest messageId wins.
- mod.scheduleMarkRead("ch_1", { messageId: "m_fresh", onDone: () => { } })
- await vi.advanceTimersByTimeAsync(500)
- const puts = apiFetchMock.mock.calls.filter(
- (c) => (c[1] as { method?: string })?.method === "PUT",
- )
- expect(puts).toHaveLength(1)
- expect((puts[0][1] as RequestInit).body).toBe(JSON.stringify({ lastReadMessageId: "m_fresh" }))
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("no messageId → no body (preserves the mass mark-read path)", async () => {
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- mod.scheduleMarkRead("ch_1", { onDone: () => { } })
- await vi.advanceTimersByTimeAsync(500)
- const put = apiFetchMock.mock.calls.find(
- (c) => (c[1] as { method?: string })?.method === "PUT",
- )
- expect((put![1] as RequestInit).body).toBeUndefined()
- } finally {
- vi.useRealTimers()
- }
- })
-})
-
-// ── useAdvanceChannelWatermark — thin wrapper for viewport advances ─────
-describe("useAdvanceChannelWatermark", () => {
- it("returns a callable that PUTs { lastReadMessageId } after the debounce", async () => {
- vi.useFakeTimers()
- try {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- const advance = mod.useAdvanceChannelWatermark()
- advance("ch_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/channels/ch_1/read")
- expect((put![1] as RequestInit).body).toBe(JSON.stringify({ lastReadMessageId: "m_42" }))
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("onDone invalidates inbox + servers after the PUT resolves", async () => {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod._resetPendingReads_forTesting()
- const advance = mod.useAdvanceChannelWatermark()
- const spy = vi.spyOn(capturedQc, "invalidateQueries")
- advance("ch_1", "m_42")
- mod.flushPendingReads()
- // Drain the `.then(onDone)` microtask chain.
- 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 serversCalls = spy.mock.calls.filter((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.length === 2 && key[1] === "servers"
- })
- expect(inboxCalls.length).toBeGreaterThanOrEqual(1)
- expect(serversCalls.length).toBeGreaterThanOrEqual(1)
- })
-})
-
-describe("useReadForumThreadFromInbox", () => {
- it("PUTs the exact opener target to the parent forum immediately", async () => {
- apiFetchMock.mockResolvedValue(undefined)
- const mod = await loadMod()
- mod.useReadForumThreadFromInbox()
-
- await runMutation({ parentChannelId: "forum_1", openerMessageId: "opener_42" })
-
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/forum_1/read", {
- method: "PUT",
- body: JSON.stringify({ lastReadMessageId: "opener_42" }),
- })
- })
-
- it("has no optimistic cache mutation and invalidates inbox + servers only after success", async () => {
- apiFetchMock.mockResolvedValue(undefined)
- const before = { servers: [{ serverId: "s1", channels: [{ channelId: "forum_1" }] }] }
- capturedQc.setQueryData(communityKeys.inboxUnreads(), before)
- const setSpy = vi.spyOn(capturedQc, "setQueryData")
- const invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")
- const mod = await loadMod()
- mod.useReadForumThreadFromInbox()
-
- await runMutation({ parentChannelId: "forum_1", openerMessageId: "opener_42" })
-
- expect(setSpy).not.toHaveBeenCalled()
- expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual(before)
- const invalidated = invalidateSpy.mock.calls.map((call) => call[0]?.queryKey)
- expect(invalidated).toContainEqual(communityKeys.inbox())
- expect(invalidated).toContainEqual(communityKeys.servers())
- })
-
- it("keeps cache intact, skips success invalidation, and toasts when the PUT fails", async () => {
- const error = new Error("parent read failed")
- apiFetchMock.mockRejectedValue(error)
- const before = { servers: [{ serverId: "s1", channels: [{ channelId: "forum_1" }] }] }
- capturedQc.setQueryData(communityKeys.inboxUnreads(), before)
- const setSpy = vi.spyOn(capturedQc, "setQueryData")
- const invalidateSpy = vi.spyOn(capturedQc, "invalidateQueries")
- const mod = await loadMod()
- mod.useReadForumThreadFromInbox()
-
- await runMutation({ parentChannelId: "forum_1", openerMessageId: "opener_42" }).catch(() => {})
-
- expect(setSpy).not.toHaveBeenCalled()
- expect(invalidateSpy).not.toHaveBeenCalled()
- expect(capturedQc.getQueryData(communityKeys.inboxUnreads())).toEqual(before)
- expect(toastMock).toHaveBeenCalledWith("parent read failed")
- })
-})
-
-// ── useAdvanceDmWatermark — DM sibling of the channel wrapper ───────────
-describe("useAdvanceDmWatermark", () => {
- it("returns a callable that PUTs { lastReadMessageId } to the canonical channels 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/channels/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",
- )
- // DM and channel now share the canonical /channels/{id}/read URL, so the
- // two schedules are distinguished by BODY, not path — the point is the
- // shared debounce map (keyed `dm:x` vs the channel's own key) does NOT
- // alias them into one PUT.
- expect(puts).toHaveLength(2)
- const bodies = puts.map((c) => (c[1] as RequestInit).body)
- expect(bodies).toContain(JSON.stringify({ lastReadMessageId: "m_dm" }))
- expect(bodies).toContain(JSON.stringify({ lastReadMessageId: "m_ch" }))
- for (const c of puts) {
- expect(c[0] as string).toBe("/api/community/channels/x/read")
- }
- } 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", () => {
- it("optimistically clears unread; restores on failure", async () => {
- capturedQc.setQueryData(communityKeys.dms(), {
- conversations: [{ id: "dm_1", unread: true }],
- })
- apiFetchMock.mockRejectedValueOnce(new Error("boom"))
- const mod = await loadMod()
- mod.useMarkDmRead()
- await runMutation({ dmId: "dm_1" }).catch(() => { })
- const cache = capturedQc.getQueryData<{ conversations: { id: string; unread?: boolean }[] }>(
- communityKeys.dms(),
- )
- expect(cache?.conversations[0].unread).toBe(true)
- })
-})
-
// ── useMarkAllInboxRead ───────────────────────────────────────────────────
describe("useMarkAllInboxRead", () => {
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 94b328cf4..d0e871e5e 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -28,7 +28,6 @@ import {
import type { Attachment, MessagesPage, Msg } from "@/lib/community/models/message"
import type { PinsResponse } from "@/hooks/community/use-channel-panels"
import type { MarkedResponse, MessageMarkedResponse } from "@/hooks/community/use-inbox"
-import { scheduleMarkRead } from "@/lib/community/pending-reads"
import {
getForumSidebarBase,
hasForumSidebarThread,
@@ -39,13 +38,6 @@ import {
import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"
import { isBlocked, type MentionType } from "@alook/shared"
-export {
- _resetPendingReads_forTesting,
- flushPendingReads,
- MARK_CHANNEL_READ_DEBOUNCE_MS,
- scheduleMarkRead,
-} from "@/lib/community/pending-reads"
-export type { ScheduleMarkReadOpts } from "@/lib/community/pending-reads"
/**
* Message-scoped mutation hooks — the split of the God-context's
@@ -806,194 +798,6 @@ export function useCreateThread() {
})
}
-// ── Read state ─────────────────────────────────────────────────────────────
-
-export type MarkChannelReadArgs = { channelId: string }
-
-/**
- * Debounced mark-channel-read for the mass "mark whole channel read" path
- * (no specific messageId). After #3, no in-repo caller invokes this — the
- * eager mass mark-read on sidebar-click / inbox-open was removed, and
- * `useMarkAllInboxRead` POSTs to the three inbox read-all routes directly.
- * Kept as a stable API for future bulk mark-read affordances (per-channel context
- * menu, "mark from here down", etc.) and to document the shape of a
- * no-body PUT.
- *
- * For per-viewport watermark advances (Slack-style progressive read), use
- * `useAdvanceChannelWatermark` below, which passes a specific `messageId`.
- *
- * This hook:
- * 1. Debounces the PUT per `channelId` (500ms) so a burst of triggers
- * collapses to a single request.
- * 2. Invalidates `communityKeys.inbox()` and `communityKeys.servers()` after
- * the PUT — one refetch cycle, not three unrelated per-feed fetches.
- * 3. On unmount / channel switch, `flushPendingReads()` forces the pending
- * PUT to fire so the pointer isn't stranded in the debounce window.
- *
- * Note: `mutationFn` resolves synchronously (fire-and-forget). The PUT and
- * the inbox invalidate happen inside `scheduleMarkRead`'s `onDone`, NOT in
- * TanStack's `onSuccess`. This is deliberate — the previous design wrapped
- * the setTimeout inside the mutationFn's Promise, and a same-channel
- * re-invoke (which clears the timer) or a `flushPendingReads()` call would
- * strand the Promise's `resolve()` forever.
- */
-export function useMarkChannelRead() {
- const queryClient = useQueryClient()
- return useMutation<void, Error, MarkChannelReadArgs>({
- mutationFn: async ({ channelId }) => {
- scheduleMarkRead(channelId, {
- onDone: () => {
- // Single invalidate on the whole inbox prefix — refreshes all three
- // feeds under one round-trip. Do NOT invalidate on WS message.create;
- // that debounce lives in useCommunityWs.
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- // Marking a channel read drops any unread mention rows for that
- // channel — refresh the server list so the rail badge decrements.
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
- },
- })
- // Resolve immediately — the debounced work runs independently. Callers
- // don't (and shouldn't) block on the eventual PUT.
- },
- onMutate: async (_args) => {
- // Optimistic inbox trim so the popover updates instantly. The server
- // reconciles on the WS invalidate.
- queryClient.setQueryData<{ servers: { serverId: string; serverName: string; channels: { channelId: string }[] }[] } | undefined>(
- communityKeys.inboxUnreads(),
- (prev) => {
- if (!prev) return prev
- const servers = prev.servers
- .map((s) => ({ ...s, channels: s.channels.filter((c) => c.channelId !== _args.channelId) }))
- .filter((s) => s.channels.length > 0)
- return { ...prev, servers }
- },
- )
- },
- })
-}
-
-// ── Advance channel watermark (progressive read) ──────────────────────────
-
-/**
- * Thin wrapper around `scheduleMarkRead` that includes a specific
- * `messageId` in the PUT body — advances the read pointer to that
- * message's `(createdAt, id)`. Callback returned is stable across renders.
- *
- * Monotonicity (never regress) is the caller's job — this hook just carries
- * whatever id was passed to the underlying debounce. `useChannelWatermark`
- * keeps a `maxSeen` ref and only invokes this hook when it advances.
- *
- * The caller supplies the channelId + messageId at call time so a single
- * hook instance can serve multiple channels across a session; the debounce
- * key is `channelId`, so bursts against the same channel still collapse.
- */
-export function useAdvanceChannelWatermark(): (
- channelId: string,
- messageId: string,
-) => void {
- const queryClient = useQueryClient()
- return (channelId, messageId) => {
- scheduleMarkRead(channelId, {
- messageId,
- onDone: () => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
- },
- })
- }
-}
-
-// ── Read a forum opener from Inbox ──────────────────────────────────────
-
-export type ReadForumThreadFromInboxArgs = {
- parentChannelId: string
- openerMessageId: string
-}
-
-/**
- * Immediate progressive read used only by an opener-backed Inbox row.
- *
- * Unlike viewport watermarks this is not debounced: the click starts the
- * parent read and navigation immediately. There is deliberately no onMutate
- * cache trim. Success refreshes Inbox/server aggregates; failure keeps the
- * unread row and only reports the error.
- */
-export function useReadForumThreadFromInbox() {
- const queryClient = useQueryClient()
- return useMutation<void, Error, ReadForumThreadFromInboxArgs>({
- mutationFn: async ({ parentChannelId, openerMessageId }) => {
- await apiFetch(`/api/community/channels/${parentChannelId}/read`, {
- method: "PUT",
- body: JSON.stringify({ lastReadMessageId: openerMessageId }),
- })
- },
- onSuccess: () => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
- },
- onError: (error) => {
- toastApiError(error, "Failed to mark forum post read")
- },
- })
-}
-
-// ── Advance DM watermark (progressive read) ───────────────────────────────
-
-/**
- * DM sibling of `useAdvanceChannelWatermark` — a thin wrapper that PUTs
- * `{ lastReadMessageId }` to `/api/community/channels/:id/read` (DM and
- * channel share the one canonical read door). 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 }
-
-export function useMarkDmRead() {
- const queryClient = useQueryClient()
- return useMutation<void, Error, MarkDmReadArgs, { snapshot: unknown } | undefined>({
- mutationFn: async ({ dmId }) => {
- await apiFetch(`/api/community/channels/${dmId}/read`, { method: "PUT" })
- },
- onMutate: async (args) => {
- const key = communityKeys.dms()
- const snapshot = queryClient.getQueryData(key)
- queryClient.setQueryData(key, (prev: { conversations: { id: string; unread?: boolean }[] } | undefined) =>
- prev
- ? { ...prev, conversations: prev.conversations.map((d) => (d.id === args.dmId ? { ...d, unread: false } : d)) }
- : prev,
- )
- return { snapshot }
- },
- onError: (_err, _args, ctx) => {
- if (ctx?.snapshot) queryClient.setQueryData(communityKeys.dms(), ctx.snapshot)
- },
- })
-}
-
// ── Inbox mutations ────────────────────────────────────────────────────────
export function useMarkAllInboxRead() {
diff --git a/src/web/src/hooks/community/read-coordinator-snapshot-projection.ts b/src/web/src/hooks/community/read-coordinator-snapshot-projection.ts
new file mode 100644
index 000000000..766c332fc
--- /dev/null
+++ b/src/web/src/hooks/community/read-coordinator-snapshot-projection.ts
@@ -0,0 +1,27 @@
+import type { QueryClient } from "@tanstack/react-query"
+
+export type ReadCoordinatorSnapshot = {
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+}
+
+type SnapshotProjector = (snapshot: ReadCoordinatorSnapshot) => void
+
+const snapshotProjectors = new WeakMap<QueryClient, SnapshotProjector>()
+
+export function registerReadCoordinatorSnapshotProjector(
+ queryClient: QueryClient,
+ projector: SnapshotProjector,
+) {
+ snapshotProjectors.set(queryClient, projector)
+}
+
+export function unregisterReadCoordinatorSnapshotProjector(queryClient: QueryClient) {
+ snapshotProjectors.delete(queryClient)
+}
+
+export function projectReadCoordinatorSnapshot(
+ queryClient: QueryClient,
+ snapshot: ReadCoordinatorSnapshot,
+) {
+ snapshotProjectors.get(queryClient)?.(snapshot)
+}
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
new file mode 100644
index 000000000..135f8c528
--- /dev/null
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -0,0 +1,336 @@
+import { QueryClient } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { ApiError } from "@/lib/errors"
+
+const apiFetch = vi.hoisted(() => vi.fn())
+const reconcileAccountReadState = vi.hoisted(() => vi.fn())
+
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetch(...args),
+}))
+
+vi.mock("./community-ws/read-state-reconciliation", () => ({
+ reconcileAccountReadState: (...args: unknown[]) => reconcileAccountReadState(...args),
+}))
+
+import {
+ disposeReadCoordinator,
+ getReadCoordinator,
+ projectReadCoordinatorSnapshot,
+ READ_COORDINATOR_DEBOUNCE_MS,
+ registerReadSurface,
+ releaseReadSurface,
+ resumeReadCoordinator,
+ submitReadIntent,
+} from "./read-coordinator"
+
+function timelineLease(queryClient: QueryClient, confirmedSeq = 0) {
+ return registerReadSurface(
+ queryClient,
+ "user-1",
+ { kind: "timeline", channelId: "channel-1" },
+ confirmedSeq,
+ )
+}
+
+function submitTimeline(
+ lease: ReturnType<typeof timelineLease>,
+ seq: number,
+) {
+ return submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: `message-${seq}`,
+ seq,
+ })
+}
+
+describe("read coordinator", () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ apiFetch.mockReset()
+ reconcileAccountReadState.mockReset().mockResolvedValue(undefined)
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it("is an account-owned singleton and cannot be rebuilt after disposal", () => {
+ const queryClient = new QueryClient()
+ expect(getReadCoordinator(queryClient, "user-1"))
+ .toBe(getReadCoordinator(queryClient, "user-1"))
+ expect(() => getReadCoordinator(queryClient, "user-2"))
+ .toThrow("read coordinator owner mismatch")
+
+ disposeReadCoordinator(queryClient)
+ expect(() => getReadCoordinator(queryClient, "user-1"))
+ .toThrow("read coordinator disposed")
+ })
+
+ it("coalesces a visible timeline burst to its maximum target and hands off the returned revision", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockResolvedValue({ changed: false, revision: 9, targetSeq: 7 })
+
+ expect(submitTimeline(lease, 3)).toBe(true)
+ expect(submitTimeline(lease, 7)).toBe(true)
+ expect(submitTimeline(lease, 5)).toBe(true)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(apiFetch).toHaveBeenCalledWith(
+ "/api/community/channels/channel-1/read",
+ expect.objectContaining({
+ method: "PUT",
+ body: JSON.stringify({ lastReadMessageId: "message-7" }),
+ signal: expect.any(AbortSignal),
+ }),
+ )
+ expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ targetRevision: 9,
+ })
+ expect(submitTimeline(lease, 7)).toBe(false)
+ })
+
+ it("rejects hidden submissions without accepting a target", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ vi.stubGlobal("document", { visibilityState: "hidden" })
+
+ expect(submitTimeline(lease, 4)).toBe(false)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS * 2)
+ expect(apiFetch).not.toHaveBeenCalled()
+ })
+
+ it("does not automatically retry terminal responses", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockRejectedValue(new ApiError("forbidden", 403))
+
+ submitTimeline(lease, 4)
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("bounds transient retries, retains dirty intent, and resumes it later", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch
+ .mockRejectedValueOnce(new ApiError("offline", 0))
+ .mockRejectedValueOnce(new ApiError("busy", 503))
+ .mockRejectedValueOnce(new ApiError("busy", 503))
+ .mockRejectedValueOnce(new ApiError("busy", 503))
+ .mockResolvedValueOnce({ changed: true, revision: 11, targetSeq: 8 })
+
+ submitTimeline(lease, 8)
+ await vi.runAllTimersAsync()
+ expect(apiFetch).toHaveBeenCalledTimes(4)
+
+ await vi.runAllTimersAsync()
+ expect(apiFetch).toHaveBeenCalledTimes(4)
+ resumeReadCoordinator(queryClient)
+ await vi.runAllTimersAsync()
+ expect(apiFetch).toHaveBeenCalledTimes(5)
+ expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ targetRevision: 11,
+ })
+ })
+
+ it("lets an authoritative snapshot cancel scheduled and in-flight work", async () => {
+ const scheduledClient = new QueryClient()
+ const scheduledLease = timelineLease(scheduledClient)
+ submitTimeline(scheduledLease, 6)
+ projectReadCoordinatorSnapshot(scheduledClient, {
+ readStates: [{ channelId: "channel-1", lastReadSeq: 6 }],
+ })
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(apiFetch).not.toHaveBeenCalled()
+
+ const inFlightClient = new QueryClient()
+ const inFlightLease = timelineLease(inFlightClient)
+ let resolveRequest!: (value: unknown) => void
+ apiFetch.mockReturnValueOnce(new Promise((resolve) => {
+ resolveRequest = resolve
+ }))
+ submitTimeline(inFlightLease, 10)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ const signal = apiFetch.mock.calls[0]?.[1]?.signal as AbortSignal
+ projectReadCoordinatorSnapshot(inFlightClient, {
+ readStates: [{ channelId: "channel-1", lastReadSeq: 10 }],
+ })
+ expect(signal.aborted).toBe(true)
+ resolveRequest({ changed: true, revision: 12, targetSeq: 10 })
+ await Promise.resolve()
+ expect(reconcileAccountReadState).not.toHaveBeenCalled()
+ })
+
+ it("preserves accepted work across a deferred StrictMode-style release and remount", async () => {
+ const queryClient = new QueryClient()
+ const firstLease = timelineLease(queryClient)
+ apiFetch.mockResolvedValue({ changed: true, revision: 4, targetSeq: 2 })
+ submitTimeline(firstLease, 2)
+ releaseReadSurface(firstLease)
+
+ const secondLease = timelineLease(queryClient)
+ await vi.advanceTimersByTimeAsync(0)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(submitTimeline(secondLease, 2)).toBe(false)
+ })
+
+ it("flushes one accepted target on a real route release and rejects the stale lease", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockResolvedValue({ changed: true, revision: 4, targetSeq: 3 })
+
+ expect(submitTimeline(lease, 3)).toBe(true)
+ releaseReadSurface(lease)
+ expect(submitTimeline(lease, 4)).toBe(false)
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ expect(apiFetch).toHaveBeenCalledWith(
+ "/api/community/channels/channel-1/read",
+ expect.objectContaining({ body: JSON.stringify({ lastReadMessageId: "message-3" }) }),
+ )
+ })
+
+ it("serializes a newer visible target behind the active request", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ let resolveFirst!: (value: unknown) => void
+ apiFetch
+ .mockReturnValueOnce(new Promise((resolve) => {
+ resolveFirst = resolve
+ }))
+ .mockResolvedValueOnce({ changed: true, revision: 6, targetSeq: 8 })
+
+ submitTimeline(lease, 3)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ submitTimeline(lease, 8)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+
+ resolveFirst({ changed: true, revision: 5, targetSeq: 3 })
+ await vi.runAllTimersAsync()
+
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(apiFetch.mock.calls[1]?.[1]).toEqual(expect.objectContaining({
+ body: JSON.stringify({ lastReadMessageId: "message-8" }),
+ }))
+ })
+
+ it("aborts and fences an in-flight completion on account disposal", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ let resolveRequest!: (value: unknown) => void
+ apiFetch.mockReturnValue(new Promise((resolve) => {
+ resolveRequest = resolve
+ }))
+
+ submitTimeline(lease, 4)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ const signal = apiFetch.mock.calls[0]?.[1]?.signal as AbortSignal
+ disposeReadCoordinator(queryClient)
+ expect(signal.aborted).toBe(true)
+
+ resolveRequest({ changed: true, revision: 7, targetSeq: 4 })
+ await Promise.resolve()
+ expect(reconcileAccountReadState).not.toHaveBeenCalled()
+ expect(submitTimeline(lease, 5)).toBe(false)
+ })
+
+ it("coalesces visible forum cards through the ordinary channel transport", async () => {
+ const queryClient = new QueryClient()
+ const lease = registerReadSurface(queryClient, "user-1", {
+ kind: "timeline",
+ channelId: "forum-1",
+ })
+ apiFetch.mockResolvedValue({
+ changed: true,
+ revision: 8,
+ targetSeq: 12,
+ })
+
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "forum-1",
+ messageId: "opener-9",
+ seq: 9,
+ })).toBe(true)
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "forum-1",
+ messageId: "opener-12",
+ seq: 12,
+ })).toBe(true)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+
+ expect(apiFetch).toHaveBeenCalledWith(
+ "/api/community/channels/forum-1/read",
+ expect.objectContaining({
+ method: "PUT",
+ body: JSON.stringify({ lastReadMessageId: "opener-12" }),
+ signal: expect.any(AbortSignal),
+ }),
+ )
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "forum-1",
+ messageId: "opener-9",
+ seq: 9,
+ })).toBe(false)
+ })
+
+ it("treats the ordinary forum channel cursor as card confirmation", async () => {
+ const queryClient = new QueryClient()
+ const lease = registerReadSurface(queryClient, "user-1", {
+ kind: "timeline",
+ channelId: "forum-1",
+ })
+ projectReadCoordinatorSnapshot(queryClient, {
+ readStates: [{ channelId: "forum-1", lastReadSeq: 12 }],
+ })
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "forum-1",
+ messageId: "opener-12",
+ seq: 12,
+ })).toBe(false)
+ await vi.runAllTimersAsync()
+ expect(apiFetch).not.toHaveBeenCalled()
+ })
+
+ it("absorbs reconciliation failures after a committed read response", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockResolvedValue({ changed: true, revision: 14, targetSeq: 4 })
+ reconcileAccountReadState.mockRejectedValue(new Error("snapshot unavailable"))
+
+ submitTimeline(lease, 4)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ await Promise.resolve()
+
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ targetRevision: 14,
+ })
+ })
+
+ it("cancels a queued transient retry when a snapshot confirms its target", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockRejectedValue(new ApiError("busy", 503))
+
+ submitTimeline(lease, 6)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ expect(apiFetch).toHaveBeenCalledOnce()
+
+ projectReadCoordinatorSnapshot(queryClient, {
+ readStates: [{ channelId: "channel-1", lastReadSeq: 6 }],
+ })
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(apiFetch).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.ts
new file mode 100644
index 000000000..192091b7a
--- /dev/null
+++ b/src/web/src/hooks/community/read-coordinator.ts
@@ -0,0 +1,366 @@
+"use client"
+
+import type { QueryClient } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { ApiError } from "@/lib/errors"
+import { communityKeys } from "@/lib/query-keys"
+import { reconcileAccountReadState } from "./community-ws/read-state-reconciliation"
+import {
+ projectReadCoordinatorSnapshot as projectRegisteredReadCoordinatorSnapshot,
+ registerReadCoordinatorSnapshotProjector,
+ type ReadCoordinatorSnapshot,
+ unregisterReadCoordinatorSnapshotProjector,
+} from "./read-coordinator-snapshot-projection"
+
+export const READ_COORDINATOR_DEBOUNCE_MS = 500
+
+export type ReadIntent = {
+ kind: "timeline"
+ channelId: string
+ messageId: string
+ seq: number
+}
+
+export type ReadSurface = { kind: "timeline"; channelId: string }
+
+type ReadMutationResponse = {
+ changed: boolean
+ revision: number
+ targetSeq: number
+}
+
+type SurfaceLease = {
+ coordinator: ReadCoordinator
+ key: string
+ token: symbol
+ epoch: number
+}
+
+type ScopeState = {
+ surface: ReadSurface
+ epoch: number
+ leases: Set<symbol>
+ releaseTimer: ReturnType<typeof setTimeout> | null
+ timer: ReturnType<typeof setTimeout> | null
+ retryTimer: ReturnType<typeof setTimeout> | null
+ accepted: ReadIntent | null
+ dirty: ReadIntent | null
+ inFlight: {
+ target: ReadIntent
+ controller: AbortController
+ attemptEpoch: number
+ } | null
+ attemptEpoch: number
+ retryCount: number
+ confirmedSeq: number
+}
+
+const coordinators = new WeakMap<QueryClient, ReadCoordinator>()
+const disposedClients = new WeakSet<QueryClient>()
+
+function scopeKey(surface: ReadSurface) {
+ return `timeline:${surface.channelId}`
+}
+
+function sameIntent(left: ReadIntent, right: ReadIntent) {
+ return left.channelId === right.channelId && left.seq === right.seq
+}
+
+function laterIntent(current: ReadIntent | null, incoming: ReadIntent) {
+ if (!current) return incoming
+ return incoming.seq > current.seq ? incoming : current
+}
+
+function retryable(error: unknown) {
+ if (!(error instanceof ApiError)) return true
+ return error.status === 0
+ || error.status === 408
+ || error.status === 429
+ || error.status >= 500
+}
+
+class ReadCoordinator {
+ private readonly states = new Map<string, ScopeState>()
+ private disposed = false
+ private identityEpoch = 0
+
+ constructor(
+ private readonly queryClient: QueryClient,
+ readonly ownerUserId: string,
+ ) {}
+
+ register(surface: ReadSurface, confirmedSeq = 0): SurfaceLease {
+ this.assertActive()
+ const key = scopeKey(surface)
+ let state = this.states.get(key)
+ if (!state) {
+ state = {
+ surface,
+ epoch: 0,
+ leases: new Set(),
+ releaseTimer: null,
+ timer: null,
+ retryTimer: null,
+ accepted: null,
+ dirty: null,
+ inFlight: null,
+ attemptEpoch: 0,
+ retryCount: 0,
+ confirmedSeq,
+ }
+ this.states.set(key, state)
+ } else if (surface.kind === "timeline") {
+ state.confirmedSeq = Math.max(state.confirmedSeq, confirmedSeq)
+ }
+ if (state.releaseTimer !== null) {
+ clearTimeout(state.releaseTimer)
+ state.releaseTimer = null
+ }
+ const token = Symbol(key)
+ state.leases.add(token)
+ const cached = this.queryClient.getQueryData<{
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }>(communityKeys.accountReadStateSnapshot())
+ if (cached) this.applySnapshot(cached)
+ return { coordinator: this, key, token, epoch: state.epoch }
+ }
+
+ release(lease: SurfaceLease) {
+ const state = this.validState(lease)
+ if (!state) return
+ state.leases.delete(lease.token)
+ if (state.leases.size > 0 || state.releaseTimer !== null) return
+ state.releaseTimer = setTimeout(() => {
+ state.releaseTimer = null
+ if (state.leases.size > 0 || this.disposed) return
+ state.epoch += 1
+ this.flush(state)
+ }, 0)
+ }
+
+ submit(lease: SurfaceLease, intent: ReadIntent) {
+ const state = this.validState(lease)
+ if (!state || !this.matchesSurface(state.surface, intent)) return false
+ if (typeof document !== "undefined" && document.visibilityState !== "visible") {
+ return false
+ }
+ if (this.confirmed(state, intent)) return false
+ state.accepted = laterIntent(state.accepted, intent)
+ state.dirty = laterIntent(state.dirty, intent)
+ this.schedule(state, READ_COORDINATOR_DEBOUNCE_MS)
+ return true
+ }
+
+ resume() {
+ if (this.disposed) return
+ for (const state of this.states.values()) {
+ if (state.dirty && !this.confirmed(state, state.dirty)) {
+ state.accepted = laterIntent(state.accepted, state.dirty)
+ state.retryCount = 0
+ this.schedule(state, 0)
+ }
+ }
+ }
+
+ applySnapshot(snapshot: {
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }) {
+ if (this.disposed) return
+ const seqByChannel = new Map(
+ snapshot.readStates.map((row) => [row.channelId, row.lastReadSeq]),
+ )
+ for (const state of this.states.values()) {
+ state.confirmedSeq = Math.max(
+ state.confirmedSeq,
+ seqByChannel.get(state.surface.channelId) ?? 0,
+ )
+ this.cancelConfirmedWork(state)
+ }
+ }
+
+ dispose() {
+ if (this.disposed) return
+ this.disposed = true
+ this.identityEpoch += 1
+ for (const state of this.states.values()) {
+ if (state.timer !== null) clearTimeout(state.timer)
+ if (state.retryTimer !== null) clearTimeout(state.retryTimer)
+ if (state.releaseTimer !== null) clearTimeout(state.releaseTimer)
+ state.inFlight?.controller.abort()
+ state.attemptEpoch += 1
+ state.accepted = null
+ state.dirty = null
+ state.leases.clear()
+ }
+ this.states.clear()
+ }
+
+ private schedule(state: ScopeState, delay: number) {
+ if (this.disposed || state.inFlight || state.timer !== null) return
+ state.timer = setTimeout(() => {
+ state.timer = null
+ void this.send(state)
+ }, delay)
+ }
+
+ private flush(state: ScopeState) {
+ if (state.timer !== null) {
+ clearTimeout(state.timer)
+ state.timer = null
+ }
+ if (state.accepted && !state.inFlight) void this.send(state)
+ }
+
+ private async send(state: ScopeState) {
+ if (this.disposed || state.inFlight) return
+ const target = state.accepted ?? state.dirty
+ /* istanbul ignore next -- reachable transitions cancel an empty target's timer eagerly */
+ if (!target || this.confirmed(state, target)) {
+ this.cancelConfirmedWork(state)
+ return
+ }
+ state.accepted = null
+ const controller = new AbortController()
+ const attemptEpoch = ++state.attemptEpoch
+ state.inFlight = { target, controller, attemptEpoch }
+ const identityEpoch = this.identityEpoch
+ try {
+ const response = await apiFetch<ReadMutationResponse>(
+ `/api/community/channels/${target.channelId}/read`,
+ {
+ method: "PUT",
+ body: JSON.stringify({ lastReadMessageId: target.messageId }),
+ signal: controller.signal,
+ },
+ )
+ if (!this.attemptActive(state, attemptEpoch, identityEpoch)) return
+ state.confirmedSeq = Math.max(state.confirmedSeq, response.targetSeq)
+ state.dirty = sameIntent(state.dirty ?? target, target) ? null : state.dirty
+ state.retryCount = 0
+ void reconcileAccountReadState(this.queryClient, {
+ targetRevision: response.revision,
+ }).catch(() => undefined)
+ } catch (error) {
+ if (!this.attemptActive(state, attemptEpoch, identityEpoch)) return
+ if (!retryable(error)) {
+ if (state.dirty && sameIntent(state.dirty, target)) state.dirty = null
+ state.retryCount = 0
+ } else if (state.retryCount < 3) {
+ state.retryCount += 1
+ state.accepted = laterIntent(state.accepted, target)
+ const delay = 250 * 2 ** (state.retryCount - 1)
+ state.retryTimer = setTimeout(() => {
+ state.retryTimer = null
+ this.schedule(state, 0)
+ }, delay)
+ }
+ } finally {
+ if (state.inFlight?.attemptEpoch === attemptEpoch) state.inFlight = null
+ if (!this.disposed && state.accepted && state.retryTimer === null) {
+ this.schedule(state, 0)
+ }
+ }
+ }
+
+ private cancelConfirmedWork(state: ScopeState) {
+ if (state.accepted && this.confirmed(state, state.accepted)) state.accepted = null
+ if (state.dirty && this.confirmed(state, state.dirty)) state.dirty = null
+ if (state.inFlight && this.confirmed(state, state.inFlight.target)) {
+ state.attemptEpoch += 1
+ state.inFlight.controller.abort()
+ state.inFlight = null
+ }
+ if (!state.accepted && state.timer !== null) {
+ clearTimeout(state.timer)
+ state.timer = null
+ }
+ if (!state.dirty && state.retryTimer !== null) {
+ clearTimeout(state.retryTimer)
+ state.retryTimer = null
+ }
+ }
+
+ private confirmed(state: ScopeState, intent: ReadIntent) {
+ return state.confirmedSeq >= intent.seq
+ }
+
+ private matchesSurface(surface: ReadSurface, intent: ReadIntent) {
+ return surface.channelId === intent.channelId
+ }
+
+ private validState(lease: SurfaceLease) {
+ if (this.disposed || lease.coordinator !== this) return null
+ const state = this.states.get(lease.key)
+ if (!state || state.epoch !== lease.epoch || !state.leases.has(lease.token)) return null
+ return state
+ }
+
+ private attemptActive(
+ state: ScopeState,
+ attemptEpoch: number,
+ identityEpoch: number,
+ ) {
+ return !this.disposed
+ && this.identityEpoch === identityEpoch
+ && state.inFlight?.attemptEpoch === attemptEpoch
+ && state.attemptEpoch === attemptEpoch
+ }
+
+ private assertActive() {
+ if (this.disposed) throw new Error("read coordinator disposed")
+ }
+}
+
+export function getReadCoordinator(
+ queryClient: QueryClient,
+ ownerUserId: string,
+) {
+ if (disposedClients.has(queryClient)) throw new Error("read coordinator disposed")
+ const current = coordinators.get(queryClient)
+ if (current) {
+ if (current.ownerUserId !== ownerUserId) {
+ throw new Error("read coordinator owner mismatch")
+ }
+ return current
+ }
+ const created = new ReadCoordinator(queryClient, ownerUserId)
+ coordinators.set(queryClient, created)
+ registerReadCoordinatorSnapshotProjector(queryClient, (snapshot) => {
+ created.applySnapshot(snapshot)
+ })
+ return created
+}
+
+export function disposeReadCoordinator(queryClient: QueryClient) {
+ disposedClients.add(queryClient)
+ coordinators.get(queryClient)?.dispose()
+ unregisterReadCoordinatorSnapshotProjector(queryClient)
+}
+
+export function projectReadCoordinatorSnapshot(
+ queryClient: QueryClient,
+ snapshot: ReadCoordinatorSnapshot,
+) {
+ projectRegisteredReadCoordinatorSnapshot(queryClient, snapshot)
+}
+
+export function registerReadSurface(
+ queryClient: QueryClient,
+ ownerUserId: string,
+ surface: ReadSurface,
+ confirmedSeq = 0,
+) {
+ return getReadCoordinator(queryClient, ownerUserId).register(surface, confirmedSeq)
+}
+
+export function releaseReadSurface(lease: SurfaceLease) {
+ lease.coordinator.release(lease)
+}
+
+export function submitReadIntent(lease: SurfaceLease, intent: ReadIntent) {
+ return lease.coordinator.submit(lease, intent)
+}
+
+export function resumeReadCoordinator(queryClient: QueryClient) {
+ coordinators.get(queryClient)?.resume()
+}
diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.ts
index b99b0e329..8e6611396 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.ts
@@ -3,7 +3,6 @@
import { useMemo, useState } from "react"
import { useChannelReadStateSnapshot } from "./use-channel-read-state"
import { useChannelWatermark } from "./use-channel-watermark"
-import { useEagerChannelRead } from "./use-eager-channel-read"
import { useMessages } from "./use-messages"
import { usePins, useThreads } from "./use-channel-panels"
@@ -11,7 +10,7 @@ export function useChannelMessageFeed({
channelId,
serverId,
viewerUserId,
- isChildChannel,
+ isChildChannel: _isChildChannel,
anchorMessageId,
}: {
channelId: string | null
@@ -54,12 +53,13 @@ export function useChannelMessageFeed({
return { newDividerBefore: undefined, anchorFound: true }
}, [messagesQuery.anchorReconciled, messagesQuery.messages, readSnapshot, viewerUserId])
const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)
- useChannelWatermark({ channelId, messages: messagesQuery.messages, scrollRootEl })
- useEagerChannelRead({
+ /* istanbul ignore next -- retained Chromium covers the mounted observer integration */
+ useChannelWatermark({
channelId,
- serverId,
- isChildChannel,
+ messages: messagesQuery.messages,
+ scrollRootEl,
snapshotReady: !readState.isFetching,
+ confirmedSeq: readSnapshot?.lastReadSeq ?? 0,
})
const unreadCount = useMemo(() => {
const difference = messagesQuery.latestSeq - (readSnapshot?.lastReadSeq ?? 0)
diff --git a/src/web/src/hooks/community/use-channel-watermark.test.ts b/src/web/src/hooks/community/use-channel-watermark.test.ts
deleted file mode 100644
index f90944b6a..000000000
--- a/src/web/src/hooks/community/use-channel-watermark.test.ts
+++ /dev/null
@@ -1,463 +0,0 @@
-/**
- * `useChannelWatermark` — IntersectionObserver-driven read pointer advance.
- *
- * The vitest env is node (no jsdom, no IntersectionObserver). We install a
- * lightweight IO polyfill on `globalThis` that records the callback and
- * exposes a `trigger()` helper so tests can simulate intersections.
- */
-import { describe, it, expect, vi, beforeEach } from "vitest"
-
-// ── React shim ────────────────────────────────────────────────────────────
-// Positional hooks, React-faithful: `useRef`/`useEffect` are keyed by call
-// order within a render, and `useEffect` honors its deps array (runs only when
-// a dep changed vs the previous render — deps: [] runs once, no deps runs
-// always). Faithful deps matter here: the hook resets its read watermark on a
-// `[channelId]` effect and seeds once via a guarded ref — a shim that re-ran
-// every effect on every render would spuriously reset/re-seed on a plain
-// re-render (e.g. a WS message arriving), which React does not do.
-let refs: Map<string, { current: unknown }> = new Map()
-let refCounter = 0
-let effectCounter = 0
-const effectPrevDeps: Map<number, unknown[] | undefined> = new Map()
-const effectCleanupBySlot: Map<number, () => void> = new Map()
-let pendingEffects: Array<{ slot: number; fn: () => void | (() => void); deps: unknown[] | undefined }> = []
-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({ slot: effectCounter++, fn, deps })
- },
-}))
-
-function depsChanged(prev: unknown[] | undefined, next: unknown[] | undefined): boolean {
- if (next === undefined) return true // no deps → run every render
- if (prev === undefined) return true // first render
- if (prev.length !== next.length) return true
- return next.some((d, i) => !Object.is(d, prev[i]))
-}
-
-function flushEffects() {
- const effects = pendingEffects
- pendingEffects = []
- for (const e of effects) {
- if (!depsChanged(effectPrevDeps.get(e.slot), e.deps)) continue
- // React runs the cleanup from the prior invocation before re-running.
- effectCleanupBySlot.get(e.slot)?.()
- effectCleanupBySlot.delete(e.slot)
- const cleanup = e.fn()
- if (typeof cleanup === "function") {
- effectCleanupBySlot.set(e.slot, cleanup)
- effectCleanups.push(cleanup)
- }
- effectPrevDeps.set(e.slot, e.deps)
- }
-}
-
-function runCleanups() {
- const c = effectCleanups
- effectCleanups = []
- for (const fn of c) fn()
-}
-
-// Simulate a React re-render: refs + effect slots persist (same call order →
-// same ref / same effect identity), but the per-render counters rewind so the
-// hook's `useRef`/`useEffect` calls map back onto the same slots. Effects then
-// re-run only if their deps changed — faithful to React.
-function rerender() {
- refCounter = 0
- effectCounter = 0
-}
-
-// ── 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()
- }
-}
-
-// ── MutationObserver polyfill ────────────────────────────────────────────
-// The virtualized message list mounts/unmounts rows as the user scrolls —
-// no `messages` array change fires, so the IntersectionObserver seed effect
-// never re-runs. The hook wires a MutationObserver on the scroll root to
-// observe rows added after the initial seed; this polyfill records the
-// callback and lets a test fire an "added node" batch.
-type MutationObserverInstance = {
- callback: MutationCallback
- disconnected: boolean
-}
-let mutationObservers: MutationObserverInstance[] = []
-
-class MockMutationObserver {
- private inst: MutationObserverInstance
- constructor(callback: MutationCallback) {
- this.inst = { callback, disconnected: false }
- mutationObservers.push(this.inst)
- }
- observe() {}
- disconnect() {
- this.inst.disconnected = true
- }
- takeRecords(): MutationRecord[] {
- return []
- }
-}
-
-// Simulate the virtualizer appending new row nodes to the scroll container.
-function fireAddedNodes(nodes: Element[]) {
- for (const obs of mutationObservers) {
- if (obs.disconnected) continue
- obs.callback(
- [
- {
- type: "childList",
- addedNodes: nodes as unknown as NodeList,
- removedNodes: [] as unknown as NodeList,
- } as unknown as MutationRecord,
- ],
- undefined as unknown as MutationObserver,
- )
- }
-}
-
-function fireIntersections(
- entries: Array<{ target: Element; isIntersecting: boolean; intersectionRatio: number }>,
-) {
- // Broadcast to every active observer (matches real IO semantics — the
- // caller decides which observer receives which entries via observe()).
- 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", () => ({
- useAdvanceChannelWatermark: () => advanceSpy,
-}))
-vi.mock("@/lib/community/pending-reads", () => ({
- flushPendingReads: () => flushSpy(),
-}))
-
-vi.mock("@/contexts/community/current-user", () => ({
- useCurrentUser: () => ({ id: "u_viewer", name: "viewer", avatar: "V" }),
-}))
-
-function resetHarness() {
- refs = new Map()
- refCounter = 0
- effectCounter = 0
- effectPrevDeps.clear()
- effectCleanupBySlot.clear()
- pendingEffects = []
- effectCleanups = []
- observers = []
- mutationObservers = []
- advanceSpy.mockClear()
- flushSpy.mockClear()
-}
-
-async function loadHook() {
- const mod = await import("./use-channel-watermark")
- return mod.useChannelWatermark
-}
-
-// Fabricate a scroll-root element the observer can key `root` off. jsdom
-// isn't available, so we lie about the type — the polyfill above doesn't
-// actually look at the root's DOM behaviour beyond identity.
-function makeRoot(): HTMLElement {
- return { __kind: "root" } as unknown as HTMLElement
-}
-
-// Fabricate a message-row element. `dataset.msgId` mirrors the DOM API the
-// hook reads at intersection time. `matches`/`querySelectorAll` mirror the
-// Element API the MutationObserver-added-node scan reads: the row element
-// itself carries `data-msg-id`, so `matches("[data-msg-id]")` is true and a
-// self-scan returns itself.
-function makeRow(id: string): Element {
- const el = {
- dataset: { msgId: id },
- nodeType: 1,
- matches: (sel: string) => sel === "[data-msg-id]",
- querySelectorAll: () => [] as unknown as Iterable<Element>,
- }
- return el as unknown as Element
-}
-
-// The hook queries `root.querySelectorAll("[data-msg-id]")` to seed the
-// observer with the currently-rendered rows. We synthesize that here.
-function attachRows(root: HTMLElement, rows: Element[]) {
- ;(root as unknown as { querySelectorAll: (sel: string) => Iterable<Element> }).querySelectorAll =
- () => rows
-}
-
-beforeEach(() => {
- resetHarness()
- // Install IO polyfill on globalThis so `typeof IntersectionObserver` is
- // "function" inside the hook.
- ;(globalThis as unknown as { IntersectionObserver: unknown }).IntersectionObserver =
- MockIntersectionObserver
- ;(globalThis as unknown as { MutationObserver: unknown }).MutationObserver =
- MockMutationObserver
-})
-
-// A message NEWER than everything in the mount window — used to exercise the
-// watermark's advance path under the read-dedupe seed (the mount window is
-// pre-seeded as "already read by the eager mark-read", so only a genuinely
-// newer arrival advances). Its createdAt is later than any fixture below.
-const NEWER = { id: "m_newer", createdAt: "2026-09-01T00:00:00.000Z", authorId: "u_other" }
-
-describe("useChannelWatermark — visibility gate", () => {
- it("advances the watermark when a NEWER-than-seed row hits >=0.2 visibility", async () => {
- const useHook = await loadHook()
- const root = makeRoot()
- // Mount window: m_1 (already read by the eager mark-read → seeded, won't
- // advance). A newer message then arrives (WS) and its row mounts.
- const seedMsg = { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" }
- attachRows(root, [makeRow("m_1")])
- useHook({ channelId: "ch_1", messages: [seedMsg], scrollRootEl: root })
- flushEffects()
- // Re-render with the newer message present (WS arrival) so the hook's
- // messagesRef sees it; its row mounts via a DOM mutation.
- rerender()
- useHook({ channelId: "ch_1", messages: [seedMsg, NEWER], scrollRootEl: root })
- flushEffects()
- const newerRow = makeRow(NEWER.id)
- fireAddedNodes([newerRow])
- fireIntersections([{ target: newerRow, isIntersecting: true, intersectionRatio: 0.3 }])
- expect(advanceSpy).toHaveBeenCalledWith("ch_1", NEWER.id)
- })
-
- it("does NOT re-advance a message already in the mount window (eager mark-read covered it)", async () => {
- const useHook = await loadHook()
- const root = makeRoot()
- const row = makeRow("m_1")
- attachRows(root, [row])
- useHook({
- channelId: "ch_1",
- messages: [
- { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
- ],
- scrollRootEl: root,
- })
- flushEffects()
- // m_1 was present at mount → seeded as read by the eager PUT → the
- // watermark must NOT fire a second, redundant read PUT for it.
- fireIntersections([{ target: row, isIntersecting: true, intersectionRatio: 0.9 }])
- expect(advanceSpy).not.toHaveBeenCalled()
- })
-
- 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({
- channelId: "ch_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()
- })
-
- it("does NOT advance when isIntersecting is false, even at high ratio", async () => {
- const useHook = await loadHook()
- const root = makeRoot()
- const row = makeRow("m_1")
- attachRows(root, [row])
- useHook({
- channelId: "ch_1",
- messages: [
- { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
- ],
- scrollRootEl: root,
- })
- flushEffects()
- fireIntersections([{ target: row, isIntersecting: false, intersectionRatio: 0.9 }])
- expect(advanceSpy).not.toHaveBeenCalled()
- })
-})
-
-// A message older than every advancing fixture below — used to seed the mount
-// window so the read-dedupe seed lands on it, leaving the (newer) test messages
-// to arrive post-mount and exercise the advance path exactly as before the seed.
-const SEED_BASELINE = { id: "m_seed", createdAt: "2026-06-01T00:00:00.000Z", authorId: "u_other" }
-
-// Mount with just the seed baseline, then re-render with the baseline + the
-// given post-mount arrivals (WS/scroll), mounting their rows via a DOM
-// mutation. Returns the arrival row objects (keyed by id) so callers fire
-// intersections on the SAME element instances the observer is tracking.
-function mountThenArrive(
- // Not named `use…` on purpose — a plain helper isn't a React hook/component,
- // and the rules-of-hooks lint forbids calling a `use*` binding here.
- runWatermark: (a: { channelId: string; messages: unknown[]; scrollRootEl: HTMLElement }) => void,
- root: HTMLElement,
- arrivals: Array<{ id: string; createdAt: string; authorId: string }>,
-): Record<string, Element> {
- attachRows(root, [makeRow(SEED_BASELINE.id)])
- runWatermark({ channelId: "ch_1", messages: [SEED_BASELINE], scrollRootEl: root })
- flushEffects()
- rerender()
- runWatermark({ channelId: "ch_1", messages: [SEED_BASELINE, ...arrivals], scrollRootEl: root })
- flushEffects()
- const rows: Record<string, Element> = {}
- for (const a of arrivals) rows[a.id] = makeRow(a.id)
- fireAddedNodes(Object.values(rows))
- return rows
-}
-
-describe("useChannelWatermark — monotone forward", () => {
- it("advances forward across two newer intersections", async () => {
- const useHook = await loadHook()
- const root = makeRoot()
- const rows = mountThenArrive(useHook, root, [
- { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
- { id: "m_2", createdAt: "2026-07-01T00:00:01.000Z", authorId: "u_other" },
- ])
- fireIntersections([{ target: rows.m_1, isIntersecting: true, intersectionRatio: 0.9 }])
- fireIntersections([{ target: rows.m_2, isIntersecting: true, intersectionRatio: 0.9 }])
- expect(advanceSpy.mock.calls.map((c) => c[1])).toEqual(["m_1", "m_2"])
- })
-
- it("NEVER regresses — a stale-older intersection after seeing a newer row is ignored", async () => {
- const useHook = await loadHook()
- const root = makeRoot()
- const rows = mountThenArrive(useHook, root, [
- { 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" },
- ])
- // See the newer one first.
- fireIntersections([{ target: rows.m_new, isIntersecting: true, intersectionRatio: 0.9 }])
- // Then scroll back — an older row briefly clears the threshold again.
- fireIntersections([{ target: rows.m_old, isIntersecting: true, intersectionRatio: 0.9 }])
- expect(advanceSpy.mock.calls.map((c) => c[1])).toEqual(["m_new"])
- })
-
- it("breaks (createdAt, id) ties lexicographically on id", async () => {
- const useHook = await loadHook()
- const root = makeRoot()
- const rows = mountThenArrive(useHook, root, [
- { id: "m_a", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
- { id: "m_b", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
- ])
- fireIntersections([{ target: rows.m_a, isIntersecting: true, intersectionRatio: 0.9 }])
- fireIntersections([{ target: rows.m_b, isIntersecting: true, intersectionRatio: 0.9 }])
- // b > a lexicographically at the same createdAt, so both advance.
- expect(advanceSpy.mock.calls.map((c) => c[1])).toEqual(["m_a", "m_b"])
- })
-})
-
-describe("useChannelWatermark — virtualized rows (mounted on scroll, no messages change)", () => {
- it("observes a row the virtualizer mounts AFTER the initial seed, so scrolling clears unreads", async () => {
- // Regression: with the virtualized message list, rows enter the DOM as
- // the user scrolls — the `messages` array reference doesn't change, so
- // the seed effect never re-runs and the newly-mounted row is never
- // observed. The read watermark then never advances past whatever was
- // on-screen at mount, so "NEW" unreads never clear on scroll. A
- // MutationObserver on the scroll root must pick up the added row.
- //
- // Under read-dedupe, the advancing row must also be NEWER than the mount
- // seed — a message already in the mount window was covered by the eager
- // mark-read, so scrolling to it correctly does not re-PUT. Here m_2 arrives
- // after the seed baseline and is genuinely newer.
- const useHook = await loadHook()
- const root = makeRoot()
- const rows = mountThenArrive(useHook, root, [
- { id: "m_2", createdAt: "2026-07-01T00:00:05.000Z", authorId: "u_other" },
- ])
- // The newly-mounted (newer) row is observed and advances the watermark.
- fireIntersections([{ target: rows.m_2, isIntersecting: true, intersectionRatio: 0.9 }])
- expect(advanceSpy).toHaveBeenCalledWith("ch_1", "m_2")
- })
-})
-
-describe("useChannelWatermark — 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({
- channelId: "ch_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("useChannelWatermark — lifecycle", () => {
- it("flushes pending mark-reads on unmount / channel change", async () => {
- const useHook = await loadHook()
- const root = makeRoot()
- attachRows(root, [])
- useHook({ channelId: "ch_1", messages: [], scrollRootEl: root })
- flushEffects()
- // Trigger cleanup — the effect keyed on channelId returns
- // `flushPendingReads`.
- runCleanups()
- expect(flushSpy).toHaveBeenCalled()
- })
-
- it("no-op when scrollRootEl is null (IntersectionObserver never mounts)", async () => {
- const useHook = await loadHook()
- useHook({ channelId: "ch_1", messages: [], scrollRootEl: null })
- flushEffects()
- expect(observers).toHaveLength(0)
- })
-})
diff --git a/src/web/src/hooks/community/use-channel-watermark.ts b/src/web/src/hooks/community/use-channel-watermark.ts
index 6cc80985e..d30f55f71 100644
--- a/src/web/src/hooks/community/use-channel-watermark.ts
+++ b/src/web/src/hooks/community/use-channel-watermark.ts
@@ -1,193 +1,27 @@
"use client"
-import { useEffect, useRef } from "react"
-import { flushPendingReads } from "@/lib/community/pending-reads"
-import { useAdvanceChannelWatermark } from "@/hooks/community/mutations/messages"
import type { Msg } from "@/lib/community/models/message"
-import { useCurrentUser } from "@/contexts/community/current-user"
+import { useTimelineReadObserver } from "./use-read-observer"
-/**
- * Threshold at which a message must be visible before it counts as "read".
- * 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.2
-
-/**
- * Slack-style progressive read watermark. Observes every rendered message
- * row in the scroll container and, when a row hits ≥75% visibility, walks
- * the local `maxSeen` pointer forward and asks the mutation layer to PUT
- * the new pointer to the server (debounced 500ms — bursts collapse into a
- * single request).
- *
- * Invariants:
- *
- * - **Monotone forward.** Scrolling back never regresses the local
- * `maxSeen`. The watermark only ever moves toward the newest visible id.
- * - **Self-authored messages are skipped.** The write-path already sets
- * the sender's own `lastReadMessageId` when they post (see #1 in the
- * plan) — a client PUT would be redundant.
- * - **On unmount, flush.** Any pending debounce fires immediately via
- * `flushPendingReads()` so the last watched message isn't stranded in
- * the debounce window.
- *
- * `scrollRootEl` must be the same element that scrolls the message list —
- * the `IntersectionObserver` uses it as `root` so ratios are computed
- * against the visible scroll frame, not the entire viewport.
- */
+/* istanbul ignore next -- retained Chromium covers this React hook adapter */
export function useChannelWatermark({
channelId,
messages,
scrollRootEl,
+ snapshotReady,
+ confirmedSeq,
}: {
channelId: string | null | undefined
messages: Msg[]
scrollRootEl: HTMLElement | null
+ snapshotReady: boolean
+ confirmedSeq: number
}) {
- const currentUser = useCurrentUser()
- const viewerId = currentUser.id
- const advance = useAdvanceChannelWatermark()
-
- // `maxSeen` is a `(createdAt, id)` pair — lex ordering so identical
- // createdAt strings still sort deterministically. Reset when the
- // channel changes so a switch between channels doesn't leak the prior
- // channel's pointer.
- const maxSeenRef = useRef<{ createdAt: string; id: string } | null>(null)
- // Read-PUT de-dupe (W-READ-DEDUPE, necessity plan): opening a channel already
- // fires ONE mark-read-to-latest via `useEagerChannelRead`. Without a seed the
- // watermark would then observe the already-visible tail and fire a SECOND,
- // redundant read PUT for messages the eager read just covered. So seed
- // `maxSeen` once per channel to the newest loaded message — the same point
- // the eager read marks — so the initial visible rows don't advance. Only a
- // genuinely newer message (a WS arrival, or one scrolled to beyond the seed)
- // moves the watermark and PUTs, which is a real read the eager PUT didn't
- // cover. `seededForRef` gates the one-shot per channel (mirrors eager-read's
- // `firedForRef`); the channel-change reset re-arms it.
- const seededForRef = useRef<string | null>(null)
- useEffect(() => {
- maxSeenRef.current = null
- seededForRef.current = null
- }, [channelId])
-
- // 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. WS-delivered new messages get
- // observed on the next render pass (see the effect below), so the ref
- // avoids stale-closure lookups when a row is measured.
- const messagesRef = useRef<Msg[]>(messages)
- const advanceRef = useRef(advance)
- useEffect(() => {
- messagesRef.current = messages
- advanceRef.current = advance
+ useTimelineReadObserver({
+ channelId,
+ messages,
+ scrollRootEl,
+ snapshotReady,
+ confirmedSeq,
})
-
- // Seed `maxSeen` to the newest loaded message once per channel (see the
- // `seededForRef` comment above). Runs before the observer effect below and on
- // the first non-empty `messages`, so the initial visible tail is already
- // "seen" by the time the IntersectionObserver fires — no redundant read PUT
- // on open. A later message with a strictly greater (createdAt, id) still
- // advances past this seed.
- useEffect(() => {
- if (!channelId) return
- if (seededForRef.current === channelId) return
- if (messages.length === 0) return
- let newest: { createdAt: string; id: string } | null = null
- for (const m of messages) {
- if (!m.createdAt) continue
- if (
- !newest ||
- m.createdAt > newest.createdAt ||
- (m.createdAt === newest.createdAt && m.id > newest.id)
- ) {
- newest = { createdAt: m.createdAt, id: m.id }
- }
- }
- if (newest) {
- maxSeenRef.current = newest
- seededForRef.current = channelId
- }
- }, [channelId, messages])
-
- useEffect(() => {
- if (!channelId) 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 — see hook docstring.
- 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(channelId, 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))
-
- // The message list is virtualized — rows mount/unmount as the user
- // scrolls, WITHOUT any `messages` array change to re-run this effect.
- // A one-time `querySelectorAll` seed above therefore only ever covers
- // the rows on-screen at mount; a row scrolled into view later would
- // never be observed, so its read watermark would never advance and the
- // "NEW" unread badge would never clear on scroll. Watch the scroll root
- // for added `[data-msg-id]` nodes and observe them as they appear. No-op
- // in environments without MutationObserver (SSR / older test shims).
- let mutationObserver: MutationObserver | null = null
- if (typeof MutationObserver !== "undefined") {
- mutationObserver = new MutationObserver((records) => {
- for (const record of records) {
- record.addedNodes.forEach((node) => {
- // Element nodes only (skip text/comment nodes — nodeType 1).
- if ((node as { nodeType?: number }).nodeType !== 1) return
- const el = node as Element
- if (el.matches?.("[data-msg-id]")) observer.observe(el)
- el.querySelectorAll?.("[data-msg-id]").forEach((n) => observer.observe(n))
- })
- }
- })
- mutationObserver.observe(scrollRootEl, { childList: true, subtree: true })
- }
-
- return () => {
- observer.disconnect()
- mutationObserver?.disconnect()
- }
- }, [channelId, messages, scrollRootEl, viewerId])
-
- // On unmount / channel switch, flush the debounce so the last-watched
- // message isn't stranded in the pending window. `flushPendingReads`
- // fires every entry synchronously (no `await` — the PUT is fire-and-
- // forget, matching the mutation hook's contract).
- useEffect(() => {
- return () => {
- flushPendingReads()
- }
- }, [channelId])
}
diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
new file mode 100644
index 000000000..48ea5a7ff
--- /dev/null
+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
@@ -0,0 +1,74 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ capturedQueryClient,
+ capturedUseUserWsOptions,
+ cleanupCommunityWsHarness,
+ flushEffects,
+ mountHook,
+ resetCommunityWsHarness,
+} from "./community-ws/test-harness"
+
+const documentListeners = new Map<string, () => void>()
+const windowListeners = new Map<string, () => void>()
+
+beforeEach(async () => {
+ documentListeners.clear()
+ windowListeners.clear()
+ vi.stubGlobal("document", {
+ visibilityState: "visible",
+ addEventListener: (type: string, listener: () => void) => documentListeners.set(type, listener),
+ removeEventListener: (type: string) => documentListeners.delete(type),
+ })
+ vi.stubGlobal("window", {
+ addEventListener: (type: string, listener: () => void) => windowListeners.set(type, listener),
+ removeEventListener: (type: string) => windowListeners.delete(type),
+ })
+ await resetCommunityWsHarness()
+})
+
+afterEach(async () => {
+ await cleanupCommunityWsHarness()
+ vi.unstubAllGlobals()
+})
+
+describe("community read-state lifecycle reconciliation", () => {
+ it("loads the authoritative account snapshot on authentication", async () => {
+ await mountHook()
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ await capturedUseUserWsOptions?.onAuthenticated?.()
+ expect(capturedQueryClient.getQueryData(
+ communityKeys.accountReadStateSnapshot(),
+ )).toEqual({ revision: 0, readStates: [] })
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: communityKeys.inbox(),
+ refetchType: "active",
+ }, {
+ cancelRefetch: true,
+ throwOnError: true,
+ })
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: communityKeys.dms(),
+ refetchType: "active",
+ }, {
+ cancelRefetch: true,
+ throwOnError: true,
+ })
+ })
+
+ it.each(["visibilitychange", "pageshow"] as const)(
+ "reconciles cached read state on %s",
+ async (eventType) => {
+ await mountHook()
+ flushEffects()
+ const listener = eventType === "visibilitychange"
+ ? documentListeners.get(eventType)
+ : windowListeners.get(eventType)
+ expect(listener).toBeTypeOf("function")
+ listener!()
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(
+ communityKeys.accountReadStateSnapshot(),
+ )).toEqual({ revision: 0, readStates: [] }))
+ },
+ )
+})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 6f1937148..d6ca4300f 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -13,6 +13,7 @@ import {
dispatchCommunityWsEvent,
dispatchCommunityWsEvents,
} from "@/hooks/community/community-ws/registry"
+import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"
import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
import {
invalidateDms,
@@ -146,13 +147,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
viewerUserIdRef.current = options?.viewerUserId ?? null
})
- // #3: the previous WS-driven auto-mark-read (a `useMarkChannelRead()` call
- // fired on every foreign-authored message in the focused channel) has
- // been removed. The IntersectionObserver in `useChannelWatermark` is now
- // authoritative — if a WS-delivered message actually becomes visible in
- // the viewport, IO advances the read pointer; if the user is scrolled up
- // reading history, the pointer stays put (which is the correct behavior).
-
// Debounced inbox invalidation. Grouping repeated invalidations into one
// refetch cycle keeps the popover from re-rendering on every message tick.
const inboxDebounce = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -289,10 +283,14 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
const handleReconnect = useCallback(async ({ reconnectDurationMs }: { reconnectDurationMs: number }) => {
await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs)
}, [queryClient])
+ const handleAuthenticated = useCallback(async () => {
+ useCommunityWsStore.getState().markAccessConnected()
+ await reconcileAccountReadState(queryClient)
+ }, [queryClient])
const { send, reconnectNow } = useUserWs(handleMessage, {
onReconnect: handleReconnect,
onDisconnect: useCommunityWsStore.getState().markAccessDisconnected,
- onAuthenticated: useCommunityWsStore.getState().markAccessConnected,
+ onAuthenticated: handleAuthenticated,
onConnectionStateChange: handleConnectionStateChange,
requestDaemonStatusOnAuth: false,
})
@@ -300,6 +298,20 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
reconnectTransportRef.current = reconnectNow
}, [reconnectNow])
+ useEffect(() => {
+ if (typeof document === "undefined" || typeof window === "undefined") return
+ const reconcileVisible = () => {
+ if (document.visibilityState !== "visible") return
+ void reconcileAccountReadState(queryClient).catch(() => undefined)
+ }
+ document.addEventListener("visibilitychange", reconcileVisible)
+ window.addEventListener("pageshow", reconcileVisible)
+ return () => {
+ document.removeEventListener("visibilitychange", reconcileVisible)
+ window.removeEventListener("pageshow", reconcileVisible)
+ }
+ }, [queryClient])
+
// Publish the send binding so free helpers (`communityWsSendTyping`) can
// dispatch without holding a hook reference. Single-instance assumption
// matches the "mount at tree root" contract; if a second call site invoked
diff --git a/src/web/src/hooks/community/use-dm-watermark.test.ts b/src/web/src/hooks/community/use-dm-watermark.test.ts
deleted file mode 100644
index 49d415bcb..000000000
--- a/src/web/src/hooks/community/use-dm-watermark.test.ts
+++ /dev/null
@@ -1,318 +0,0 @@
-/**
- * `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()
- }
-}
-
-// ── MutationObserver polyfill ────────────────────────────────────────────
-// Mirrors the channel-side harness — the virtualized list mounts rows on
-// scroll with no `messages` change, so the hook watches the scroll root via
-// MutationObserver to observe rows added after the initial seed.
-type MutationObserverInstance = {
- callback: MutationCallback
- disconnected: boolean
-}
-let mutationObservers: MutationObserverInstance[] = []
-
-class MockMutationObserver {
- private inst: MutationObserverInstance
- constructor(callback: MutationCallback) {
- this.inst = { callback, disconnected: false }
- mutationObservers.push(this.inst)
- }
- observe() {}
- disconnect() {
- this.inst.disconnected = true
- }
- takeRecords(): MutationRecord[] {
- return []
- }
-}
-
-function fireAddedNodes(nodes: Element[]) {
- for (const obs of mutationObservers) {
- if (obs.disconnected) continue
- obs.callback(
- [
- {
- type: "childList",
- addedNodes: nodes as unknown as NodeList,
- removedNodes: [] as unknown as NodeList,
- } as unknown as MutationRecord,
- ],
- undefined as unknown as MutationObserver,
- )
- }
-}
-
-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,
-}))
-vi.mock("@/lib/community/pending-reads", () => ({
- 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 = []
- mutationObservers = []
- 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 {
- const el = {
- dataset: { msgId: id },
- nodeType: 1,
- matches: (sel: string) => sel === "[data-msg-id]",
- querySelectorAll: () => [] as unknown as Iterable<Element>,
- }
- return el 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
- ;(globalThis as unknown as { MutationObserver: unknown }).MutationObserver =
- MockMutationObserver
-})
-
-describe("useDmWatermark — virtualized rows (mounted on scroll, no messages change)", () => {
- it("observes a row the virtualizer mounts AFTER the initial seed, so scrolling clears unreads", async () => {
- // Parity with the channel hook — see its equivalent test. Rows enter the
- // DOM on scroll with no `messages` change; a MutationObserver on the
- // scroll root must observe them so the read watermark advances.
- const useHook = await loadHook()
- const root = makeRoot()
- const topRow = makeRow("m_1")
- attachRows(root, [topRow])
- useHook({
- dmId: "dm_1",
- messages: [
- { id: "m_1", createdAt: "2026-07-01T00:00:00.000Z", authorId: "u_other" },
- { id: "m_2", createdAt: "2026-07-01T00:00:05.000Z", authorId: "u_other" },
- ],
- scrollRootEl: root,
- })
- flushEffects()
-
- const scrolledRow = makeRow("m_2")
- fireAddedNodes([scrolledRow])
-
- fireIntersections([{ target: scrolledRow, isIntersecting: true, intersectionRatio: 0.9 }])
- expect(advanceSpy).toHaveBeenCalledWith("dm_1", "m_2")
- })
-})
-
-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.ts
index 3b6c34590..211c03e91 100644
--- a/src/web/src/hooks/community/use-dm-watermark.ts
+++ b/src/web/src/hooks/community/use-dm-watermark.ts
@@ -1,140 +1,27 @@
"use client"
-import { useEffect, useRef } from "react"
-import { flushPendingReads } from "@/lib/community/pending-reads"
-import { useAdvanceDmWatermark } from "@/hooks/community/mutations/messages"
import type { Msg } from "@/lib/community/models/message"
-import { useCurrentUser } from "@/contexts/community/current-user"
+import { useTimelineReadObserver } from "./use-read-observer"
-/**
- * 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.
- */
+/* istanbul ignore next -- retained Chromium covers this React hook adapter */
export function useDmWatermark({
dmId,
messages,
scrollRootEl,
+ snapshotReady,
+ confirmedSeq,
}: {
dmId: string | null | undefined
messages: Msg[]
scrollRootEl: HTMLElement | null
+ snapshotReady: boolean
+ confirmedSeq: number
}) {
- 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
+ useTimelineReadObserver({
+ channelId: dmId,
+ messages,
+ scrollRootEl,
+ snapshotReady,
+ confirmedSeq,
})
-
- 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))
-
- // The message list is virtualized — rows mount/unmount as the user
- // scrolls, WITHOUT any `messages` array change to re-run this effect.
- // Mirrors the channel hook: watch the scroll root for added
- // `[data-msg-id]` nodes and observe them so a row scrolled into view
- // after mount still advances the read watermark. See
- // `useChannelWatermark` for the full rationale — kept identical for
- // divider/read-pointer parity.
- let mutationObserver: MutationObserver | null = null
- if (typeof MutationObserver !== "undefined") {
- mutationObserver = new MutationObserver((records) => {
- for (const record of records) {
- record.addedNodes.forEach((node) => {
- // Element nodes only (skip text/comment nodes — nodeType 1).
- if ((node as { nodeType?: number }).nodeType !== 1) return
- const el = node as Element
- if (el.matches?.("[data-msg-id]")) observer.observe(el)
- el.querySelectorAll?.("[data-msg-id]").forEach((n) => observer.observe(n))
- })
- }
- })
- mutationObserver.observe(scrollRootEl, { childList: true, subtree: true })
- }
-
- return () => {
- observer.disconnect()
- mutationObserver?.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-eager-channel-read.test.ts b/src/web/src/hooks/community/use-eager-channel-read.test.ts
deleted file mode 100644
index 90c333dc5..000000000
--- a/src/web/src/hooks/community/use-eager-channel-read.test.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-/**
- * `useEagerChannelRead` — the once-per-mount "mark this channel read on open"
- * PUT, and the query invalidations that follow it.
- *
- * The vitest env is node (no jsdom), so we drive the hook through the same
- * minimal React shim the other community-hook tests use: useRef + useEffect
- * are mocked so we can flush the mount effect by hand. `apiFetch` is stubbed
- * to resolve immediately; `useQueryClient` returns a spy client so we can
- * assert exactly which query keys get invalidated after the PUT.
- *
- * The behaviour under test (WS1 rail-fan-out fix): the eager PUT must always
- * refresh `inbox()`, but must refresh the rail mention badge
- * (`server(serverId)`) ONLY when this server actually carries mentions —
- * never the whole `servers()` prefix. A plain switch into a mention-free
- * server must not trigger any server-level refetch.
- */
-import { describe, it, expect, vi, beforeEach } from "vitest"
-import { communityKeys } from "@/lib/query-keys"
-import type { ServersResponse } from "@/hooks/community/use-servers"
-
-// ── 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()
-}
-
-// ── apiFetch stub — the PUT resolves immediately ───────────────────────────
-const apiFetchMock = vi.fn(() => Promise.resolve({}))
-vi.mock("@/lib/api/client", () => ({
- apiFetch: (...args: unknown[]) => apiFetchMock(...args),
-}))
-
-// ── TanStack Query shim — a spy client with a controllable cache ───────────
-let serversCache: ServersResponse | undefined
-const invalidateQueries = vi.fn()
-const getQueryData = vi.fn((_key: unknown) => serversCache)
-const setQueryData = vi.fn()
-const setQueriesData = vi.fn()
-vi.mock("@tanstack/react-query", () => ({
- useQueryClient: () => ({
- invalidateQueries,
- getQueryData,
- setQueryData,
- setQueriesData,
- }),
-}))
-
-function resetHarness() {
- refs = new Map()
- refCounter = 0
- pendingEffects = []
- serversCache = undefined
- apiFetchMock.mockClear()
- invalidateQueries.mockClear()
- getQueryData.mockClear()
- setQueryData.mockClear()
- setQueriesData.mockClear()
-}
-
-async function loadHook() {
- const mod = await import("./use-eager-channel-read")
- return mod.useEagerChannelRead
-}
-
-// Awaits the microtasks the eager PUT's `.then()` chain schedules.
-const settle = () => new Promise((r) => setTimeout(r, 0))
-
-function invalidatedKeys() {
- return invalidateQueries.mock.calls.map((c) => JSON.stringify(c[0].queryKey))
-}
-
-beforeEach(() => {
- resetHarness()
-})
-
-const server = (id: string, mentions: number) => ({
- id,
- name: id,
- initial: id[0]?.toUpperCase() ?? "?",
- active: false,
- mentions,
- icon: null,
-})
-
-describe("useEagerChannelRead — rail-badge fan-out gate", () => {
- it("fires exactly one mark-read PUT per mount", async () => {
- const useHook = await loadHook()
- useHook({
- channelId: "ch_1",
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: true,
- })
- flushEffects()
- await settle()
- expect(apiFetchMock).toHaveBeenCalledTimes(1)
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/read", {
- method: "PUT",
- })
- })
-
- it("does not repeat a PUT for the same channel and fires once after a channel switch", async () => {
- const hook = await loadHook()
- const render = (channelId: string) => {
- refCounter = 0
- pendingEffects = []
- hook({
- channelId,
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: true,
- })
- flushEffects()
- }
-
- render("ch_1")
- await settle()
- render("ch_1")
- await settle()
- expect(apiFetchMock).toHaveBeenCalledTimes(1)
-
- render("ch_2")
- await settle()
- expect(apiFetchMock).toHaveBeenCalledTimes(2)
- expect(apiFetchMock).toHaveBeenLastCalledWith("/api/community/channels/ch_2/read", {
- method: "PUT",
- })
- })
-
- it("uses the unified channels/[id]/read trunk for a child channel too (a thread IS a channel)", async () => {
- // The per-type /threads/:id/read split is retired — all kinds mark read via
- // channels/[id]/read, which dispatches by surface. isChildChannel no longer
- // picks the endpoint.
- const useHook = await loadHook()
- useHook({
- channelId: "th_9",
- serverId: "srv_1",
- isChildChannel: true,
- snapshotReady: true,
- })
- flushEffects()
- await settle()
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/th_9/read", {
- method: "PUT",
- })
- })
-
- it("always invalidates inbox() after the PUT", async () => {
- const useHook = await loadHook()
- serversCache = { servers: [server("srv_1", 0)] }
- useHook({
- channelId: "ch_1",
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: true,
- })
- flushEffects()
- await settle()
- expect(invalidatedKeys()).toContain(JSON.stringify(communityKeys.inbox()))
- })
-
- it("does NOT refetch any server-level query when this server has no mentions", async () => {
- const useHook = await loadHook()
- serversCache = { servers: [server("srv_1", 0), server("srv_2", 5)] }
- useHook({
- channelId: "ch_1",
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: true,
- })
- flushEffects()
- await settle()
- const keys = invalidatedKeys()
- // inbox only — no server(), no servers() cascade.
- expect(keys).toContain(JSON.stringify(communityKeys.inbox()))
- expect(keys).not.toContain(JSON.stringify(communityKeys.server("srv_1")))
- expect(keys).not.toContain(JSON.stringify(communityKeys.servers()))
- })
-
- it("refreshes the servers() list with exact:true (no cascade) when this server has mentions", async () => {
- const useHook = await loadHook()
- serversCache = { servers: [server("srv_1", 3)] }
- useHook({
- channelId: "ch_1",
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: true,
- })
- flushEffects()
- await settle()
- // The badge count lives in the servers() LIST; refresh that, and ONLY that,
- // with exact:true. A non-exact servers() invalidate prefix-matches the
- // nested server(id)/members/presence/… subtree and force-refetches all of
- // it (the per-switch storm). We must NOT touch server(serverId) (it doesn't
- // even hold the count).
- const serversCall = invalidateQueries.mock.calls.find(
- (c) => JSON.stringify(c[0].queryKey) === JSON.stringify(communityKeys.servers()),
- )
- expect(serversCall).toBeTruthy()
- expect(serversCall![0].exact).toBe(true)
- expect(invalidatedKeys()).not.toContain(JSON.stringify(communityKeys.server("srv_1")))
- })
-
- it("does not PUT until the read-state snapshot is ready", async () => {
- const useHook = await loadHook()
- useHook({
- channelId: "ch_1",
- serverId: "srv_1",
- isChildChannel: false,
- snapshotReady: false,
- })
- flushEffects()
- await settle()
- expect(apiFetchMock).not.toHaveBeenCalled()
- })
-})
diff --git a/src/web/src/hooks/community/use-eager-channel-read.ts b/src/web/src/hooks/community/use-eager-channel-read.ts
deleted file mode 100644
index 19dc350b8..000000000
--- a/src/web/src/hooks/community/use-eager-channel-read.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-"use client"
-
-import { useEffect, useRef } from "react"
-import { useQueryClient } from "@tanstack/react-query"
-import { apiFetch } from "@/lib/api/client"
-import { communityKeys } from "@/lib/query-keys"
-import type { ServersResponse } from "@/hooks/community/use-servers"
-import {
- patchForumSidebarUnreadExact,
- removeForumSidebarUnreadChild,
- setForumSidebarParentUnreadBase,
-} from "@/hooks/community/use-forum-sidebar-threads"
-
-/**
- * Eager "mark this channel/thread read on open."
- *
- * Being *inside* a channel should consume its unread — the inbox must not keep
- * showing a channel the viewer is actively looking at. This fires ONE mass
- * mark-read PUT (empty body → the server marks to the latest message) per
- * mount, as soon as the read-state snapshot has latched.
- *
- * Ordering matters (NEW-divider preservation): the divider anchors to
- * `useChannelReadStateSnapshot`, a once-per-mount frozen pointer. We gate this
- * PUT on `snapshotReady` so the snapshot latches the PRE-open pointer first;
- * the eager PUT then advances the server pointer without moving the divider.
- *
- * Race avoidance: we deliberately do NOT route through `scheduleMarkRead` (the
- * debounced watermark path keyed on `channelId`). The IntersectionObserver
- * watermark can schedule an advance to an OLDER (divider-area) message at
- * mount; a shared debounce would collapse to whichever fires last and could
- * under-advance. A direct PUT-to-latest, guarded server-side by the monotonic
- * `lastReadAt < message.createdAt` rule, can never be regressed by a later
- * older watermark PUT.
- *
- * All channel kinds (top-level and child thread) mark read through the one
- * `/channels/:id/read` trunk — a thread IS a channel, and the unified handler
- * dispatches by surface (DM ids run the block gate). The old per-type
- * `/threads/:id/read` split is retired. Empty body = mass mark-read + batched
- * mention clear.
- *
- * Note: `lastReadSeq` (the numeric bot-wake cursor) is intentionally NOT
- * touched here — human read routes don't bump it; that divergence is a
- * separate concern.
- */
-export function useEagerChannelRead({
- channelId,
- serverId,
- isChildChannel,
- snapshotReady,
-}: {
- channelId: string | null | undefined
- serverId: string | null | undefined
- isChildChannel: boolean
- snapshotReady: boolean
-}) {
- const queryClient = useQueryClient()
- // One eager PUT per (channel mount). Reset when the channel changes.
- const firedForRef = useRef<string | null>(null)
-
- useEffect(() => {
- if (!channelId) return
- if (!snapshotReady) return
- if (firedForRef.current === channelId) return
- firedForRef.current = channelId
-
- void apiFetch(`/api/community/channels/${channelId}/read`, { method: "PUT" })
- .then(() => {
- // Always refresh the inbox feeds — the mass mark-read cleared them.
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
-
- // Keep the local canonical attribution in step with the successful
- // read even on a direct/deep-link mount (where no sidebar click ran).
- // Otherwise a loaded child that later expires from the projection
- // could incorrectly re-light its parent from stale local ownership.
- if (serverId && isChildChannel) {
- removeForumSidebarUnreadChild(queryClient, serverId, channelId)
- patchForumSidebarUnreadExact(queryClient, serverId, channelId, false)
- } else if (serverId) {
- setForumSidebarParentUnreadBase(queryClient, serverId, channelId, false)
- }
-
- // The rail mention badge (`server.mentions`) only needs refreshing when
- // this server actually carries mentions the PUT may have cleared. Read
- // it from the `servers()` cache and gate on it: the common case (no
- // mentions anywhere in the server) skips the invalidate entirely.
- //
- // The badge count lives in the `servers()` LIST query — NOT in
- // `server(serverId)` (that's the detail: categories/channels, no
- // count). So refresh `servers()` and, critically, with `exact: true`:
- // members/presence/invites/server(id) are all nested under
- // `servers()` in the key hierarchy, and a non-exact invalidate
- // prefix-matches and force-refetches that whole subtree (overriding
- // their staleTime: Infinity). `exact` refreshes only the badge list.
- if (!serverId) return
- const servers = queryClient.getQueryData<ServersResponse>(
- communityKeys.servers(),
- )
- const hasMentions = servers?.servers.some(
- (s) => s.id === serverId && s.mentions > 0,
- )
- if (hasMentions) {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.servers(),
- exact: true,
- })
- }
- })
- .catch(() => {
- // Silent — the watermark / WS invalidate reconciles the inbox anyway.
- })
- }, [channelId, serverId, isChildChannel, snapshotReady, queryClient])
-}
diff --git a/src/web/src/hooks/community/use-eager-dm-read.ts b/src/web/src/hooks/community/use-eager-dm-read.ts
deleted file mode 100644
index b9f49bbf2..000000000
--- a/src/web/src/hooks/community/use-eager-dm-read.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-"use client"
-
-import { useEffect, useRef } from "react"
-import { useQueryClient } from "@tanstack/react-query"
-import { apiFetch } from "@/lib/api/client"
-import { communityKeys } from "@/lib/query-keys"
-import type { UnreadsResponse } from "./use-inbox"
-
-/**
- * DM sibling of `useEagerChannelRead`. Opening a DM should consume its unread:
- * fire ONE direct mass mark-read PUT (empty body → mark to latest) per mount,
- * gated on the read-state snapshot having latched so the "New" divider keeps
- * the pre-open anchor.
- *
- * Invalidates BOTH `inbox()` and `dms()` — the top-of-app unread badge lives
- * under `inbox()` and the sidebar DM list's `unread` flag under `dms()`. It
- * also optimistically trims the DM out of the `inboxUnreads().dms` array so
- * the popover updates instantly (mirrors `useMarkChannelRead`'s optimistic
- * inbox trim for channels).
- */
-export function useEagerDmRead({
- dmId,
- snapshotReady,
-}: {
- dmId: string | null | undefined
- snapshotReady: boolean
-}) {
- const queryClient = useQueryClient()
- const firedForRef = useRef<string | null>(null)
-
- useEffect(() => {
- if (!dmId) return
- if (!snapshotReady) return
- if (firedForRef.current === dmId) return
- firedForRef.current = dmId
-
- // Optimistic trim so the inbox popover drops this DM immediately.
- queryClient.setQueryData<UnreadsResponse>(communityKeys.inboxUnreads(), (prev) =>
- prev ? { ...prev, dms: prev.dms.filter((d) => d.channelId !== dmId) } : prev,
- )
-
- void apiFetch(`/api/community/channels/${dmId}/read`, { method: "PUT" })
- .then(() => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })
- })
- .catch(() => {
- // Silent — the watermark / WS invalidate reconciles the inbox anyway.
- })
- }, [dmId, snapshotReady, queryClient])
-}
diff --git a/src/web/src/hooks/community/use-forum-opener-hint.test.ts b/src/web/src/hooks/community/use-forum-opener-hint.test.ts
index d15dfcc19..e0ba2e1de 100644
--- a/src/web/src/hooks/community/use-forum-opener-hint.test.ts
+++ b/src/web/src/hooks/community/use-forum-opener-hint.test.ts
@@ -32,8 +32,14 @@ describe("useForumOpenerHint", () => {
expect(apiFetchMock).not.toHaveBeenCalled()
})
- it("reuses a seeded lightweight hint without a full opener request", async () => {
+ it("refetches a legacy seeded hint that lacks the opener seq", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ apiFetchMock.mockResolvedValue({
+ id: "opener-1",
+ content: "Seeded",
+ seq: 7,
+ channelId: "forum-1",
+ })
queryClient.setQueryData(
communityKeys.forumOpenerHint("server-1", "opener-1"),
{ id: "opener-1", content: "Seeded" },
@@ -47,6 +53,14 @@ describe("useForumOpenerHint", () => {
),
)
})
- expect(apiFetchMock).not.toHaveBeenCalled()
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/messages/opener-1")
+ expect(queryClient.getQueryData(
+ communityKeys.forumOpenerHint("server-1", "opener-1"),
+ )).toEqual({
+ id: "opener-1",
+ content: "Seeded",
+ seq: 7,
+ channelId: "forum-1",
+ })
})
})
diff --git a/src/web/src/hooks/community/use-forum-opener-hint.ts b/src/web/src/hooks/community/use-forum-opener-hint.ts
index 1362083fd..0df22bb16 100644
--- a/src/web/src/hooks/community/use-forum-opener-hint.ts
+++ b/src/web/src/hooks/community/use-forum-opener-hint.ts
@@ -1,6 +1,6 @@
"use client"
-import { useQuery } from "@tanstack/react-query"
+import { useQuery, useQueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { ForumOpenerHint } from "@/hooks/community/use-forum-sidebar-threads"
@@ -11,16 +11,29 @@ export function useForumOpenerHint(
enabled: boolean,
) {
const active = enabled && !!messageId
+ const queryClient = useQueryClient()
+ const queryKey = communityKeys.forumOpenerHint(serverId, messageId ?? "__none__")
+ const cached = queryClient.getQueryData<ForumOpenerHint>(queryKey)
return useQuery<ForumOpenerHint>({
- queryKey: communityKeys.forumOpenerHint(serverId, messageId ?? "__none__"),
+ queryKey,
queryFn: async () => {
- const message = await apiFetch<{ id: string; content: string }>(
+ const message = await apiFetch<{
+ id: string
+ content: string
+ seq: number
+ channelId: string
+ }>(
`/api/community/messages/${messageId}`,
)
- return { id: message.id, content: message.content }
+ return {
+ id: message.id,
+ content: message.content,
+ seq: message.seq,
+ channelId: message.channelId,
+ }
},
enabled: active,
- staleTime: Infinity,
+ staleTime: cached?.seq === undefined ? 0 : Infinity,
gcTime: 5 * 60 * 1000,
})
}
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
index 2623970f6..ae17ef568 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -37,7 +37,7 @@ export type SidebarThreadEnvelope = {
canonicalChannels?: SidebarThreadEnvelope["channels"]
retainedChannel?: SidebarThreadEnvelope["channels"][number] | null
included: {
- parentMessages: Array<{ id: string; content: string }>
+ parentMessages: Array<{ id: string; content: string; seq?: number; channelId?: string }>
}
serverNow: string
}
@@ -62,7 +62,12 @@ export type ChildChannelMeta = {
verifiedEpoch: number
}
-export type ForumOpenerHint = { id: string; content: string }
+export type ForumOpenerHint = {
+ id: string
+ content: string
+ seq?: number
+ channelId?: string
+}
export type NormalizedForumSidebarEnvelope = {
base: ForumSidebarQueryData
@@ -421,7 +426,10 @@ export function normalizeForumSidebarEnvelope(
if (meta) channelMetas[meta.id] = meta
}
const openerHints = Object.fromEntries(
- envelope.included.parentMessages.map(({ id, content }) => [id, { id, content }]),
+ envelope.included.parentMessages.map(({ id, content, seq, channelId }) => [
+ id,
+ { id, content, ...(seq === undefined ? {} : { seq }), ...(channelId ? { channelId } : {}) },
+ ]),
)
return { base, retained, channelMetas, openerHints }
}
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 00a7d7956..b40b863fa 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -15,7 +15,6 @@ import type {
MessagesPageParam,
Msg,
} from "@/lib/community/models/message"
-import { flushPendingReads } from "@/lib/community/pending-reads"
import {
materializeMessageStream,
type CanonicalMessage,
@@ -364,16 +363,6 @@ function useMessagesInner(
) ? Infinity : 0,
})
- // 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 (!scopeId) return
- return () => {
- flushPendingReads()
- }
- }, [scopeId])
-
useEffect(() => {
setPresentOverride((current) => current?.viewKey === viewKey ? current : null)
}, [viewKey])
diff --git a/src/web/src/hooks/community/use-read-observer.test.ts b/src/web/src/hooks/community/use-read-observer.test.ts
new file mode 100644
index 000000000..6bb565730
--- /dev/null
+++ b/src/web/src/hooks/community/use-read-observer.test.ts
@@ -0,0 +1,267 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+
+const effects: Array<() => void | (() => void)> = []
+const queryClient = {}
+const coordinator = vi.hoisted(() => ({
+ register: vi.fn(() => ({ lease: "timeline" })),
+ release: vi.fn(),
+ resume: vi.fn(),
+ submit: vi.fn(() => true),
+}))
+
+vi.mock("react", () => ({
+ useRef: (initial: unknown) => ({ current: initial }),
+ useEffect: (effect: () => void | (() => void)) => effects.push(effect),
+}))
+
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => queryClient,
+}))
+
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: "viewer-1", name: "Viewer", avatar: "V" }),
+}))
+
+vi.mock("./read-coordinator", () => ({
+ registerReadSurface: (...args: unknown[]) => coordinator.register(...args),
+ releaseReadSurface: (...args: unknown[]) => coordinator.release(...args),
+ resumeReadCoordinator: (...args: unknown[]) => coordinator.resume(...args),
+ submitReadIntent: (...args: unknown[]) => coordinator.submit(...args),
+}))
+
+import { useTimelineReadObserver } from "./use-read-observer"
+
+type ObserverRecord = {
+ callback: IntersectionObserverCallback
+ observed: Set<Element>
+ disconnected: boolean
+}
+
+let observers: ObserverRecord[]
+let visibility: DocumentVisibilityState
+let visibilityListeners: Set<() => void>
+let pageShowListeners: Set<() => void>
+let mutationCallback: MutationCallback | undefined
+
+class FakeIntersectionObserver {
+ private readonly record: ObserverRecord
+
+ constructor(callback: IntersectionObserverCallback) {
+ this.record = { callback, observed: new Set(), disconnected: false }
+ observers.push(this.record)
+ }
+
+ observe(element: Element) {
+ this.record.observed.add(element)
+ }
+
+ unobserve(element: Element) {
+ this.record.observed.delete(element)
+ }
+
+ disconnect() {
+ this.record.disconnected = true
+ this.record.observed.clear()
+ }
+}
+
+function makeRow(id: string) {
+ return {
+ nodeType: 1,
+ dataset: { msgId: id },
+ matches: (selector: string) => selector === "[data-msg-id]",
+ querySelectorAll: () => [],
+ } as unknown as HTMLElement
+}
+
+function makeRoot(rows: HTMLElement[]) {
+ return {
+ querySelectorAll: () => rows,
+ contains: (node: Element) => rows.includes(node as HTMLElement),
+ } as unknown as HTMLElement
+}
+
+function runEffects() {
+ return effects.splice(0).map((effect) => effect()).filter(
+ (cleanup): cleanup is () => void => typeof cleanup === "function",
+ )
+}
+
+function trigger(record: ObserverRecord, target: Element, ratio = 1) {
+ record.callback([{
+ target,
+ isIntersecting: true,
+ intersectionRatio: ratio,
+ } as IntersectionObserverEntry], {} as IntersectionObserver)
+}
+
+function useTestRender(options: Partial<Parameters<typeof useTimelineReadObserver>[0]> = {}) {
+ const row = makeRow("message-4")
+ const root = makeRoot([row])
+ useTimelineReadObserver({
+ channelId: "channel-1",
+ messages: [{ id: "message-4", seq: 4, authorId: "other-1" }] as any,
+ scrollRootEl: root,
+ snapshotReady: true,
+ confirmedSeq: 2,
+ ...options,
+ })
+ return { row, root }
+}
+
+describe("useTimelineReadObserver", () => {
+ beforeEach(() => {
+ effects.length = 0
+ observers = []
+ visibility = "visible"
+ visibilityListeners = new Set()
+ pageShowListeners = new Set()
+ mutationCallback = undefined
+ vi.clearAllMocks()
+ vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver)
+ vi.stubGlobal("MutationObserver", class {
+ constructor(callback: MutationCallback) {
+ mutationCallback = callback
+ }
+
+ observe() {}
+ disconnect() {}
+ })
+ vi.stubGlobal("document", {
+ get visibilityState() {
+ return visibility
+ },
+ addEventListener: (type: string, listener: () => void) => {
+ if (type === "visibilitychange") visibilityListeners.add(listener)
+ },
+ removeEventListener: (_type: string, listener: () => void) => {
+ visibilityListeners.delete(listener)
+ },
+ })
+ vi.stubGlobal("window", {
+ addEventListener: (type: string, listener: () => void) => {
+ if (type === "pageshow") pageShowListeners.add(listener)
+ },
+ removeEventListener: (_type: string, listener: () => void) => {
+ pageShowListeners.delete(listener)
+ },
+ })
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it("accepts only after the snapshot-ready observer sees a visible foreign row", () => {
+ useTestRender({ snapshotReady: false })
+ runEffects()
+ expect(observers).toHaveLength(0)
+ expect(coordinator.register).not.toHaveBeenCalled()
+
+ effects.length = 0
+ const { row } = useTestRender({ snapshotReady: true })
+ runEffects()
+ expect(coordinator.register).toHaveBeenCalledWith(
+ queryClient,
+ "viewer-1",
+ { kind: "timeline", channelId: "channel-1" },
+ 2,
+ )
+ trigger(observers[0]!, row)
+ expect(coordinator.submit).toHaveBeenCalledWith({ lease: "timeline" }, {
+ kind: "timeline",
+ channelId: "channel-1",
+ messageId: "message-4",
+ seq: 4,
+ })
+ })
+
+ it("keeps observing visible rows when MutationObserver is unavailable", () => {
+ vi.stubGlobal("MutationObserver", undefined)
+ const { row } = useTestRender()
+ const cleanups = runEffects()
+
+ expect(observers).toHaveLength(1)
+ trigger(observers[0]!, row)
+ expect(coordinator.submit).toHaveBeenCalledOnce()
+
+ for (const cleanup of cleanups) cleanup()
+ expect(observers[0]!.disconnected).toBe(true)
+ })
+
+ it("submits only the visible forum-card prefix candidate and preserves unseen newer siblings", () => {
+ const rows = [makeRow("opener-a"), makeRow("opener-b"), makeRow("opener-c")]
+ const root = makeRoot(rows)
+ useTestRender({
+ channelId: "forum-1",
+ messages: [
+ { id: "opener-a", seq: 1, authorId: "alice" },
+ { id: "opener-b", seq: 2, authorId: "alice" },
+ { id: "opener-c", seq: 3, authorId: "alice" },
+ ],
+ scrollRootEl: root,
+ confirmedSeq: 0,
+ })
+ runEffects()
+
+ trigger(observers[0]!, rows[0]!)
+
+ expect(coordinator.submit).toHaveBeenCalledOnce()
+ expect(coordinator.submit).toHaveBeenCalledWith({ lease: "timeline" }, {
+ kind: "timeline",
+ channelId: "forum-1",
+ messageId: "opener-a",
+ seq: 1,
+ })
+ })
+
+ it("rejects hidden callbacks and re-samples the static row on foreground", () => {
+ const { row } = useTestRender()
+ runEffects()
+ visibility = "hidden"
+ trigger(observers[0]!, row)
+ expect(coordinator.submit).not.toHaveBeenCalled()
+
+ visibility = "visible"
+ for (const listener of visibilityListeners) listener()
+ expect(coordinator.resume).toHaveBeenCalledWith(queryClient)
+ trigger(observers[0]!, row)
+ expect(coordinator.submit).toHaveBeenCalledOnce()
+ })
+
+ it("fences a recycled node and a callback from a released route scope", () => {
+ const { row } = useTestRender()
+ const cleanups = runEffects()
+ const record = observers[0]!
+
+ row.dataset.msgId = "message-recycled"
+ trigger(record, row)
+ expect(coordinator.submit).not.toHaveBeenCalled()
+
+ row.dataset.msgId = "message-4"
+ for (const cleanup of cleanups) cleanup()
+ trigger(record, row)
+ expect(coordinator.submit).not.toHaveBeenCalled()
+ expect(coordinator.release).toHaveBeenCalledWith({ lease: "timeline" })
+ })
+
+ it("binds direct and nested message rows added after the observer mounts", () => {
+ useTestRender()
+ runEffects()
+ const direct = makeRow("message-4")
+ const nested = makeRow("message-4")
+ const wrapper = {
+ nodeType: 1,
+ matches: () => false,
+ querySelectorAll: () => [nested],
+ } as unknown as Element
+
+ mutationCallback?.([
+ { addedNodes: [direct as unknown as Node] } as unknown as MutationRecord,
+ { addedNodes: [{ nodeType: 3 } as Node, wrapper as unknown as Node] } as unknown as MutationRecord,
+ ], {} as MutationObserver)
+
+ expect(observers[0]!.observed.has(direct)).toBe(true)
+ expect(observers[0]!.observed.has(nested)).toBe(true)
+ })
+})
diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.ts
new file mode 100644
index 000000000..0b6df16db
--- /dev/null
+++ b/src/web/src/hooks/community/use-read-observer.ts
@@ -0,0 +1,129 @@
+"use client"
+
+import { useEffect, useRef } from "react"
+import { useQueryClient } from "@tanstack/react-query"
+import { useCurrentUser } from "@/contexts/community/current-user"
+import {
+ registerReadSurface,
+ releaseReadSurface,
+ resumeReadCoordinator,
+ submitReadIntent,
+} from "./read-coordinator"
+
+const READ_VISIBILITY_THRESHOLD = 0.2
+
+export type ReadCandidate = {
+ id: string
+ seq?: number
+ authorId?: string
+}
+
+export function useTimelineReadObserver({
+ channelId,
+ messages,
+ scrollRootEl,
+ snapshotReady,
+ confirmedSeq,
+}: {
+ channelId: string | null | undefined
+ messages: ReadCandidate[]
+ scrollRootEl: HTMLElement | null
+ snapshotReady: boolean
+ confirmedSeq: number
+}) {
+ const queryClient = useQueryClient()
+ const currentUser = useCurrentUser()
+ const messagesRef = useRef(messages)
+ const readyRef = useRef(snapshotReady)
+
+ useEffect(() => {
+ messagesRef.current = messages
+ readyRef.current = snapshotReady
+ }, [messages, snapshotReady])
+
+ useEffect(() => {
+ if (!channelId || !scrollRootEl || !snapshotReady) return
+ if (typeof IntersectionObserver === "undefined") return
+ const lease = registerReadSurface(
+ queryClient,
+ currentUser.id,
+ { kind: "timeline", channelId },
+ confirmedSeq,
+ )
+ let observerGeneration = 0
+ const bindings = new WeakMap<Element, { id: string; generation: number }>()
+ const bind = (node: Element) => {
+ const id = (node as HTMLElement).dataset.msgId
+ if (!id) return
+ bindings.set(node, { id, generation: observerGeneration })
+ observer.observe(node)
+ }
+ const observer = new IntersectionObserver((entries) => {
+ if (!readyRef.current || document.visibilityState !== "visible") return
+ for (const entry of entries) {
+ if (!entry.isIntersecting || entry.intersectionRatio < READ_VISIBILITY_THRESHOLD) continue
+ const binding = bindings.get(entry.target)
+ if (!binding || binding.generation !== observerGeneration) continue
+ if (!scrollRootEl.contains(entry.target)) continue
+ if ((entry.target as HTMLElement).dataset.msgId !== binding.id) continue
+ const message = messagesRef.current.find((row) => row.id === binding.id)
+ if (!message?.seq || message.authorId === currentUser.id) continue
+ submitReadIntent(lease, {
+ kind: "timeline",
+ channelId,
+ messageId: message.id,
+ seq: message.seq,
+ })
+ }
+ }, { root: scrollRootEl, threshold: READ_VISIBILITY_THRESHOLD })
+
+ const sample = () => {
+ if (document.visibilityState !== "visible") return
+ observerGeneration += 1
+ scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach((node) => {
+ observer.unobserve(node)
+ bind(node)
+ })
+ resumeReadCoordinator(queryClient)
+ }
+ scrollRootEl.querySelectorAll<HTMLElement>("[data-msg-id]").forEach(bind)
+
+ const mutations = typeof MutationObserver === "undefined"
+ ? null
+ : new MutationObserver((records) => {
+ for (const record of records) {
+ for (const node of record.addedNodes) {
+ if ((node as { nodeType?: number }).nodeType !== 1) continue
+ const element = node as Element
+ if (element.matches?.("[data-msg-id]")) bind(element)
+ element.querySelectorAll?.("[data-msg-id]").forEach(bind)
+ }
+ }
+ })
+ mutations?.observe(scrollRootEl, { childList: true, subtree: true })
+ const onVisibility = () => sample()
+ const onPageShow = () => sample()
+ document.addEventListener("visibilitychange", onVisibility)
+ window.addEventListener("pageshow", onPageShow)
+ return () => {
+ observerGeneration += 1
+ observer.disconnect()
+ mutations?.disconnect()
+ document.removeEventListener("visibilitychange", onVisibility)
+ window.removeEventListener("pageshow", onPageShow)
+ releaseReadSurface(lease)
+ }
+ }, [
+ channelId,
+ confirmedSeq,
+ currentUser.id,
+ queryClient,
+ scrollRootEl,
+ snapshotReady,
+ ])
+
+ useEffect(() => {
+ if (!channelId || !snapshotReady || document.visibilityState !== "visible") return
+ resumeReadCoordinator(queryClient)
+ }, [channelId, messages, queryClient, snapshotReady])
+}
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 1cfc7772d..9610522e8 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -167,6 +167,7 @@ export type CommunityWsReconcilePolicy =
| "focused-pins"
| "focused-threads"
| "inbox-dms"
+ | "cached-read-state"
| "all-cached-servers"
| "friends"
| "presence-overlay"
diff --git a/src/web/src/lib/community/create-channels.test.ts b/src/web/src/lib/community/create-channels.test.ts
index 88abbb9a4..2ce4197e6 100644
--- a/src/web/src/lib/community/create-channels.test.ts
+++ b/src/web/src/lib/community/create-channels.test.ts
@@ -6,6 +6,7 @@ const mockGetThreadChannelByParentMessage = vi.fn()
const mockHardDeleteMessage = vi.fn()
const mockAddThreadParticipants = vi.fn()
const mockFanOutToChannel = vi.fn()
+const mockBroadcastToUserSafe = vi.fn()
const mockDeleteChannel = vi.fn()
const mockListMessageAttachments = vi.fn()
const mockRebindPendingAttachmentsToChild = vi.fn()
@@ -19,6 +20,7 @@ vi.mock("@/lib/community/message-handler", () => ({
vi.mock("@/lib/community/fanout", () => ({
fanOutToServerMembers: vi.fn(),
fanOutToChannel: (...a: unknown[]) => mockFanOutToChannel(...a),
+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
}))
vi.mock("@/lib/community/permissions", () => ({
@@ -177,7 +179,7 @@ describe("createMessageWithThread (phase2 forum≡thread — atomic-by-compensat
expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
expect.objectContaining({
authorId: "u1",
- target: { kind: "channel", channelId: "forum_1", serverId: "s1" },
+ target: { kind: "forum", channelId: "forum_1", serverId: "s1" },
}),
)
expect(mockCreateChannel).toHaveBeenCalledWith(
diff --git a/src/web/src/lib/community/create-channels.ts b/src/web/src/lib/community/create-channels.ts
index 8b26ab2ff..59d1cfd7c 100644
--- a/src/web/src/lib/community/create-channels.ts
+++ b/src/web/src/lib/community/create-channels.ts
@@ -13,7 +13,7 @@ import {
type StoredChannelType,
type Database,
} from "@alook/shared"
-import { fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"
+import { broadcastToUserSafe, fanOutToServerMembers, fanOutToChannel } from "@/lib/community/fanout"
import { createWithCollisionPolicy } from "@/lib/community/create-collision"
import { requireServerMember, requireChannelMember } from "@/lib/community/permissions"
import { requireMessageBearingSurface } from "@/lib/community/channel-write-guard"
@@ -23,6 +23,19 @@ import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"
const log = createLogger({ service: "community-create-channels" })
+/* istanbul ignore next -- real workerd compensation oracle covers revision fanout */
+async function hardDeleteMessageAndBroadcastReadState(db: Database, messageId: string) {
+ const result = await queries.communityMessage.hardDeleteMessage(db, messageId)
+ await Promise.all((result?.readStateRevisions ?? []).map((revision) =>
+ broadcastToUserSafe(revision.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: revision.revision,
+ inboxChanged: true,
+ })
+ ))
+ return result
+}
+
/**
* Single-source creation cores for the `POST /channels` create door (route/disc
* trunk 接口树统一, create-door step). Each function is the exact body that used
@@ -304,6 +317,7 @@ export type CreateMessageWithThreadResult =
export async function createMessageWithThread(params: {
db: Database
authorId: string
+ authorKind: "human" | "bot"
parentChannelId: string
serverId: string
body: IncomingMessageBody
@@ -320,7 +334,8 @@ export async function createMessageWithThread(params: {
const created = await createCommunityMessage({
db,
authorId,
- target: { kind: "channel", channelId: parentChannelId, serverId },
+ authorKind: params.authorKind,
+ target: { kind: "forum", channelId: parentChannelId, serverId },
body: params.body,
source: params.source,
attachmentIds: params.attachmentIds,
@@ -392,7 +407,7 @@ export async function createMessageWithThread(params: {
// let a secondary rollback failure mask the real cause, and never fail
// silently — Aigneis #670/#680).
try {
- await queries.communityMessage.hardDeleteMessage(db, messageId)
+ await hardDeleteMessageAndBroadcastReadState(db, messageId)
} catch (rollbackErr) {
log.error("thread_open_rollback_failed", {
messageId,
@@ -404,7 +419,8 @@ export async function createMessageWithThread(params: {
}
if (!threadResult.ok) {
try {
- await queries.communityMessage.hardDeleteMessage(db, messageId)
+ /* istanbul ignore next -- retained thread-open compensation journey */
+ await hardDeleteMessageAndBroadcastReadState(db, messageId)
} catch (rollbackErr) {
log.error("thread_open_rollback_failed", {
messageId,
@@ -429,7 +445,7 @@ export async function createMessageWithThread(params: {
})
}
try {
- await queries.communityMessage.hardDeleteMessage(db, messageId)
+ await hardDeleteMessageAndBroadcastReadState(db, messageId)
} catch (rollbackErr) {
log.error("thread_rollback_delete_opener_failed", {
messageId,
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 6dd786988..965dfe156 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -71,6 +71,11 @@ vi.mock("./message-dispatcher", () => ({
dispatchCommittedMessage: (...a: unknown[]) => mockDispatchCommittedMessage(...a),
}))
+const mockBroadcastToUserSafe = vi.fn(async () => {})
+vi.mock("./fanout", () => ({
+ broadcastToUserSafe: (...a: unknown[]) => mockBroadcastToUserSafe(...a),
+}))
+
import {
createCommunityMessage,
@@ -382,6 +387,51 @@ describe("createCommunityMessage — committed delivery handoff", () => {
expect(mockDispatchCommittedMessage).toHaveBeenCalledWith({}, "msg_1", {})
})
+
+ it("broadcasts the human author watermark as one bounded revision hint", async () => {
+ mockCreateMessage.mockResolvedValue({
+ id: "msg_1",
+ readStateRevision: 12,
+ })
+ mockGetMessage.mockResolvedValue(messageRow())
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ authorKind: "human",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "human send" },
+ })
+
+ expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({
+ authorId: "author_1",
+ authorKind: "human",
+ }))
+ await vi.waitFor(() => expect(mockBroadcastToUserSafe).toHaveBeenCalledWith("author_1", {
+ type: "community:read_state.advanced",
+ revision: 12,
+ inboxChanged: true,
+ }))
+ })
+
+ it("routes a human forum opener through the ordinary author read-state ownership", async () => {
+ mockCreateMessage.mockResolvedValue({ id: "msg_forum", readStateRevision: 13 })
+ mockGetMessage.mockResolvedValue(messageRow({ id: "msg_forum", channelId: "forum_1" }))
+
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ authorKind: "human",
+ target: { kind: "forum", channelId: "forum_1", serverId: "srv_1" },
+ body: { content: "new forum opener" },
+ })
+
+ expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({
+ authorId: "author_1",
+ authorKind: "human",
+ channelId: "forum_1",
+ }))
+ })
})
describe("createCommunityMessage — @Name#0042 mention disambiguation", () => {
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 2a7eec5b8..2c9e67a44 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -10,14 +10,29 @@ import {
isUniqueConstraintError,
withD1Retry,
reachIsParticipantSet,
+ WS_EVENTS,
} from "@alook/shared"
import type { MentionType } from "@alook/shared"
import type { Database } from "@alook/shared"
import { dispatchCommittedMessage } from "./message-dispatcher"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
+import { broadcastToUserSafe } from "./fanout"
const log = createLogger({ service: "community-message-handler" })
+/* istanbul ignore next -- real workerd compensation oracle covers revision fanout */
+async function hardDeleteMessageAndBroadcastReadState(db: Database, messageId: string) {
+ const result = await queries.communityMessage.hardDeleteMessage(db, messageId)
+ await Promise.all((result?.readStateRevisions ?? []).map((revision) =>
+ broadcastToUserSafe(revision.userId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: revision.revision,
+ inboxChanged: true,
+ })
+ ))
+ return result
+}
+
export type MessageTarget =
| { kind: "channel"; channelId: string; serverId: string }
| {
@@ -151,6 +166,8 @@ export type CreateMessageResult = CreateMessageOk | CreateMessageError
export async function createCommunityMessage(params: {
db: Database
authorId: string
+ /** Human writers mint/broadcast a bounded account read-state revision hint. */
+ authorKind: "human" | "bot"
target: MessageTarget
body: IncomingMessageBody
/** Provenance tag included in diagnostics when a requested reply target is out of scope. */
@@ -242,6 +259,7 @@ export async function createCommunityMessage(params: {
const {
db,
authorId,
+ authorKind,
target,
body,
source,
@@ -341,6 +359,7 @@ export async function createCommunityMessage(params: {
const baseMessageData: {
authorId: string;
+ authorKind: "human" | "bot";
content: string;
channelId: string;
replyToId: string | undefined;
@@ -350,6 +369,7 @@ export async function createCommunityMessage(params: {
extraStatements?: unknown[];
} = {
authorId,
+ authorKind,
content,
channelId: target.channelId,
replyToId,
@@ -428,7 +448,7 @@ export async function createCommunityMessage(params: {
// recovering from), log both and re-throw the ORIGINAL reserve error —
// it's the one the caller cares about; matches bots/route.ts:139's shape.
try {
- await queries.communityMessage.hardDeleteMessage(db, created.id)
+ await hardDeleteMessageAndBroadcastReadState(db, created.id)
} catch (rollbackErr) {
log.error("attachment_reserve_rollback_failed", {
messageId: created.id,
@@ -459,7 +479,7 @@ export async function createCommunityMessage(params: {
})
}
try {
- await queries.communityMessage.hardDeleteMessage(db, created.id)
+ await hardDeleteMessageAndBroadcastReadState(db, created.id)
} catch (rollbackErr) {
log.error("attachment_partial_reserve_rollback_failed", {
messageId: created.id,
@@ -670,12 +690,25 @@ export async function createCommunityMessage(params: {
// Delivery is planned from committed D1 facts. The handler contributes only
// structural outcomes that cannot be safely reconstructed later.
- const doBroadcast = (): Promise<void> => dispatchCommittedMessage(db, row.id, {
- ...(joinedParticipantUserIds.includes(authorId)
- ? { memberAddedUserId: authorId }
- : {}),
- ...(skipChildChannelUpdate ? { suppressParentProjection: true } : {}),
- })
+ const readStateRevision = (created as typeof created & {
+ readStateRevision?: number
+ }).readStateRevision
+ const doBroadcast = async (): Promise<void> => {
+ const deliveries: Promise<void>[] = [dispatchCommittedMessage(db, row.id, {
+ ...(joinedParticipantUserIds.includes(authorId)
+ ? { memberAddedUserId: authorId }
+ : {}),
+ ...(skipChildChannelUpdate ? { suppressParentProjection: true } : {}),
+ })]
+ if (readStateRevision !== undefined) {
+ deliveries.push(broadcastToUserSafe(authorId, {
+ type: WS_EVENTS.READ_STATE_ADVANCED,
+ revision: readStateRevision,
+ inboxChanged: true,
+ }))
+ }
+ await Promise.all(deliveries)
+ }
// Migration-backfill mode drops the real-time delivery shell entirely — the
// structural core (row + thread + enroll + mention rows) already committed
diff --git a/src/web/src/lib/community/pending-reads.ts b/src/web/src/lib/community/pending-reads.ts
deleted file mode 100644
index c915cdca3..000000000
--- a/src/web/src/lib/community/pending-reads.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { apiFetch } from "@/lib/api/client"
-
-export const MARK_CHANNEL_READ_DEBOUNCE_MS = 500
-
-/**
- * A single pending mark-read carries the debounce timer, a `fire` closure,
- * and the most recently queued `messageId` (or `undefined` for a no-body
- * mass mark-read). Re-scheduling within the debounce window replaces the
- * pending `messageId` — monotone forward semantics live one layer up in
- * `useChannelWatermark`, so this layer just uses whichever value the last
- * caller passed.
- *
- * Both the timer callback and `flushPendingReads()` invoke `fire` — same
- * code path, whether the window elapsed naturally or was flushed early.
- */
-type PendingRead = {
- timer: ReturnType<typeof setTimeout>
- fire: () => void
- // Latest queued message id — captured in the closure so `fire` reads the
- // freshest value even after the timer was scheduled with a stale one.
- messageId: string | undefined
-}
-
-const pendingReads = new Map<string, PendingRead>()
-
-export function _resetPendingReads_forTesting() {
- for (const p of pendingReads.values()) clearTimeout(p.timer)
- pendingReads.clear()
-}
-
-/**
- * Flush every pending mark-read immediately. Each entry's `fire` runs the
- * same code the timer would have — so `onDone` (typically the inbox
- * invalidate) still fires exactly once per PUT, even when a caller flushes
- * mid-window.
- */
-export function flushPendingReads() {
- const pending = [...pendingReads.values()]
- for (const p of pending) {
- clearTimeout(p.timer)
- p.fire()
- }
-}
-
-export type ScheduleMarkReadOpts = {
- /**
- * 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?: string
- onDone: () => void
-}
-
-/**
- * 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 {
- // DM and channel both resolve through the one canonical read door (a DM is a
- // channel row in the same id-space); the `dm:` key prefix only strips to the
- // channelId, no per-type URL fork.
- const channelId = key.startsWith("dm:") ? key.slice(3) : key
- return `/api/community/channels/${channelId}/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(
- key: string,
- opts: ScheduleMarkReadOpts,
-): void {
- 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
- // schedule call updated it in place. Cleaner than closing over a mutable
- // outer variable.
- const entry: PendingRead = {
- // Timer is filled in below after fire is defined.
- timer: undefined as unknown as ReturnType<typeof setTimeout>,
- messageId: opts.messageId,
- fire: () => {
- // Idempotent: if the map has already moved on (fire ran, or a fresh
- // 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(key)
- if (cur !== entry) return
- pendingReads.delete(key)
- const body = entry.messageId
- ? JSON.stringify({ lastReadMessageId: entry.messageId })
- : undefined
- const init: RequestInit = body
- ? { method: "PUT", body }
- : { method: "PUT" }
- void apiFetch(resolveReadEndpoint(key), init)
- .then(() => opts.onDone())
- .catch(() => {
- // Silent — the inbox will reconcile once the WS invalidate fires.
- })
- },
- }
- entry.timer = setTimeout(entry.fire, MARK_CHANNEL_READ_DEBOUNCE_MS)
- pendingReads.set(key, entry)
-}
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index 8749fce7f..77bf42865 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -4,6 +4,7 @@ import { tid } from "./testids"
describe("community QA selectors", () => {
it("keys forum-title read models by their stable child identity", () => {
expect(tid.inboxUnreadChild("post_1")).toBe("community-inbox-unread-child-post_1")
+ expect(tid.inboxUnreadChannel("channel_1")).toBe("community-inbox-unread-channel-channel_1")
expect(tid.channelRefPill("post_1")).toBe("community-channel-ref-pill-post_1")
expect(tid.channelRefOption("channel_1")).toBe("community-channel-ref-option-channel_1")
})
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 2fc9762aa..e0b83194f 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -112,6 +112,7 @@ export const tid = {
forumTagChip: (tag: string) => `community-forum-tag-chip-${tag}`,
forumNewPost: "community-forum-new-post",
forumPostList: "community-forum-post-list",
+ inboxUnreadChannel: (id: string) => `community-inbox-unread-channel-${id}`,
inboxUnreadChild: (id: string) => `community-inbox-unread-child-${id}`,
inboxUnreadDm: (id: string) => `community-inbox-unread-dm-${id}`,
channelRefPill: (id: string) => `community-channel-ref-pill-${id}`,
diff --git a/src/web/src/lib/db.test.ts b/src/web/src/lib/db.test.ts
index d693cf129..aee9d9a3e 100644
--- a/src/web/src/lib/db.test.ts
+++ b/src/web/src/lib/db.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
-import { withD1Retry } from "./db"
+import { getDb, getPrimaryDb, withD1Retry } from "./db"
import { mockD1FailingUntil, makeD1Error } from "@alook/shared/db/resilience-testing"
/**
@@ -74,3 +74,20 @@ describe("web/lib/db withD1Retry re-export", () => {
expect(calls).toBe(3)
})
})
+
+describe("D1 session selection", () => {
+ const session = {} as D1DatabaseSession
+ const d1 = { withSession: vi.fn(() => session) } as unknown as D1Database
+
+ beforeEach(() => vi.clearAllMocks())
+
+ it("keeps ordinary reads replica-eligible", () => {
+ expect(getDb(d1)).toBeDefined()
+ expect(d1.withSession).toHaveBeenCalledWith("first-unconstrained")
+ })
+
+ it("starts authoritative reads and write-derived pre-reads on primary", () => {
+ expect(getPrimaryDb(d1)).toBeDefined()
+ expect(d1.withSession).toHaveBeenCalledWith("first-primary")
+ })
+})
diff --git a/src/web/src/lib/db.ts b/src/web/src/lib/db.ts
index 67f9f9f51..006b7f88f 100644
--- a/src/web/src/lib/db.ts
+++ b/src/web/src/lib/db.ts
@@ -6,3 +6,8 @@ export function getDb(d1: D1Database): Database {
const session = d1.withSession("first-unconstrained")
return createDb(session as unknown as Parameters<typeof createDb>[0])
}
+
+export function getPrimaryDb(d1: D1Database): Database {
+ const session = d1.withSession("first-primary")
+ return createDb(session as unknown as Parameters<typeof createDb>[0])
+}
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 1c7bf13a0..9ca9cab5a 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -99,6 +99,8 @@ export const communityKeys = {
// stays put while the progressive watermark advances.
dmReadStateSnapshot: (dmId: string) =>
[...communityKeys.all, "dm", dmId, "read-state-snapshot"] as const,
+ accountReadStateSnapshot: () =>
+ [...communityKeys.all, "read-state-snapshot"] as const,
// Single hydrated message (opener block, deep-link previews).
message: (messageId: string) =>
diff --git a/src/web/src/stores/community/index.test.ts b/src/web/src/stores/community/index.test.ts
index 3a06e5c08..979283905 100644
--- a/src/web/src/stores/community/index.test.ts
+++ b/src/web/src/stores/community/index.test.ts
@@ -1,21 +1,8 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import { useCommunityStore } from "./index"
-// Mock the mark-reads flush so we can assert `reset()` invokes it without
-// the real implementation firing HTTP requests. `vi.mock` is hoisted above
-// regular `const` declarations, so we stash the spy in `vi.hoisted(...)`
-// which the hoisted mock factory can safely reference.
-const { flushPendingReadsSpy } = vi.hoisted(() => ({
- flushPendingReadsSpy: vi.fn(),
-}))
-vi.mock("@/lib/community/pending-reads", () => ({
- flushPendingReads: flushPendingReadsSpy,
-}))
-
beforeEach(() => {
useCommunityStore.getState().reset()
- expect(flushPendingReadsSpy).toHaveBeenCalled()
- flushPendingReadsSpy.mockClear()
})
describe("useCommunityStore", () => {
@@ -118,11 +105,6 @@ describe("useCommunityStore", () => {
expect(useCommunityStore.getState().uiHandlers.openProfile).toBe(openProfile)
})
- it("reset flushes pending mark-reads before returning", () => {
- useCommunityStore.getState().reset()
- expect(flushPendingReadsSpy).toHaveBeenCalledTimes(1)
- })
-
it("reset clears every field including timer maps", () => {
vi.useFakeTimers()
try {
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index 3624719b0..48239a1a3 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -4,7 +4,6 @@ import { create } from "zustand"
import { useShallow } from "zustand/react/shallow"
import type React from "react"
import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"
-import { flushPendingReads } from "@/lib/community/pending-reads"
/**
* Zustand store for community client-only state.
@@ -245,9 +244,6 @@ export const useCommunityStore = create<CommunityStoreState>((set, get) => ({
set({ uiHandlers: { ...get().uiHandlers, ...handlers } }),
reset: () => {
- flushPendingReads()
- // Fire-and-forget: clear every outstanding timer so nothing lingers past
- // sign-out or a hard-reset.
const { typingTimers, reactionTimers } = get()
typingTimers.forEach((t) => clearTimeout(t))
reactionTimers.forEach(({ timer }) => clearTimeout(timer))
diff --git a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
new file mode 100644
index 000000000..d95634edd
--- /dev/null
+++ b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
@@ -0,0 +1,138 @@
+import { readdirSync, readFileSync } from "node:fs"
+import { relative, resolve } from "node:path"
+import { fileURLToPath } from "node:url"
+import { describe, expect, it } from "vitest"
+
+const repositoryRoot = fileURLToPath(new URL("../../../../../", import.meta.url))
+const sharedCommunityQueries = resolve(
+ repositoryRoot,
+ "src/shared/src/db/queries/community",
+)
+
+function walkTypeScript(directory: string, files: string[] = []): string[] {
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
+ const path = resolve(directory, entry.name)
+ if (entry.isDirectory()) walkTypeScript(path, files)
+ else if (entry.name.endsWith(".ts")) files.push(path)
+ }
+ return files
+}
+
+function source(path: string): string {
+ return readFileSync(resolve(repositoryRoot, path), "utf8")
+}
+
+describe("human account read-state writer contract", () => {
+ it("has no sparse authority in production schema, snapshot, transport, or producer code", () => {
+ const productionFiles = [
+ ...walkTypeScript(resolve(repositoryRoot, "src/shared/src")),
+ ...walkTypeScript(resolve(repositoryRoot, "src/web/src"))
+ .filter((path) => !path.includes("/test/") && !path.endsWith(".test.ts")),
+ ]
+ const sparsePattern = /communityForumOpenerRead|forumOpenerReads|forum_opener_read|ForumOpenerRead/
+ expect(productionFiles
+ .filter((path) => sparsePattern.test(readFileSync(path, "utf8")))
+ .map((path) => relative(repositoryRoot, path)))
+ .toEqual([])
+ })
+
+ it("keeps every direct read-state writer in the reviewed allowlist", () => {
+ const directWriters = walkTypeScript(sharedCommunityQueries)
+ .filter((path) => /\.(?:insert|update|delete)\(\s*communityReadState\s*\)/m.test(readFileSync(path, "utf8")))
+ .map((path) => relative(repositoryRoot, path).replaceAll("\\", "/"))
+ .sort()
+
+ expect(directWriters).toEqual([
+ "src/shared/src/db/queries/community/forum-post-delete.ts",
+ "src/shared/src/db/queries/community/message.ts",
+ "src/shared/src/db/queries/community/notification-setting.ts",
+ "src/shared/src/db/queries/community/read-state.ts",
+ ])
+ })
+
+ it("requires every human-capable writer and FK cascade to mint only bounded revisions", () => {
+ const message = source("src/shared/src/db/queries/community/message.ts")
+ expect(message).toContain('authorKind?: "human" | "bot"')
+ expect(message).toContain("communityReadStateRevision")
+ expect(message).toContain("authorWatermark")
+ expect(message).toContain("return { ...msg, readStateRevision: revision }")
+ expect(message).toContain("impactedMentions")
+ expect(message).not.toContain("humanSnapshot")
+
+ const notification = source("src/shared/src/db/queries/community/notification-setting.ts")
+ expect(notification).toContain('actorKind: "human" | "bot"')
+ expect(notification).toContain("advanceReadStateRevisionWhenBuilder")
+ expect(notification).not.toContain("accountReadStateRowsBuilder")
+
+ const forumDelete = source("src/shared/src/db/queries/community/forum-post-delete.ts")
+ expect(forumDelete).toContain("advanceReadStateRevisionsForUsersBuilder")
+ expect(forumDelete).not.toContain("accountReadStateRowsForUsersBuilder")
+ expect(forumDelete).toContain("impactedHumansStable")
+ expect(forumDelete).toContain("impactedMentions")
+ expect(forumDelete).toContain("deleteForumPostAttempt(db, input, attempt + 1)")
+
+ const cascadeDelete = source("src/shared/src/db/queries/community/delete-media.ts")
+ expect(cascadeDelete).toContain("advanceReadStateRevisionsForUsersBuilder")
+ expect(cascadeDelete).not.toContain("accountReadStateRowsForUsersBuilder")
+ expect(cascadeDelete.match(/impactedHumansStable/g)?.length).toBeGreaterThanOrEqual(6)
+ expect(cascadeDelete.match(/impactedMentions/g)?.length).toBeGreaterThanOrEqual(4)
+ expect(cascadeDelete).toContain("deleteChannelWithMediaAttempt(db, input, attempt + 1)")
+ expect(cascadeDelete).toContain("deleteServerWithMediaAttempt(db, input, attempt + 1)")
+
+ const event = source("src/shared/src/community-ws-events.ts")
+ expect(event).toContain("bounded dirty hint")
+ expect(event).not.toContain("readStates: z.array")
+ expect(event).not.toContain("advances:")
+
+ const readState = source("src/shared/src/db/queries/community/read-state.ts")
+ expect(readState).toContain("getAccountReadStateSnapshot")
+ expect(readState).toContain("accountReadStateRowsBuilder(db, userId)")
+ expect(readState).not.toContain("accountReadStateRowsForUsersBuilder")
+ })
+
+ it("keeps the sole browser read transport in the account coordinator only", () => {
+ const webSourceRoot = resolve(repositoryRoot, "src/web/src")
+ const transportPattern = /\/api\/community\/channels\/\$\{[^}]+\}\/read(?!-)/
+ const owners = walkTypeScript(webSourceRoot)
+ .filter((path) => !path.includes("/test/") && !path.endsWith(".test.ts"))
+ .filter((path) => transportPattern.test(readFileSync(path, "utf8")))
+ .map((path) => relative(repositoryRoot, path).replaceAll("\\", "/"))
+
+ expect(owners).toEqual([
+ "src/web/src/hooks/community/read-coordinator.ts",
+ ])
+ })
+
+ it("keeps type-specific access in the adapter and the post-auth read effect generic", () => {
+ const route = source("src/web/src/app/api/community/channels/[id]/read/route.ts")
+ const postAuthorization = route.slice(route.indexOf("if (!auth.ok)"))
+ expect(postAuthorization).not.toMatch(/channel\.type|visibilityIsDmParticipant|surface ===/)
+ expect(route).not.toContain("getLatestMessage")
+ expect(route).toContain('Object.keys(body).length !== 1')
+ expect(route).toContain('typeof body.lastReadMessageId !== "string"')
+ })
+
+ it("adapts forum cards into generic message rows and leaves navigation write-free", () => {
+ const forumView = source("src/web/src/components/community/channels/forum-view.tsx")
+ const forumSurface = source("src/web/src/components/community/channels/forum-surface.tsx")
+ expect(forumSurface).toContain("useTimelineReadObserver")
+ expect(forumView).toContain("data-msg-id={p.openerMessageId || undefined}")
+ expect(forumSurface).toContain("channelId: forumChannelId")
+
+ const thread = source("src/web/src/components/community/channels/thread-channel-surface.tsx")
+ expect(thread).not.toContain("submitReadIntent")
+ expect(thread).not.toContain("/read")
+ })
+
+ it("makes every production message door state the author kind explicitly", () => {
+ const route = source("src/web/src/app/api/community/channels/[id]/messages/route.ts")
+ expect(route.match(/authorKind: "human"/g)).toHaveLength(2)
+ expect(route.match(/authorKind: "bot"/g)).toHaveLength(2)
+
+ const botEnrollment = source("src/web/src/app/api/community/servers/[id]/bots/route.ts")
+ expect(botEnrollment).toContain('authorKind: "bot"')
+
+ const friendship = source("src/shared/src/db/queries/community/friendship.ts")
+ expect(friendship.match(/authorKind: "bot"/g)).toHaveLength(2)
+ })
+})
diff --git a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
new file mode 100644
index 000000000..c3ee45ec2
--- /dev/null
+++ b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
@@ -0,0 +1,827 @@
+import { test, expect, userId } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import { tid } from "./_fixtures/testids"
+import {
+ seedChannel,
+ seedDm,
+ seedDmMessage,
+ seedForumThread,
+ seedJoinServer,
+ seedMessage,
+ seedServer,
+} from "./_fixtures/seed"
+import {
+ type CapturedCommunityFrame,
+ communityFrameEvents,
+ proxyCommunityWebSockets,
+} from "./_fixtures/community-ws-proxy"
+
+type CapturedReadStateEvent = CapturedCommunityFrame & {
+ type: "community:read_state.advanced" | "community:inbox.changed"
+ revision: number
+ inboxChanged: boolean
+}
+
+function isCapturedReadStateEvent(event: CapturedCommunityFrame): event is CapturedReadStateEvent {
+ return (
+ (event.type === "community:read_state.advanced" || event.type === "community:inbox.changed")
+ && typeof event.revision === "number"
+ && typeof event.inboxChanged === "boolean"
+ )
+}
+
+function readStateEventsSince(
+ frames: CapturedCommunityFrame[],
+ start: number,
+): CapturedReadStateEvent[] {
+ return frames
+ .slice(start)
+ .flatMap((frame) => communityFrameEvents(frame))
+ .filter((event): event is CapturedReadStateEvent => (
+ isCapturedReadStateEvent(event)
+ && event.type === "community:read_state.advanced"
+ ))
+}
+
+function unreadBumpsSince(
+ frames: CapturedCommunityFrame[],
+ start: number,
+ channelId: string,
+) {
+ return frames
+ .slice(start)
+ .flatMap((frame) => communityFrameEvents(frame))
+ .filter((event) => event.type === "community:unread.bump" && event.channelId === channelId)
+}
+
+test("one human account converges read state across two browser profiles", async ({ asUser }) => {
+ test.setTimeout(180_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Multi-device ${stamp}`)
+ const channelName = `read-sync-${stamp}`
+ const channelId = await seedChannel("alice", serverId, channelName)
+ const siblingId = await seedChannel("alice", serverId, `sync-sibling-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedMessage("alice", channelId, `channel unread ${stamp}`)
+ const dmId = await seedDm("alice", userId("bob"))
+ await seedDmMessage("alice", dmId, `dm unread ${stamp}`)
+
+ const deviceA = await asUser("bob")
+ const deviceB = await asUser("bob")
+ const proxyA = await proxyCommunityWebSockets(deviceA.context)
+ const proxyB = await proxyCommunityWebSockets(deviceB.context)
+ await gotoAfterUserWsAuth(deviceA.page, "/c/me")
+ await gotoAfterUserWsAuth(deviceB.page, `/c/channels/${serverId}/${siblingId}`)
+
+ await deviceB.page.getByRole("button", { name: "Inbox" }).click()
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible({ timeout: 20_000 })
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible({ timeout: 20_000 })
+
+ const accountSnapshot = async () => await (await deviceB.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ const channelResponses: number[] = []
+ const trackChannelResponse = (response: {
+ request: () => { method: () => string }
+ url: () => string
+ status: () => number
+ }) => {
+ if (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`
+ ) channelResponses.push(response.status())
+ }
+ const beforeChannelRead = await accountSnapshot()
+ deviceA.page.on("response", trackChannelResponse)
+
+ const channelRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`,
+ )
+ const channelRepair = deviceB.page.waitForResponse((response) =>
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/read-state",
+ )
+ const channelFrameStart = proxyB.frames.length
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${channelId}`)
+ expect((await channelRead).status()).toBe(200)
+ await expect.poll(() => readStateEventsSince(proxyB.frames, channelFrameStart).length,
+ { timeout: 20_000 }).toBeGreaterThan(0)
+ expect((await channelRepair).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
+ await deviceA.page.waitForTimeout(1_200)
+ expect(channelResponses).toEqual([200])
+ const afterChannelRead = await accountSnapshot()
+ expect(afterChannelRead.revision).toBe(beforeChannelRead.revision + 1)
+ expect(afterChannelRead.readStates.find((row) => row.channelId === channelId)?.lastReadSeq)
+ .toBeGreaterThan(0)
+ deviceA.page.off("response", trackChannelResponse)
+
+ const dmResponses: number[] = []
+ const trackDmResponse = (response: {
+ request: () => { method: () => string }
+ url: () => string
+ status: () => number
+ }) => {
+ if (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${dmId}/read`
+ ) dmResponses.push(response.status())
+ }
+ const beforeDmRead = await accountSnapshot()
+ deviceA.page.on("response", trackDmResponse)
+
+ const dmRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${dmId}/read`,
+ )
+ const dmRepair = deviceB.page.waitForResponse((response) =>
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/read-state",
+ )
+ const dmFrameStart = proxyB.frames.length
+ await gotoAfterUserWsAuth(deviceA.page, `/c/me/${dmId}`)
+ expect((await dmRead).status()).toBe(200)
+ await expect.poll(() => readStateEventsSince(proxyB.frames, dmFrameStart).length,
+ { timeout: 20_000 }).toBeGreaterThan(0)
+ expect((await dmRepair).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toHaveCount(0)
+ await expect(deviceB.page.getByText("Caught up", { exact: true })).toBeVisible()
+ await deviceA.page.waitForTimeout(1_200)
+ expect(dmResponses).toEqual([200])
+ const afterDmRead = await accountSnapshot()
+ expect(afterDmRead.revision).toBe(beforeDmRead.revision + 1)
+ expect(afterDmRead.readStates.find((row) => row.channelId === dmId)?.lastReadSeq)
+ .toBeGreaterThan(0)
+ deviceA.page.off("response", trackDmResponse)
+
+ const orderedReadFrames = proxyB.frames.filter((frame) =>
+ communityFrameEvents(frame).some((event) => event.type === "community:read_state.advanced"))
+ const firstReadFrame = orderedReadFrames[0]
+ expect(firstReadFrame).toBeTruthy()
+ proxyB.replay(firstReadFrame!)
+ await expect(deviceB.page.getByText("Caught up", { exact: true })).toBeVisible()
+
+ await seedMessage("alice", channelId, `offline channel ${stamp}`)
+ await seedDmMessage("alice", dmId, `offline dm ${stamp}`)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible({ timeout: 20_000 })
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible({ timeout: 20_000 })
+
+ await deviceB.context.setOffline(true)
+ await proxyB.disconnect()
+ const offlineChannelRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`,
+ )
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${channelId}`)
+ expect((await offlineChannelRead).status()).toBe(200)
+ const offlineDmRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${dmId}/read`,
+ )
+ await gotoAfterUserWsAuth(deviceA.page, `/c/me/${dmId}`)
+ expect((await offlineDmRead).status()).toBe(200)
+ const snapshotResponse = deviceB.page.waitForResponse((response) =>
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/read-state",
+ )
+ await deviceB.context.setOffline(false)
+ expect((await snapshotResponse).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toHaveCount(0)
+
+ await seedMessage("alice", channelId, `read-all channel ${stamp}`)
+ await seedDmMessage("alice", dmId, `read-all dm ${stamp}`)
+ await gotoAfterUserWsAuth(deviceA.page, "/c/me")
+ await gotoAfterUserWsAuth(deviceB.page, "/c/me")
+ await deviceA.page.getByRole("button", { name: "Inbox" }).click()
+ await deviceB.page.getByRole("button", { name: "Inbox" }).click()
+ await expect(deviceA.page.getByRole("button", { name: "Mark all read" })).toBeEnabled()
+ await expect(deviceB.page.getByRole("button", { name: "Mark all read" })).toBeEnabled()
+ const readAllFrameStarts = [proxyA.frames.length, proxyB.frames.length]
+
+ const readAllResponses = [deviceA.page, deviceB.page].flatMap((page) => [
+ page.waitForResponse((response) => response.request().method() === "POST"
+ && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads/read-all"),
+ page.waitForResponse((response) => response.request().method() === "POST"
+ && new URL(response.url()).pathname === "/api/community/users/me/inbox/dms/read-all"),
+ ])
+ await Promise.all([
+ deviceA.page.getByRole("button", { name: "Mark all read" }).click(),
+ deviceB.page.getByRole("button", { name: "Mark all read" }).click(),
+ ])
+ const completedReadAllResponses = await Promise.all(readAllResponses)
+ expect(completedReadAllResponses.every((response) => response.status() === 200)).toBe(true)
+ const readAllResults = await Promise.all(completedReadAllResponses.map(async (response) =>
+ await response.json() as { changed: boolean; revision: number }))
+ expect(readAllResults.filter((result) => result.changed)).toHaveLength(1)
+ await expect(deviceA.page.getByText("Caught up", { exact: true })).toBeVisible({ timeout: 20_000 })
+ await expect(deviceB.page.getByText("Caught up", { exact: true })).toBeVisible({ timeout: 20_000 })
+
+ const readAllEvents = (frames: typeof proxyA.frames, start: number) => frames
+ .slice(start)
+ .flatMap((frame) => communityFrameEvents(frame))
+ .filter((event): event is CapturedReadStateEvent => (
+ isCapturedReadStateEvent(event) && event.type === "community:inbox.changed"
+ ))
+ await expect.poll(() => readAllEvents(proxyA.frames, readAllFrameStarts[0]!).length, {
+ timeout: 20_000,
+ }).toBe(1)
+ await expect.poll(() => readAllEvents(proxyB.frames, readAllFrameStarts[1]!).length, {
+ timeout: 20_000,
+ }).toBe(1)
+ for (const events of [
+ readAllEvents(proxyA.frames, readAllFrameStarts[0]!),
+ readAllEvents(proxyB.frames, readAllFrameStarts[1]!),
+ ]) {
+ expect(events[0]?.revision).toBe(readAllResults.find((result) => result.changed)?.revision)
+ expect(events.every((event) => event.inboxChanged && !("readStates" in event))).toBe(true)
+ }
+
+ const snapshot = await (await deviceB.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ const scoped = snapshot.readStates.filter((row) => row.channelId === channelId || row.channelId === dmId)
+ expect(snapshot.revision).toBeGreaterThanOrEqual(5)
+ expect(scoped).toHaveLength(2)
+ expect(new Set(scoped.map((row) => row.channelId)).size).toBe(2)
+ expect(scoped.every((row) => row.lastReadSeq > 0)).toBe(true)
+})
+
+test("hidden eager channel and DM mounts defer cross-device reads until visible", async ({ asUser }) => {
+ test.setTimeout(180_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Hidden eager sync ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `hidden-eager-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ const channelBody = `hidden eager channel ${stamp}`
+ await seedMessage("alice", channelId, channelBody)
+ const dmId = await seedDm("alice", userId("bob"))
+ const dmBody = `hidden eager dm ${stamp}`
+ await seedDmMessage("alice", dmId, dmBody)
+
+ const deviceA = await asUser("bob")
+ const deviceB = await asUser("bob")
+ await gotoAfterUserWsAuth(deviceA.page, "/c/me")
+ await gotoAfterUserWsAuth(deviceB.page, "/c/me")
+ await deviceA.page.evaluate(() => {
+ let qaVisibility: DocumentVisibilityState = "visible"
+ Object.defineProperty(document, "visibilityState", {
+ configurable: true,
+ get: () => qaVisibility,
+ })
+ Object.defineProperty(window, "__alookQaSetVisibility", {
+ configurable: true,
+ value: (next: DocumentVisibilityState) => {
+ qaVisibility = next
+ document.dispatchEvent(new Event("visibilitychange"))
+ },
+ })
+ })
+ const setDeviceAVisibility = async (state: "hidden" | "visible") => {
+ await deviceA.page.evaluate((nextState) => {
+ const setter = (window as Window & {
+ __alookQaSetVisibility?: (state: DocumentVisibilityState) => void
+ }).__alookQaSetVisibility
+ if (!setter) throw new Error("QA visibility setter missing")
+ setter(nextState)
+ }, state)
+ await expect.poll(() => deviceA.page.evaluate(() => document.visibilityState))
+ .toBe(state)
+ }
+ const accountSnapshot = async () => await (await deviceB.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ const scopedSeq = (
+ snapshot: Awaited<ReturnType<typeof accountSnapshot>>,
+ targetChannelId: string,
+ ) => snapshot.readStates.find((row) => row.channelId === targetChannelId)?.lastReadSeq ?? 0
+
+ await deviceB.page.getByRole("button", { name: "Inbox" }).click()
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
+
+ const beforeChannel = await accountSnapshot()
+ const channelReadResponses: number[] = []
+ const trackChannelReads = (response: { request: () => { method: () => string }; url: () => string; status: () => number }) => {
+ if (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`
+ ) channelReadResponses.push(response.status())
+ }
+ deviceA.page.on("response", trackChannelReads)
+ await setDeviceAVisibility("hidden")
+ await deviceA.page.getByTestId(tid.serverIcon(serverId)).click()
+ await expect(deviceA.page.getByTestId(tid.channelRow(channelId))).toBeVisible()
+ await deviceA.page.getByTestId(tid.channelRow(channelId)).evaluate((element) => {
+ ;(element as HTMLElement).click()
+ })
+ await expect.poll(() => new URL(deviceA.page.url()).pathname, { timeout: 20_000 })
+ .toBe(`/c/channels/${serverId}/${channelId}`)
+ await expect.poll(() => deviceA.page.evaluate(() => document.visibilityState)).toBe("hidden")
+ await expect(deviceA.page.getByText(channelBody, { exact: true })).toBeVisible()
+ await deviceA.page.waitForTimeout(1_000)
+ expect(channelReadResponses).toEqual([])
+ const hiddenChannel = await accountSnapshot()
+ expect(hiddenChannel.revision).toBe(beforeChannel.revision)
+ expect(scopedSeq(hiddenChannel, channelId)).toBe(scopedSeq(beforeChannel, channelId))
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
+
+ const visibleChannelRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`,
+ )
+ await setDeviceAVisibility("visible")
+ expect((await visibleChannelRead).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ deviceA.page.off("response", trackChannelReads)
+
+ await deviceA.page.getByTestId(tid.homeButton).click()
+ await expect.poll(() => new URL(deviceA.page.url()).pathname).toMatch(/^\/c\/me(?:\/|$)/)
+ await expect(deviceA.page.getByTestId(tid.dmRow(dmId))).toBeVisible()
+ const beforeDm = await accountSnapshot()
+ const dmReadResponses: number[] = []
+ const trackDmReads = (response: { request: () => { method: () => string }; url: () => string; status: () => number }) => {
+ if (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${dmId}/read`
+ ) dmReadResponses.push(response.status())
+ }
+ deviceA.page.on("response", trackDmReads)
+ await setDeviceAVisibility("hidden")
+ await deviceA.page.getByTestId(tid.dmRow(dmId)).click()
+ await expect.poll(() => new URL(deviceA.page.url()).pathname, { timeout: 20_000 })
+ .toBe(`/c/me/${dmId}`)
+ await expect.poll(() => deviceA.page.evaluate(() => document.visibilityState)).toBe("hidden")
+ await expect(deviceA.page.getByText(dmBody, { exact: true })).toBeVisible()
+ await deviceA.page.waitForTimeout(1_000)
+ expect(dmReadResponses).toEqual([])
+ const hiddenDm = await accountSnapshot()
+ expect(hiddenDm.revision).toBe(beforeDm.revision)
+ expect(scopedSeq(hiddenDm, dmId)).toBe(scopedSeq(beforeDm, dmId))
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
+
+ const visibleDmRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${dmId}/read`,
+ )
+ await setDeviceAVisibility("visible")
+ expect((await visibleDmRead).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadDm(dmId))).toHaveCount(0)
+ deviceA.page.off("response", trackDmReads)
+})
+
+test("a visible live tail clears both devices while an unseen tail stays unread", async ({ asUser }) => {
+ test.setTimeout(180_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Visible read sync ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `visible-sync-${stamp}`)
+ const siblingId = await seedChannel("alice", serverId, `visible-sibling-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ for (let index = 0; index < 28; index += 1) {
+ await seedMessage("alice", channelId, `visible baseline ${index} ${stamp}`)
+ }
+
+ const deviceA = await asUser("bob")
+ const deviceB = await asUser("bob")
+ const proxyA = await proxyCommunityWebSockets(deviceA.context)
+ const proxyB = await proxyCommunityWebSockets(deviceB.context)
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${channelId}`)
+ await gotoAfterUserWsAuth(deviceB.page, `/c/channels/${serverId}/${siblingId}`)
+ await deviceB.page.getByRole("button", { name: "Inbox" }).click()
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
+
+ const scroller = deviceA.page
+ .locator("[data-onboarding-target='channel-composer']")
+ .locator("xpath=ancestor::main[1]")
+ .locator(".thin-scrollbar")
+ .first()
+ await expect(deviceA.page.getByTestId(tid.scrollToPresent)).toBeVisible()
+ const baselineRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`,
+ )
+ await deviceA.page.getByTestId(tid.scrollToPresent).click()
+ await expect(deviceA.page.getByTestId(tid.scrollToPresent)).toHaveCount(0)
+ expect((await baselineRead).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+
+ const visibleStarts = [proxyA.frames.length, proxyB.frames.length]
+ const visibleRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`,
+ )
+ const visibleBody = `visible live tail ${stamp}`
+ await seedMessage("alice", channelId, visibleBody)
+ await expect(deviceA.page.getByText(visibleBody, { exact: true })).toBeVisible()
+ for (const [proxy, start] of [[proxyA, visibleStarts[0]], [proxyB, visibleStarts[1]]] as const) {
+ await expect.poll(() => unreadBumpsSince(proxy.frames, start!, channelId).length, {
+ timeout: 20_000,
+ }).toBeGreaterThan(0)
+ }
+ expect((await visibleRead).status()).toBe(200)
+ await expect.poll(() => readStateEventsSince(proxyB.frames, visibleStarts[1]!).length, {
+ timeout: 20_000,
+ }).toBeGreaterThan(0)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+
+ const setDeviceAVisibility = async (state: "hidden" | "visible") => {
+ await deviceA.page.evaluate((nextState) => {
+ Object.defineProperty(document, "visibilityState", {
+ configurable: true,
+ get: () => nextState,
+ })
+ document.dispatchEvent(new Event("visibilitychange"))
+ }, state)
+ await expect.poll(() => deviceA.page.evaluate(() => document.visibilityState))
+ .toBe(state)
+ }
+ const beforeHidden = await (await deviceA.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ const beforeHiddenSeq = beforeHidden.readStates
+ .find((row) => row.channelId === channelId)?.lastReadSeq
+ expect(beforeHiddenSeq).toBeGreaterThan(0)
+
+ const hiddenReadResponses: number[] = []
+ const trackHiddenReads = (response: { request: () => { method: () => string }; url: () => string; status: () => number }) => {
+ if (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`
+ ) hiddenReadResponses.push(response.status())
+ }
+ deviceA.page.on("response", trackHiddenReads)
+ await setDeviceAVisibility("hidden")
+ const hiddenStarts = [proxyA.frames.length, proxyB.frames.length]
+ const hiddenBody = `hidden live tail ${stamp}`
+ await seedMessage("alice", channelId, hiddenBody)
+ await expect(deviceA.page.getByText(hiddenBody, { exact: true })).toBeVisible()
+ for (const [proxy, start] of [[proxyA, hiddenStarts[0]], [proxyB, hiddenStarts[1]]] as const) {
+ await expect.poll(() => unreadBumpsSince(proxy.frames, start!, channelId).length, {
+ timeout: 20_000,
+ }).toBeGreaterThan(0)
+ }
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
+ await deviceA.page.waitForTimeout(1_000)
+ expect(hiddenReadResponses).toEqual([])
+ const afterHidden = await (await deviceA.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ expect(afterHidden.revision).toBe(beforeHidden.revision)
+ expect(afterHidden.readStates.find((row) => row.channelId === channelId)?.lastReadSeq)
+ .toBe(beforeHiddenSeq)
+
+ const foregroundRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`,
+ )
+ await setDeviceAVisibility("visible")
+ expect((await foregroundRead).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ deviceA.page.off("response", trackHiddenReads)
+
+ const beforeUnseen = await (await deviceA.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ const beforeUnseenSeq = beforeUnseen.readStates.find((row) => row.channelId === channelId)?.lastReadSeq
+ expect(beforeUnseenSeq).toBeGreaterThan(0)
+
+ await scroller.evaluate((element) => {
+ element.scrollTop = 0
+ element.dispatchEvent(new Event("scroll"))
+ })
+ await expect(deviceA.page.getByTestId(tid.scrollToPresent)).toBeVisible()
+ const unseenReadResponses: number[] = []
+ const trackUnseenReads = (response: { request: () => { method: () => string }; url: () => string; status: () => number }) => {
+ if (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`
+ ) unseenReadResponses.push(response.status())
+ }
+ deviceA.page.on("response", trackUnseenReads)
+ const unseenStarts = [proxyA.frames.length, proxyB.frames.length]
+ const unseenBody = `unseen live tail ${stamp}`
+ await seedMessage("alice", channelId, unseenBody)
+ for (const [proxy, start] of [[proxyA, unseenStarts[0]], [proxyB, unseenStarts[1]]] as const) {
+ await expect.poll(() => unreadBumpsSince(proxy.frames, start!, channelId).length, {
+ timeout: 20_000,
+ }).toBeGreaterThan(0)
+ }
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
+ await deviceA.page.waitForTimeout(1_000)
+ expect(unseenReadResponses).toEqual([])
+ const afterUnseen = await (await deviceA.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ expect(afterUnseen.revision).toBe(beforeUnseen.revision)
+ expect(afterUnseen.readStates.find((row) => row.channelId === channelId)?.lastReadSeq)
+ .toBe(beforeUnseenSeq)
+
+ const catchUpRead = deviceA.page.waitForResponse((response) =>
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/read`,
+ )
+ await deviceA.page.getByTestId(tid.scrollToPresent).click()
+ expect((await catchUpRead).status()).toBe(200)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ deviceA.page.off("response", trackUnseenReads)
+})
+
+test("forum cards use the ordinary parent cursor while child cursors stay independent", async ({ asUser }) => {
+ test.setTimeout(180_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Unified forum sync ${stamp}`)
+ const forumId = await seedChannel("alice", serverId, `unified-forum-${stamp}`, "forum")
+ await seedJoinServer("alice", "bob", serverId)
+
+ const alice = await asUser("alice")
+ const createEmptyPost = async (label: string) => {
+ const response = await alice.page.request.post(
+ `/api/community/channels/${forumId}/messages`,
+ { data: { content: label, nonce: `e2e:${crypto.randomUUID()}:opener` } },
+ )
+ expect(response.status()).toBe(201)
+ return await response.json() as { threadId: string }
+ }
+ const first = await createEmptyPost(`Unified first ${stamp}`)
+ const second = await createEmptyPost(`Unified second ${stamp}`)
+
+ const deviceA = await asUser("bob")
+ const deviceB = await asUser("bob")
+ const proxyA = await proxyCommunityWebSockets(deviceA.context)
+ const proxyB = await proxyCommunityWebSockets(deviceB.context)
+ await gotoAfterUserWsAuth(deviceB.page, "/c/me")
+
+ const threadsResponse = await deviceA.page.request.get(
+ `/api/community/channels/${forumId}/threads?order=createdAt&limit=50`,
+ )
+ expect(threadsResponse.status()).toBe(200)
+ const threads = await threadsResponse.json() as {
+ threads: Array<{ id: string; parentMessageId: string | null }>
+ }
+ const firstOpener = threads.threads.find((thread) => thread.id === first.threadId)?.parentMessageId
+ const secondOpener = threads.threads.find((thread) => thread.id === second.threadId)?.parentMessageId
+ expect(firstOpener).toBeTruthy()
+ expect(secondOpener).toBeTruthy()
+
+ const accountSnapshot = async () => await (await deviceA.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadSeq: number }>
+ }
+ const forumResponses: Array<{ target: string; status: number }> = []
+ const trackForumResponse = (response: {
+ request: () => { method: () => string }
+ url: () => string
+ status: () => number
+ }) => {
+ const url = new URL(response.url())
+ if (
+ response.request().method() === "PUT"
+ && url.pathname === `/api/community/channels/${forumId}/read`
+ ) {
+ const body = (response.request() as unknown as { postDataJSON: () => { lastReadMessageId: string } })
+ .postDataJSON()
+ forumResponses.push({ target: body.lastReadMessageId, status: response.status() })
+ }
+ }
+ deviceA.page.on("response", trackForumResponse)
+
+ const beforeVisible = await accountSnapshot()
+ const frameStarts = [proxyA.frames.length, proxyB.frames.length]
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${forumId}`)
+ await expect(deviceA.page.getByTestId(tid.forumThreadCard(first.threadId))).toBeVisible()
+ await expect(deviceA.page.getByTestId(tid.forumThreadCard(second.threadId))).toBeVisible()
+ await expect.poll(() => forumResponses.length, {
+ timeout: 20_000,
+ }).toBe(1)
+ await deviceA.page.waitForTimeout(1_200)
+ expect(forumResponses).toEqual([
+ { target: secondOpener!, status: 200 },
+ ])
+ const afterVisible = await accountSnapshot()
+ expect(afterVisible.revision).toBe(beforeVisible.revision + 1)
+ expect(afterVisible.readStates.find((row) => row.channelId === forumId)?.lastReadSeq)
+ .toBeGreaterThanOrEqual(2)
+ expect(afterVisible.readStates.some((row) => row.channelId === first.threadId)).toBe(false)
+ expect(afterVisible.readStates.some((row) => row.channelId === second.threadId)).toBe(false)
+ for (const [proxy, start] of [[proxyA, frameStarts[0]], [proxyB, frameStarts[1]]] as const) {
+ await expect.poll(() => readStateEventsSince(proxy.frames, start!).filter(
+ (event) => event.revision === afterVisible.revision,
+ ).length, { timeout: 20_000 }).toBe(1)
+ }
+
+ const beforeNavigationWrites = forumResponses.length
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${first.threadId}`)
+ await deviceA.page.waitForTimeout(1_200)
+ expect(forumResponses).toHaveLength(beforeNavigationWrites)
+ expect((await accountSnapshot()).revision).toBe(afterVisible.revision)
+
+ const directForumRead = await deviceA.page.request.put(
+ `/api/community/channels/${forumId}/read`,
+ { data: { lastReadMessageId: firstOpener } },
+ )
+ expect(directForumRead.status()).toBe(200)
+ expect(await directForumRead.json()).toMatchObject({ changed: false, revision: afterVisible.revision })
+
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${forumId}`)
+ const setDeviceAVisibility = async (state: "hidden" | "visible") => {
+ await deviceA.page.evaluate((next) => {
+ Object.defineProperty(document, "visibilityState", { configurable: true, value: next })
+ document.dispatchEvent(new Event("visibilitychange"))
+ }, state)
+ await expect.poll(() => deviceA.page.evaluate(() => document.visibilityState)).toBe(state)
+ }
+ await setDeviceAVisibility("hidden")
+ await deviceB.page.getByRole("button", { name: "Inbox" }).click()
+ const third = await createEmptyPost(`Unified third ${stamp}`)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(forumId))).toBeVisible()
+ await deviceA.page.waitForTimeout(1_200)
+ expect(forumResponses).toHaveLength(1)
+ expect((await accountSnapshot()).revision).toBe(afterVisible.revision)
+ await setDeviceAVisibility("visible")
+ await expect(deviceA.page.getByTestId(tid.forumThreadCard(third.threadId))).toBeVisible()
+ await expect.poll(() => forumResponses.length, { timeout: 20_000 }).toBe(2)
+ const afterThird = await accountSnapshot()
+ expect(afterThird.revision).toBe(afterVisible.revision + 1)
+ expect(afterThird.readStates.find((row) => row.channelId === forumId)?.lastReadSeq).toBe(3)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(forumId))).toHaveCount(0)
+ deviceA.page.off("response", trackForumResponse)
+})
+
+test("human author-send and notification writers replace both active profiles", async ({ asUser }) => {
+ test.setTimeout(150_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Writer sync ${stamp}`)
+ const authorChannelId = await seedChannel("alice", serverId, `author-sync-${stamp}`)
+ const notificationChannelId = await seedChannel("alice", serverId, `notify-sync-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedMessage("alice", authorChannelId, `author unread ${stamp}`)
+ await seedMessage("alice", notificationChannelId, `notification unread ${stamp}`)
+
+ const deviceA = await asUser("bob")
+ const deviceB = await asUser("bob")
+ const proxyA = await proxyCommunityWebSockets(deviceA.context)
+ const proxyB = await proxyCommunityWebSockets(deviceB.context)
+ await gotoAfterUserWsAuth(deviceA.page, "/c/me")
+ await gotoAfterUserWsAuth(deviceB.page, "/c/me")
+ await deviceB.page.getByRole("button", { name: "Inbox" }).click()
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(authorChannelId))).toBeVisible()
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()
+
+ const authorStarts = [proxyA.frames.length, proxyB.frames.length]
+ const authorStatus = await deviceA.page.evaluate(async ({ channelId, content }) => {
+ const response = await fetch(`/api/community/channels/${channelId}/messages`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ content }),
+ })
+ return response.status
+ }, { channelId: authorChannelId, content: `bob author send ${stamp}` })
+ expect(authorStatus).toBe(201)
+
+ for (const [proxy, start] of [[proxyA, authorStarts[0]], [proxyB, authorStarts[1]]] as const) {
+ await expect.poll(() => readStateEventsSince(proxy.frames, start!).length, {
+ timeout: 20_000,
+ }).toBe(1)
+ const event = readStateEventsSince(proxy.frames, start!)[0]!
+ expect("readStates" in event).toBe(false)
+ }
+ const authorEvents = [
+ readStateEventsSince(proxyA.frames, authorStarts[0]!)[0]!,
+ readStateEventsSince(proxyB.frames, authorStarts[1]!)[0]!,
+ ]
+ expect(authorEvents[0].revision).toBe(authorEvents[1].revision)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(authorChannelId))).toHaveCount(0)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toBeVisible()
+
+ const notificationStarts = [proxyA.frames.length, proxyB.frames.length]
+ const notificationStatus = await deviceA.page.evaluate(async (channelId) => {
+ const response = await fetch(`/api/community/users/me/notifications/channel/${channelId}`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ level: "mentions" }),
+ })
+ return response.status
+ }, notificationChannelId)
+ expect(notificationStatus).toBe(200)
+
+ for (const [proxy, start] of [[proxyA, notificationStarts[0]], [proxyB, notificationStarts[1]]] as const) {
+ await expect.poll(() => readStateEventsSince(proxy.frames, start!).length, {
+ timeout: 20_000,
+ }).toBe(1)
+ const event = readStateEventsSince(proxy.frames, start!)[0]!
+ expect(event.revision).toBeGreaterThan(authorEvents[0].revision)
+ expect("readStates" in event).toBe(false)
+ }
+ const notificationEvents = [
+ readStateEventsSince(proxyA.frames, notificationStarts[0]!)[0]!,
+ readStateEventsSince(proxyB.frames, notificationStarts[1]!)[0]!,
+ ]
+ expect(notificationEvents[0].revision).toBe(notificationEvents[1].revision)
+ await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(notificationChannelId))).toHaveCount(0)
+
+ const writerSnapshot = await (await deviceB.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ expect(writerSnapshot.readStates.find((state) => state.channelId === authorChannelId)?.lastReadSeq)
+ .toBeGreaterThan(0)
+ expect(writerSnapshot.readStates.find((state) => state.channelId === notificationChannelId)?.lastReadSeq)
+ .toBeGreaterThan(0)
+})
+
+test("forum delete broadcasts replacement and removal to both active profiles", async ({ asUser }) => {
+ test.setTimeout(150_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Forum read sync ${stamp}`)
+ const forumId = await seedChannel("alice", serverId, `forum-read-sync-${stamp}`, "forum")
+ await seedJoinServer("alice", "bob", serverId)
+ const priorChildId = await seedForumThread("alice", forumId, "Prior post", "prior body")
+ const deletedChildId = await seedForumThread("bob", forumId, "Delete my post", "delete body")
+
+ const deviceA = await asUser("bob")
+ const deviceB = await asUser("bob")
+ const proxyA = await proxyCommunityWebSockets(deviceA.context)
+ const proxyB = await proxyCommunityWebSockets(deviceB.context)
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${deletedChildId}`)
+ await gotoAfterUserWsAuth(deviceB.page, `/c/channels/${serverId}/${forumId}`)
+ await expect(deviceB.page.getByTestId(tid.forumThreadCard(deletedChildId))).toBeVisible()
+
+ const threadsResponse = await deviceB.page.request.get(
+ `/api/community/channels/${forumId}/threads?order=createdAt&limit=50`,
+ )
+ expect(threadsResponse.status()).toBe(200)
+ const threads = (await threadsResponse.json()) as {
+ threads: Array<{ id: string; parentMessageId: string | null }>
+ }
+ const priorOpenerId = threads.threads.find((thread) => thread.id === priorChildId)?.parentMessageId
+ const deletedOpenerId = threads.threads.find((thread) => thread.id === deletedChildId)?.parentMessageId
+ expect(priorOpenerId).toBeTruthy()
+ expect(deletedOpenerId).toBeTruthy()
+
+ const beforeDeleteSnapshot = await (await deviceB.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as { revision: number }
+
+ const starts = [proxyA.frames.length, proxyB.frames.length]
+ const deleteStatus = await deviceA.page.evaluate(async (messageId) => {
+ const response = await fetch(`/api/community/messages/${messageId}`, { method: "DELETE" })
+ return response.status
+ }, deletedOpenerId!)
+ expect(deleteStatus).toBe(204)
+
+ for (const [proxy, start] of [[proxyA, starts[0]], [proxyB, starts[1]]] as const) {
+ await expect.poll(() => readStateEventsSince(proxy.frames, start!)
+ .filter((event) => event.revision > beforeDeleteSnapshot.revision).length, {
+ timeout: 20_000,
+ }).toBeGreaterThan(0)
+ }
+ const eventsByProfile = [
+ readStateEventsSince(proxyA.frames, starts[0]!)
+ .filter((event) => event.revision > beforeDeleteSnapshot.revision),
+ readStateEventsSince(proxyB.frames, starts[1]!)
+ .filter((event) => event.revision > beforeDeleteSnapshot.revision),
+ ]
+ expect(eventsByProfile.flat().every((event) => !("readStates" in event))).toBe(true)
+ const profileBRevisions = new Set(eventsByProfile[1].map((event) => event.revision))
+ expect(eventsByProfile[0].some((event) => profileBRevisions.has(event.revision))).toBe(true)
+ const deletedSnapshot = await (await deviceB.page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as {
+ revision: number
+ readStates: Array<{ channelId: string; lastReadMessageId: string | null }>
+ }
+ expect(deletedSnapshot.revision).toBeGreaterThan(beforeDeleteSnapshot.revision)
+ await expect.poll(() => [proxyA, proxyB].every((proxy, index) =>
+ readStateEventsSince(proxy.frames, starts[index]!)
+ .some((event) => event.revision === deletedSnapshot.revision)), {
+ timeout: 20_000,
+ }).toBe(true)
+ expect(deletedSnapshot.readStates.some((state) => state.channelId === deletedChildId)).toBe(false)
+ expect(deletedSnapshot.readStates.find((state) => state.channelId === forumId)?.lastReadMessageId)
+ .toBe(priorOpenerId)
+ await expect(deviceB.page.getByTestId(tid.forumThreadCard(deletedChildId))).toHaveCount(0)
+})
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
index 95c1ca7a2..af0070e54 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-ws-proxy.ts
@@ -27,6 +27,7 @@ export type CommunityWsProxy = {
heldCount: () => number
releaseHeld: (predicate?: (frame: CapturedCommunityFrame) => boolean) => number
replay: (frame: CapturedCommunityFrame) => void
+ disconnect: () => Promise<void>
}
export type CommunityWsProxyOptions = {
@@ -100,6 +101,17 @@ export async function proxyCommunityWebSockets(
if (!message || !activeClient) throw new Error("community frame is not replayable")
activeClient.send(message)
},
+ /* istanbul ignore next -- retained offline/reconnect Chromium journey */
+ disconnect: async () => {
+ /* istanbul ignore next -- retained offline/reconnect Chromium journey */
+ if (!activeClient) return
+ /* istanbul ignore next -- retained offline/reconnect Chromium journey */
+ const client = activeClient
+ /* istanbul ignore next -- retained offline/reconnect Chromium journey */
+ activeClient = undefined
+ /* istanbul ignore next -- retained offline/reconnect Chromium journey */
+ await client.close({ code: 1012, reason: "test transport offline" })
+ },
}
}
diff --git a/src/web/test-runtime/community-delete-media.runtime.test.ts b/src/web/test-runtime/community-delete-media.runtime.test.ts
index b37be2658..6f4570009 100644
--- a/src/web/test-runtime/community-delete-media.runtime.test.ts
+++ b/src/web/test-runtime/community-delete-media.runtime.test.ts
@@ -96,6 +96,16 @@ describe("existing delete media real D1 batches", () => {
`att_pending_child_${stamp}`, owner, child,
`att_other_${stamp}`, unrelatedMessage, owner, unrelated,
)
+ await run(
+ `INSERT INTO community_read_state
+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq) VALUES
+ (?, ?, ?, '2026-08-23T00:00:00.000Z', ?, 1),
+ (?, ?, ?, '2026-08-23T00:00:00.000Z', ?, 1),
+ (?, ?, ?, '2026-08-23T00:00:00.000Z', ?, 1)`,
+ `rs_root_${stamp}`, owner, root, rootMessage,
+ `rs_child_${stamp}`, owner, child, childMessage,
+ `rs_other_${stamp}`, owner, unrelated, unrelatedMessage,
+ )
const db = createDb(runtimeEnv.DB)
const results = await Promise.all([
@@ -109,6 +119,16 @@ describe("existing delete media real D1 batches", () => {
"root/original", "root/thumb", "child/original", "child/thumb",
"root/pending", "root/pending-thumb", "child/pending",
]))
+ expect(winner.readStateRevisions).toEqual([{ userId: owner, revision: 1 }])
+ await expect(queries.communityReadState.getAccountReadStateSnapshot(db, owner)).resolves.toEqual({
+ revision: 1,
+ readStates: [{
+ channelId: unrelated,
+ lastReadMessageId: unrelatedMessage,
+ lastReadAt: "2026-08-23T00:00:00.000Z",
+ lastReadSeq: 1,
+ }],
+ })
expect(results.find((result) => !result.deleted)?.mediaKeys).toEqual([])
expect(await first("SELECT id FROM community_channel WHERE id = ?", root)).toBeNull()
expect(await first("SELECT id FROM community_channel WHERE id = ?", child)).toBeNull()
@@ -137,12 +157,18 @@ describe("existing delete media real D1 batches", () => {
`att_server_${stamp}`, message, owner, channel,
`att_server_pending_${stamp}`, owner, channel,
)
+ await run(
+ `INSERT INTO community_read_state
+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
+ VALUES (?, ?, ?, '2026-08-23T00:00:00.000Z', ?, 1)`,
+ `rs_server_${stamp}`, owner, channel, message,
+ )
const db = createDb(runtimeEnv.DB)
await expect(queries.communityDeleteMedia.deleteServerWithMedia(db, {
serverId: server,
ownerId: "not-owner",
- })).resolves.toEqual({ deleted: false, mediaKeys: [], iconKey: null })
+ })).resolves.toEqual({ deleted: false, mediaKeys: [], iconKey: null, readStateRevisions: [] })
const results = await Promise.all([
queries.communityDeleteMedia.deleteServerWithMedia(db, { serverId: server, ownerId: owner }),
@@ -153,11 +179,13 @@ describe("existing delete media real D1 batches", () => {
deleted: true,
mediaKeys: ["server/original", "server/thumb", "server/pending"],
iconKey: icon,
+ readStateRevisions: [{ userId: owner, revision: 1 }],
})
expect(results.find((result) => !result.deleted)).toEqual({
deleted: false,
mediaKeys: [],
iconKey: null,
+ readStateRevisions: [],
})
expect(await first("SELECT id FROM community_server WHERE id = ?", server)).toBeNull()
})
@@ -267,7 +295,7 @@ describe("guarded pending insert and server icon CAS in real D1", () => {
await expect(queries.communityDeleteMedia.deleteServerWithMedia(db, {
serverId: server,
ownerId: owner,
- })).resolves.toEqual({ deleted: true, mediaKeys: [], iconKey: replacement })
+ })).resolves.toEqual({ deleted: true, mediaKeys: [], iconKey: replacement, readStateRevisions: [] })
})
it("linearizes server deletion before a stale icon replacement at the delete", async () => {
@@ -278,7 +306,7 @@ describe("guarded pending insert and server icon CAS in real D1", () => {
await expect(queries.communityDeleteMedia.deleteServerWithMedia(db, {
serverId: server,
ownerId: owner,
- })).resolves.toEqual({ deleted: true, mediaKeys: [], iconKey: original })
+ })).resolves.toEqual({ deleted: true, mediaKeys: [], iconKey: original, readStateRevisions: [] })
await expect(queries.communityServer.updateServerIconIfCurrent(db, {
serverId: server,
expectedIcon: original,
diff --git a/src/web/test-runtime/forum-post-delete.runtime.test.ts b/src/web/test-runtime/forum-post-delete.runtime.test.ts
index 63f936df6..f6d686b0e 100644
--- a/src/web/test-runtime/forum-post-delete.runtime.test.ts
+++ b/src/web/test-runtime/forum-post-delete.runtime.test.ts
@@ -16,6 +16,11 @@ async function first<T>(statement: string, ...bindings: unknown[]): Promise<T |
return runtimeEnv.DB.prepare(statement).bind(...bindings).first<T>();
}
+async function all<T>(statement: string, ...bindings: unknown[]): Promise<T[]> {
+ const result = await runtimeEnv.DB.prepare(statement).bind(...bindings).all<T>();
+ return result.results;
+}
+
function ids() {
const stamp = crypto.randomUUID().replaceAll("-", "");
return {
@@ -143,6 +148,58 @@ async function seedCanonicalPost() {
return { id, t2 };
}
+async function snapshotDestructiveAuthority(
+ id: ReturnType<typeof ids>,
+ userIds: string[],
+) {
+ const userPlaceholders = userIds.map(() => "?").join(", ");
+ return {
+ channels: await all(
+ `SELECT id, parent_channel_id, parent_message_id, message_count, last_message_at
+ FROM community_channel
+ WHERE id IN (?, ?)
+ ORDER BY id`,
+ id.forum,
+ id.child,
+ ),
+ messages: await all(
+ `SELECT id, channel_id, seq
+ FROM community_message
+ WHERE id IN (?, ?)
+ ORDER BY id`,
+ id.opener,
+ id.reply,
+ ),
+ readStates: await all(
+ `SELECT user_id, channel_id, last_read_message_id, last_read_seq, last_read_at
+ FROM community_read_state
+ WHERE user_id IN (${userPlaceholders})
+ AND channel_id IN (?, ?)
+ ORDER BY user_id, channel_id`,
+ ...userIds,
+ id.forum,
+ id.child,
+ ),
+ mentions: await all(
+ `SELECT message_id, user_id, read
+ FROM community_mention
+ WHERE user_id IN (${userPlaceholders})
+ AND message_id IN (?, ?)
+ ORDER BY user_id, message_id`,
+ ...userIds,
+ id.opener,
+ id.reply,
+ ),
+ revisions: await all(
+ `SELECT user_id, revision
+ FROM community_read_state_revision
+ WHERE user_id IN (${userPlaceholders})
+ ORDER BY user_id`,
+ ...userIds,
+ ),
+ };
+}
+
function stamp4(value: string): string {
let hash = 0;
for (const char of value) hash = (hash * 31 + char.charCodeAt(0)) % 10_000;
@@ -159,6 +216,81 @@ afterEach(async () => {
});
describe("deleteForumPost real D1 batch", () => {
+ it("deletes without a revision statement when no human read-state effect exists", async () => {
+ const { id } = await seedCanonicalPost();
+ await run(
+ "DELETE FROM community_mention WHERE message_id IN (?, ?)",
+ id.opener,
+ id.reply,
+ );
+ await run(
+ "DELETE FROM community_read_state WHERE channel_id IN (?, ?)",
+ id.forum,
+ id.child,
+ );
+
+ const db = createDb(runtimeEnv.DB);
+ const result = await queries.communityForumPostDelete.deleteForumPost(db, {
+ openerId: id.opener,
+ openerSeq: 3,
+ forumChannelId: id.forum,
+ childChannelId: id.child,
+ });
+
+ expect(result.deleted).toBe(true);
+ expect(result.readStateRevisions).toEqual([]);
+ expect(await first("SELECT id FROM community_message WHERE id = ?", id.opener)).toBeNull();
+ expect(await first("SELECT id FROM community_channel WHERE id = ?", id.child)).toBeNull();
+ });
+
+ it("versions mention-only owners and repairs every ordinary pointer in one delete batch", async () => {
+ const { id, t2 } = await seedCanonicalPost();
+ const mentionOnly = `fpd_mention_${crypto.randomUUID().replaceAll("-", "")}`;
+ createdUsers.push(mentionOnly);
+ await run(
+ "INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, 'Mention', ?)",
+ mentionOnly,
+ `${mentionOnly}@example.com`,
+ stamp4(mentionOnly),
+ );
+ await run(
+ `INSERT INTO community_mention (id, message_id, user_id, kind, read)
+ VALUES (?, ?, ?, 'mention', 0)`,
+ `mention_only_${id.opener}`,
+ id.opener,
+ mentionOnly,
+ );
+
+ const db = createDb(runtimeEnv.DB);
+ const result = await queries.communityMessage.hardDeleteMessage(db, id.opener);
+
+ expect(new Set(result?.readStateRevisions.map((row) => row.userId))).toEqual(
+ new Set([id.owner, id.reader, mentionOnly]),
+ );
+ for (const userId of [id.owner, id.reader]) {
+ expect(await first<{ lastReadMessageId: string; lastReadSeq: number }>(
+ `SELECT last_read_message_id AS lastReadMessageId,
+ last_read_seq AS lastReadSeq
+ FROM community_read_state
+ WHERE user_id = ? AND channel_id = ?`,
+ userId,
+ id.forum,
+ )).toEqual({ lastReadMessageId: id.siblingOpener, lastReadSeq: 2 });
+ }
+ await expect(queries.communityReadState.getAccountReadStateSnapshot(
+ db,
+ mentionOnly,
+ )).resolves.toEqual({
+ revision: 1,
+ readStates: [],
+ });
+ expect(await first("SELECT id FROM community_message WHERE id = ?", id.opener)).toBeNull();
+ expect(await first<{ message_count: number; last_message_at: string }>(
+ "SELECT message_count, last_message_at FROM community_channel WHERE id = ?",
+ id.forum,
+ )).toEqual({ message_count: 2, last_message_at: t2 });
+ });
+
it("captures all media keys, repairs parent truth, and cascades only the selected post", async () => {
const { id, t2 } = await seedCanonicalPost();
const db = createDb(runtimeEnv.DB);
@@ -206,10 +338,188 @@ describe("deleteForumPost real D1 batch", () => {
last_read_seq: 2,
last_read_at: t2,
});
+ expect(result.readStateRevisions).toHaveLength(2);
+ for (const revision of result.readStateRevisions) {
+ expect(revision.revision).toBe(1);
+ await expect(queries.communityReadState.getAccountReadStateSnapshot(
+ db,
+ revision.userId,
+ )).resolves.toEqual({
+ revision: 1,
+ readStates: [{
+ channelId: id.forum,
+ lastReadMessageId: id.siblingOpener,
+ lastReadSeq: 2,
+ lastReadAt: t2,
+ }],
+ });
+ }
+ expect(new Set(result.readStateRevisions.map((revision) => revision.userId))).toEqual(
+ new Set([id.owner, id.reader]),
+ );
expect(await first("SELECT id FROM community_channel WHERE id = ?", id.siblingChild)).not.toBeNull();
expect(await first("SELECT id FROM community_message WHERE id = ?", id.siblingOpener)).not.toBeNull();
});
+ it("makes a delete-first/read-second race a generic no-op without reviving an orphan cursor", async () => {
+ const { id } = await seedCanonicalPost();
+ await run(
+ `INSERT INTO community_mention (id, message_id, user_id, kind, read)
+ VALUES (?, ?, ?, 'mention', 0)`,
+ `mention_prior_${id.opener}`,
+ id.prior,
+ id.owner,
+ );
+ const target = await first<{
+ id: string;
+ channelId: string;
+ createdAt: string;
+ seq: number;
+ }>(
+ `SELECT id, channel_id AS channelId, created_at AS createdAt, seq
+ FROM community_message WHERE id = ?`,
+ id.opener,
+ );
+ expect(target).not.toBeNull();
+
+ const db = createDb(runtimeEnv.DB);
+ await expect(queries.communityForumPostDelete.deleteForumPost(db, {
+ openerId: id.opener,
+ openerSeq: 3,
+ forumChannelId: id.forum,
+ childChannelId: id.child,
+ })).resolves.toMatchObject({ deleted: true });
+
+ const beforeSnapshot = await queries.communityReadState.getAccountReadStateSnapshot(db, id.owner);
+ const beforeMention = await first<{ read: number }>(
+ "SELECT read FROM community_mention WHERE message_id = ? AND user_id = ?",
+ id.prior,
+ id.owner,
+ );
+ const targetExists = queries.communityReadState.canonicalReadTargetExistsCondition(db, target!);
+ const results = await db.batch([
+ queries.communityReadState.advanceReadStateRevisionWhenAnyBuilder(
+ db,
+ id.owner,
+ [
+ queries.communityReadState.readStateAdvancesCondition(db, {
+ userId: id.owner,
+ channelId: id.forum,
+ targetSeq: target!.seq,
+ }, targetExists),
+ queries.communityMention.unreadChannelMentionThroughSeqCondition(
+ db,
+ id.owner,
+ id.forum,
+ target!.seq,
+ targetExists,
+ ),
+ ],
+ ),
+ queries.communityReadState.markReadToExistingMessageBuilder(db, {
+ userId: id.owner,
+ channelId: id.forum,
+ message: target!,
+ }),
+ queries.communityMention.markChannelMentionsReadBuilder(
+ db,
+ id.owner,
+ id.forum,
+ target!.seq,
+ targetExists,
+ ),
+ queries.communityReadState.accountReadStateRevisionBuilder(db, id.owner),
+ ] as any) as unknown[];
+
+ expect(results[0]).toEqual([]);
+ await expect(queries.communityReadState.getAccountReadStateSnapshot(db, id.owner))
+ .resolves.toEqual(beforeSnapshot);
+ expect(await first<{ read: number }>(
+ "SELECT read FROM community_mention WHERE message_id = ? AND user_id = ?",
+ id.prior,
+ id.owner,
+ )).toEqual(beforeMention);
+ expect(await first(
+ `SELECT rs.id
+ FROM community_read_state AS rs
+ LEFT JOIN community_message AS message
+ ON message.id = rs.last_read_message_id
+ WHERE rs.user_id = ? AND message.id IS NULL`,
+ id.owner,
+ )).toBeNull();
+ });
+
+ it.each([
+ ["parent repair", "community_read_state"],
+ ["child cascade", "community_channel"],
+ ] as const)("rolls back the whole combined delete when the %s statement fails", async (_label, failureScope) => {
+ const { id } = await seedCanonicalPost();
+ const foreign = `fpd_foreign_${crypto.randomUUID().replaceAll("-", "")}`;
+ createdUsers.push(foreign);
+ await run(
+ "INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, 'Foreign', ?)",
+ foreign,
+ `${foreign}@example.com`,
+ stamp4(foreign),
+ );
+
+ // A owns the parent pointer, child pointer, and mentions on both sides.
+ await run(
+ `INSERT INTO community_read_state
+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
+ VALUES (?, ?, ?, '2026-08-23T01:03:00.000Z', ?, 1)`,
+ `rs_owner_child_${id.opener}`,
+ id.owner,
+ id.child,
+ id.reply,
+ );
+ await run(
+ `INSERT INTO community_mention (id, message_id, user_id, kind, read)
+ VALUES (?, ?, ?, 'mention', 0)`,
+ `mention_parent_${id.opener}`,
+ id.opener,
+ id.owner,
+ );
+ // B is child-only; foreign owns no scoped authority.
+ await run(
+ "DELETE FROM community_read_state WHERE user_id = ? AND channel_id = ?",
+ id.reader,
+ id.forum,
+ );
+
+ const audience = [id.owner, id.reader, foreign];
+ const before = await snapshotDestructiveAuthority(id, audience);
+ const triggerName = `force_fpd_${failureScope}_${crypto.randomUUID().replaceAll("-", "")}`;
+ const triggerSql = failureScope === "community_read_state"
+ ? `CREATE TRIGGER ${triggerName}
+ BEFORE UPDATE ON community_read_state
+ WHEN OLD.channel_id = '${id.forum}'
+ AND OLD.last_read_message_id = '${id.opener}'
+ BEGIN SELECT RAISE(ABORT, 'forced parent statement failure'); END`
+ : `CREATE TRIGGER ${triggerName}
+ BEFORE DELETE ON community_channel
+ WHEN OLD.id = '${id.child}'
+ BEGIN SELECT RAISE(ABORT, 'forced child statement failure'); END`;
+
+ await run(triggerSql);
+ try {
+ const db = createDb(runtimeEnv.DB);
+ await expect(queries.communityForumPostDelete.deleteForumPost(db, {
+ openerId: id.opener,
+ openerSeq: 3,
+ forumChannelId: id.forum,
+ childChannelId: id.child,
+ })).rejects.toThrow(failureScope === "community_read_state"
+ ? "forced parent statement failure"
+ : "forced child statement failure");
+
+ expect(await snapshotDestructiveAuthority(id, audience)).toEqual(before);
+ expect(await all("PRAGMA foreign_key_check")).toEqual([]);
+ } finally {
+ await run(`DROP TRIGGER IF EXISTS ${triggerName}`);
+ }
+ });
+
it("serializes concurrent winners without double-decrementing or returning duplicate cleanup keys", async () => {
const { id, t2 } = await seedCanonicalPost();
const db = createDb(runtimeEnv.DB);
@@ -233,4 +543,132 @@ describe("deleteForumPost real D1 batch", () => {
)).toEqual({ message_count: 2, last_message_at: t2 });
expect(await first("SELECT id FROM community_channel WHERE id = ?", id.child)).toBeNull();
});
+
+ it("re-enumerates when a new human enters the destructive scope before batch commit", async () => {
+ const { id, t2 } = await seedCanonicalPost();
+ const lateReader = `fpd_late_${crypto.randomUUID().replaceAll("-", "")}`;
+ createdUsers.push(lateReader);
+ await run(
+ "INSERT INTO user (id, email, name, discriminator) VALUES (?, ?, 'Late', ?)",
+ lateReader,
+ `${lateReader}@example.com`,
+ stamp4(lateReader),
+ );
+
+ const baseDb = createDb(runtimeEnv.DB);
+ let injectBeforeFirstBatch = true;
+ const racedDb = new Proxy(baseDb, {
+ get(target, property, receiver) {
+ if (property === "batch") {
+ return async (statements: unknown[]) => {
+ if (injectBeforeFirstBatch) {
+ injectBeforeFirstBatch = false;
+ await run(
+ `INSERT INTO community_read_state
+ (id, user_id, channel_id, last_read_at, last_read_message_id, last_read_seq)
+ VALUES (?, ?, ?, '2026-08-23T01:02:00.000Z', ?, 3)`,
+ `rs_late_${id.opener}`,
+ lateReader,
+ id.forum,
+ id.opener,
+ );
+ expect(await first<{ isBot: number; lastReadMessageId: string }>(
+ `SELECT u."isBot" AS isBot, rs.last_read_message_id AS lastReadMessageId
+ FROM user AS u
+ INNER JOIN community_read_state AS rs ON rs.user_id = u.id
+ WHERE u.id = ?`,
+ lateReader,
+ )).toEqual({ isBot: 0, lastReadMessageId: id.opener });
+ }
+ return target.batch(statements as never[]);
+ };
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ });
+
+ const result = await queries.communityForumPostDelete.deleteForumPost(racedDb, {
+ openerId: id.opener,
+ openerSeq: 3,
+ forumChannelId: id.forum,
+ childChannelId: id.child,
+ });
+
+ expect(result.deleted).toBe(true);
+ expect(new Set(result.readStateRevisions.map((revision) => revision.userId))).toEqual(
+ new Set([id.owner, id.reader, lateReader]),
+ );
+ expect(result.readStateRevisions.find((revision) => revision.userId === lateReader)).toEqual({
+ userId: lateReader, revision: 1,
+ });
+ await expect(queries.communityReadState.getAccountReadStateSnapshot(
+ baseDb,
+ lateReader,
+ )).resolves.toEqual({
+ revision: 1,
+ readStates: [{
+ channelId: id.forum,
+ lastReadMessageId: id.siblingOpener,
+ lastReadAt: t2,
+ lastReadSeq: 2,
+ }],
+ });
+ });
+
+ it("returns the in-batch committed revision even when a later commit wins before result handling", async () => {
+ const { id } = await seedCanonicalPost();
+ const baseDb = createDb(runtimeEnv.DB);
+ const laterMessage = `fpd_later_${crypto.randomUUID().replaceAll("-", "")}`;
+ const laterTime = "2026-08-23T01:04:00.000Z";
+ let interleaveAfterFirstBatch = true;
+ const interleavedDb = new Proxy(baseDb, {
+ get(target, property, receiver) {
+ if (property === "batch") {
+ return async (statements: unknown[]) => {
+ const committedResults = await target.batch(statements as never[]);
+ if (interleaveAfterFirstBatch) {
+ interleaveAfterFirstBatch = false;
+ await runtimeEnv.DB.batch([
+ runtimeEnv.DB.prepare(
+ `INSERT INTO community_message
+ (id, author_id, content, created_at, channel_id, seq)
+ VALUES (?, ?, 'later', ?, ?, 4)`,
+ ).bind(laterMessage, id.owner, laterTime, id.forum),
+ runtimeEnv.DB.prepare(
+ `UPDATE community_read_state
+ SET last_read_at = ?, last_read_message_id = ?, last_read_seq = 4
+ WHERE user_id = ? AND channel_id = ?`,
+ ).bind(laterTime, laterMessage, id.owner, id.forum),
+ runtimeEnv.DB.prepare(
+ `UPDATE community_read_state_revision
+ SET revision = revision + 1 WHERE user_id = ?`,
+ ).bind(id.owner),
+ ]);
+ }
+ return committedResults;
+ };
+ }
+ return Reflect.get(target, property, receiver);
+ },
+ });
+
+ const result = await queries.communityForumPostDelete.deleteForumPost(interleavedDb, {
+ openerId: id.opener,
+ openerSeq: 3,
+ forumChannelId: id.forum,
+ childChannelId: id.child,
+ });
+
+ expect(result.readStateRevisions.find((revision) => revision.userId === id.owner))
+ .toEqual({ userId: id.owner, revision: 1 });
+ expect(await first<{ revision: number }>(
+ "SELECT revision FROM community_read_state_revision WHERE user_id = ?",
+ id.owner,
+ )).toEqual({ revision: 2 });
+ expect(await first<{ last_read_message_id: string; last_read_seq: number }>(
+ "SELECT last_read_message_id, last_read_seq FROM community_read_state WHERE user_id = ? AND channel_id = ?",
+ id.owner,
+ id.forum,
+ )).toEqual({ last_read_message_id: laterMessage, last_read_seq: 4 });
+ });
});
diff --git a/src/ws-do/src/community-browser-event-ingress.test.ts b/src/ws-do/src/community-browser-event-ingress.test.ts
index 17d32908b..456742d42 100644
--- a/src/ws-do/src/community-browser-event-ingress.test.ts
+++ b/src/ws-do/src/community-browser-event-ingress.test.ts
@@ -69,9 +69,9 @@ function worstEscapingTarget(index: number) {
}
describe("community browser event ingress", () => {
- it("normalizes all 41 current fixtures without a version field", () => {
+ it("normalizes all 43 current fixtures without a version field", () => {
const fixtures = Object.values(communityWsEventFixtures)
- expect(fixtures).toHaveLength(41)
+ expect(fixtures).toHaveLength(43)
for (const fixture of fixtures) {
const normalized = normalizeCommunityBrowserEvent(fixture)
expect(normalized).toMatchObject({ ok: true, event: fixture, envelope: fixture })