Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): unify unread on seq — inbox predicate EXISTS(seq>lastReadSeq)

Generb55b8cdd9a31
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.ts
index addda7968..802606c57 100644
--- a/src/shared/src/db/community-schema.ts
+++ b/src/shared/src/db/community-schema.ts
@@ -338,12 +338,15 @@ export const communityReadState = sqliteTable(
// INVARIANT: non-null whenever the row exists. Route writes through
// `markReadToMessageBuilder` — never null out.
lastReadMessageId: text("last_read_message_id"),
- // Shared per-user cursor for humans AND bots (bots ARE users invariant).
- // Populated by: the author read-watermark upsert inside `createMessage`
- // (every author, bot or human), and `bumpReadCursor` (agent `ack` route
- // only). NOT maintained by the human-only read routes
+ // Shared per-user cursor for humans AND bots (bots ARE users invariant) —
+ // and now the SINGLE unread ruler for both (ref/id read-model seq
+ // unification): the inbox unread predicate is `EXISTS(message.seq >
+ // lastReadSeq)`, the same seq compare the agent inbox uses. Maintained by
+ // EVERY read-state writer: `createMessage`'s author watermark, `bumpReadCursor`
+ // (agent ack), AND the human read routes
// (`markReadToMessageBuilder`/`markReadToMessage`/`markAllServerChannelsRead`)
- // — an explicit, documented gap, see plans/community-agent-cli-bridge.md §4.
+ // — the earlier "humans don't maintain it" gap is closed, or a human's read
+ // would never register under the seq predicate.
lastReadSeq: integer("last_read_seq").notNull().default(0),
},
(t) => [index("idx_read_state_user").on(t.userId)]
diff --git a/src/shared/src/db/queries/community/inbox.ts b/src/shared/src/db/queries/community/inbox.ts
index 25ca37a09..2096b2990 100644
--- a/src/shared/src/db/queries/community/inbox.ts
+++ b/src/shared/src/db/queries/community/inbox.ts
@@ -1,8 +1,9 @@
-import { and, eq, isNotNull, isNull, inArray, ne } from "drizzle-orm";
+import { and, eq, isNotNull, isNull, inArray, ne, sql } from "drizzle-orm";
import { chunk, D1_MAX_IN_PARAMS } from "../_chunk";
import {
communityChannel,
communityChannelMember,
+ communityMessage,
communityReadState,
communityServer,
communityServerMember,
@@ -21,7 +22,6 @@ export interface UnreadChannelRow {
// through to the inbox so it can render the same entity icon as the sidebar.
type: string | null;
lastMessageAt: string;
- lastReadAt: string | null;
// null for a top-level channel; set for a thread / forum-post child. The
// inbox route uses this to nest child unreads under their parent channel.
parentChannelId: string | null;
@@ -32,26 +32,32 @@ export interface UnreadChannelRow {
* by "unread since I last looked."
*
* - Archived / no lastMessageAt → not unread.
- * - Has read-state row → `lastMessageAt > lastReadAt` (normal path; strict
- * `>` mirrors the "author's own send is not unread" invariant from
- * `createMessage`, which writes lastMessageAt === lastReadAt in the same
- * batch).
- * - No read-state row → `lastMessageAt > joinedAt`. Users who joined a
- * server AFTER historical messages were posted must not have those old
- * messages flagged as unread. Without this, every non-empty channel
- * lights up on first join.
+ * - Has read-state row → `hasUnreadBeyondSeq`: is there a message with
+ * `seq > lastReadSeq`? (ref/id read-model seq unification — this is the SAME
+ * seq ruler the agent inbox uses; `EXISTS(message.seq > COALESCE(lastReadSeq,0))`
+ * computed in SQL, passed in here). Strict `>` mirrors the "author's own send
+ * is not unread" invariant — `createMessage` advances the author's own
+ * `lastReadSeq` to that message's seq in the same batch. Replaces the old
+ * `lastMessageAt > lastReadAt` timestamp compare, which drifted from the
+ * agent side's seq compare.
+ * - No read-state row → `lastMessageAt > joinedAt`. Users who joined a server
+ * AFTER historical messages were posted must not have those old messages
+ * flagged as unread. Kept on the TIMESTAMP: with no read-state row there's no
+ * `lastReadSeq` to compare and no bot/human cursor to drift between — the
+ * join baseline is orthogonal to the seq unification, so it stays as-is.
*
* Pure — exported for direct unit testing.
*/
export function isChannelUnread(row: {
archived: boolean;
lastMessageAt: string | null;
- lastReadAt: string | null;
+ hasReadState: boolean;
+ hasUnreadBeyondSeq: boolean;
joinedAt: string;
}): boolean {
if (row.archived) return false;
if (!row.lastMessageAt) return false;
- if (row.lastReadAt) return row.lastMessageAt > row.lastReadAt;
+ if (row.hasReadState) return row.hasUnreadBeyondSeq;
return row.lastMessageAt > row.joinedAt;
}
@@ -89,7 +95,17 @@ export async function listUnreadChannels(
type: communityChannel.type,
parentChannelId: communityChannel.parentChannelId,
lastMessageAt: communityChannel.lastMessageAt,
- lastReadAt: communityReadState.lastReadAt,
+ // `hasReadState` distinguishes "read-state row exists" (→ seq
+ // predicate) from "no row" (→ joinedAt timestamp branch). The
+ // read-state row's own id is a cheap non-null marker under the
+ // LEFT JOIN.
+ hasReadState: sql<number>`(${communityReadState.id} IS NOT NULL)`,
+ // The seq predicate (ref/id seq unification): is there any message
+ // in this channel with seq beyond the viewer's read cursor? SAME
+ // ruler as the agent inbox. COALESCE handles the no-row LEFT JOIN
+ // (lastReadSeq NULL → 0), though the joinedAt branch takes over
+ // there anyway per `isChannelUnread`.
+ hasUnreadBeyondSeq: sql<number>`EXISTS (SELECT 1 FROM ${communityMessage} m WHERE m.channel_id = ${communityChannel.id} AND m.seq > COALESCE(${communityReadState.lastReadSeq}, 0))`,
archived: communityChannel.archived,
// Sidebar / inbox unread badges must ignore messages posted before
// the viewer joined — otherwise every non-empty channel lights up
@@ -126,7 +142,9 @@ export async function listUnreadChannels(
isChannelUnread({
archived: r.archived,
lastMessageAt: r.lastMessageAt,
- lastReadAt: r.lastReadAt,
+ // SQL booleans arrive as 0/1 integers over D1.
+ hasReadState: Boolean(r.hasReadState),
+ hasUnreadBeyondSeq: Boolean(r.hasUnreadBeyondSeq),
joinedAt: r.joinedAt,
})
);
@@ -160,7 +178,6 @@ export async function listUnreadChannels(
type: r.type,
parentChannelId: r.parentChannelId,
lastMessageAt: r.lastMessageAt!,
- lastReadAt: r.lastReadAt,
}));
}
@@ -174,27 +191,28 @@ export interface UnreadDmRow {
otherUserName: string;
otherUserImage: string | null;
lastMessageAt: string;
- lastReadAt: string | null;
}
/**
- * Mirrors `isChannelUnread` for DMs.
+ * Mirrors `isChannelUnread` for DMs (ref/id read-model seq unification).
*
* - No `lastMessageAt` (empty conversation) → not unread.
- * - Has read-state row → strict `lastMessageAt > lastReadAt`. `createMessage`
- * writes both timestamps equal in the same batch for the author, so this
- * naturally excludes the author's own send (same invariant as channels).
+ * - Has read-state row → `hasUnreadBeyondSeq` (EXISTS message with
+ * `seq > lastReadSeq`, computed in SQL — same seq ruler as channels + agent).
+ * `createMessage` advances the author's own `lastReadSeq` in the same batch,
+ * so this excludes the author's own send (same invariant as channels).
* - No read-state row → unread as long as there IS a message. DMs have no
* "joinedAt" analog — the conversation only exists because one of the two
* participants opened it, and any message means the counterparty hasn't
- * looked yet.
+ * looked yet. (The `isNotNull(lastMessageAt)` WHERE guarantees a message.)
*/
export function isDmUnread(row: {
lastMessageAt: string | null;
- lastReadAt: string | null;
+ hasReadState: boolean;
+ hasUnreadBeyondSeq: boolean;
}): boolean {
if (!row.lastMessageAt) return false;
- if (row.lastReadAt) return row.lastMessageAt > row.lastReadAt;
+ if (row.hasReadState) return row.hasUnreadBeyondSeq;
return true;
}
@@ -224,7 +242,8 @@ export async function listUnreadDms(
.select({
channelId: communityChannel.id,
lastMessageAt: communityChannel.lastMessageAt,
- lastReadAt: communityReadState.lastReadAt,
+ hasReadState: sql<number>`(${communityReadState.id} IS NOT NULL)`,
+ hasUnreadBeyondSeq: sql<number>`EXISTS (SELECT 1 FROM ${communityMessage} m WHERE m.channel_id = ${communityChannel.id} AND m.seq > COALESCE(${communityReadState.lastReadSeq}, 0))`,
otherUserId: user.id,
otherUserName: user.name,
otherUserImage: user.image,
@@ -257,7 +276,11 @@ export async function listUnreadDms(
const seen = new Set<string>();
return rows
.filter((r) =>
- isDmUnread({ lastMessageAt: r.lastMessageAt, lastReadAt: r.lastReadAt })
+ isDmUnread({
+ lastMessageAt: r.lastMessageAt,
+ hasReadState: Boolean(r.hasReadState),
+ hasUnreadBeyondSeq: Boolean(r.hasUnreadBeyondSeq),
+ })
)
.filter((r) => {
if (seen.has(r.channelId)) return false;
@@ -270,6 +293,5 @@ export async function listUnreadDms(
otherUserName: r.otherUserName,
otherUserImage: r.otherUserImage,
lastMessageAt: r.lastMessageAt!,
- lastReadAt: r.lastReadAt,
}));
}
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index ee8fa235b..ef5f4f4c3 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -573,11 +573,14 @@ export async function getLatestMessageSeq(
export async function getLatestMessage(
db: Database,
target: { channelId: string }
-): Promise<{ id: string; createdAt: string } | null> {
+): Promise<{ id: string; createdAt: string; seq: number } | null> {
const rows = await db
.select({
id: communityMessage.id,
createdAt: communityMessage.createdAt,
+ // `seq` so the human read-state writers can store `lastReadSeq` alongside
+ // `lastReadAt`/`lastReadMessageId` (ref/id read-model seq unification).
+ seq: communityMessage.seq,
})
.from(communityMessage)
.where(eq(communityMessage.channelId, target.channelId))
@@ -601,7 +604,7 @@ export async function getLatestMessage(
export async function getLatestMessagesByChannelIds(
db: Database,
channelIds: string[]
-): Promise<Array<{ channelId: string; id: string; createdAt: string }>> {
+): Promise<Array<{ channelId: string; id: string; createdAt: string; seq: number }>> {
if (channelIds.length === 0) return [];
// D1 caps a statement at 100 bound params. Chunk the `inArray` subquery — each
@@ -624,6 +627,9 @@ export async function getLatestMessagesByChannelIds(
channelId: communityMessage.channelId,
id: communityMessage.id,
createdAt: communityMessage.createdAt,
+ // `seq` so `markAllServerChannelsRead` can store `lastReadSeq` per
+ // channel (ref/id read-model seq unification).
+ seq: communityMessage.seq,
})
.from(communityMessage)
.innerJoin(
@@ -643,7 +649,7 @@ export async function getLatestMessagesByChannelIds(
// exact `createdAt` (millisecond collisions on batched inserts). Pick the
// greater id — mirrors the `desc(createdAt), desc(id)` order used by
// `getLatestMessage` so single-vs-batched callers agree.
- const bestByChannel = new Map<string, { channelId: string; id: string; createdAt: string }>();
+ const bestByChannel = new Map<string, { channelId: string; id: string; createdAt: string; seq: number }>();
for (const r of rows) {
if (!r.channelId) continue;
const existing = bestByChannel.get(r.channelId);
@@ -652,6 +658,7 @@ export async function getLatestMessagesByChannelIds(
channelId: r.channelId,
id: r.id,
createdAt: r.createdAt,
+ seq: r.seq,
});
}
}
diff --git a/src/shared/src/db/queries/community/read-state.ts b/src/shared/src/db/queries/community/read-state.ts
index 4e76ef15f..0be72796a 100644
--- a/src/shared/src/db/queries/community/read-state.ts
+++ b/src/shared/src/db/queries/community/read-state.ts
@@ -57,16 +57,19 @@ function buildTargetFilter(data: { userId: string; channelId: string }) {
* `channelId` is the only scope; the upsert targets the plain unique
* `(user_id, channel_id)`.
*/
-// lastReadSeq intentionally not maintained here — humans only, bot-wake
-// filter never reads a human's row (see plans/community-agent-cli-bridge.md
-// design §4 for the full accounting of which of the four read-state writers
-// do/don't need to thread `lastReadSeq` through).
+// `lastReadSeq` IS maintained here now (ref/id read-model seq unification): the
+// unread predicate switched from `lastMessageAt > lastReadAt` (timestamp) to
+// `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.
export function markReadToMessageBuilder(
db: Database,
data: {
userId: string;
channelId: string;
- message: { id: string; createdAt: string };
+ message: { id: string; createdAt: string; seq: number };
}
) {
const { userId, channelId, message } = data;
@@ -90,12 +93,14 @@ export function markReadToMessageBuilder(
channelId,
lastReadAt: message.createdAt,
lastReadMessageId: message.id,
+ lastReadSeq: message.seq,
})
.onConflictDoUpdate({
target: [communityReadState.userId, communityReadState.channelId],
set: {
lastReadAt: message.createdAt,
lastReadMessageId: message.id,
+ lastReadSeq: message.seq,
},
setWhere: sql`${communityReadState.lastReadAt} < ${message.createdAt}`,
});
@@ -111,14 +116,14 @@ export function markReadToMessageBuilder(
* The routes don't consume the returned row today — see `PUT /dm/:id/read`
* and `PUT /threads/:id/read` which respond `{ ok: true }`.
*/
-// lastReadSeq intentionally not maintained here — see comment on
+// `lastReadSeq` maintained via the builder — see comment on
// `markReadToMessageBuilder` above.
export async function markReadToMessage(
db: Database,
data: {
userId: string;
channelId: string;
- message: { id: string; createdAt: string };
+ message: { id: string; createdAt: string; seq: number };
}
): Promise<void> {
await markReadToMessageBuilder(db, data);
@@ -194,14 +199,14 @@ export async function markAllServerChannelsRead(
// 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 }> = [];
- const toInsert: Array<{ channelId: string; msgId: string; createdAt: string }> = [];
+ 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 });
+ 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 });
+ toInsert.push({ channelId: l.channelId, msgId: l.id, createdAt: l.createdAt, seq: l.seq });
}
}
@@ -218,7 +223,7 @@ export async function markAllServerChannelsRead(
for (const u of toUpdate) {
await db
.update(communityReadState)
- .set({ lastReadAt: u.createdAt, lastReadMessageId: u.msgId })
+ .set({ lastReadAt: u.createdAt, lastReadMessageId: u.msgId, lastReadSeq: u.seq })
.where(
and(
eq(communityReadState.id, u.id),
@@ -229,8 +234,9 @@ export async function markAllServerChannelsRead(
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 default),
- // so cap at floor(100/6)=16 rows/statement for D1's 100-param limit.
+ // 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) => ({
@@ -238,6 +244,7 @@ export async function markAllServerChannelsRead(
channelId: i.channelId,
lastReadAt: i.createdAt,
lastReadMessageId: i.msgId,
+ lastReadSeq: i.seq,
}))
);
}
diff --git a/src/shared/test/queries/community-inbox.test.ts b/src/shared/test/queries/community-inbox.test.ts
index 3fe17c89b..dc8b0054c 100644
--- a/src/shared/test/queries/community-inbox.test.ts
+++ b/src/shared/test/queries/community-inbox.test.ts
@@ -5,6 +5,13 @@ import { isChannelUnread, isDmUnread } from "../../src/db/queries/community/inbo
// These tests pin the shape of the public API; SQL behavior is covered by
// integration runs against D1. The fact that this file imports cleanly
// also surfaces accidental query syntax regressions at typecheck time.
+//
+// ref/id read-model seq unification: the unread predicate now compares SEQ
+// (`EXISTS(message.seq > lastReadSeq)`, computed in SQL) instead of the old
+// `lastMessageAt > lastReadAt` timestamp. The pure predicates take the SQL
+// results — `hasReadState` (is there a read-state row) + `hasUnreadBeyondSeq`
+// (the EXISTS result) — and the no-read-state branch still uses `joinedAt`
+// (channels) / "any message" (DMs), which are orthogonal to the seq switch.
describe("community/inbox exports", () => {
it("exports listUnreadChannels", () => {
@@ -21,106 +28,75 @@ describe("community/inbox exports", () => {
});
});
-describe("isChannelUnread — two-branch predicate", () => {
+describe("isChannelUnread — two-branch predicate (seq)", () => {
const j = "2026-07-06T00:00:00.000Z"; // joinedAt
const before = "2026-07-05T00:00:00.000Z"; // before join
const after = "2026-07-07T00:00:00.000Z"; // after join
it("archived → false", () => {
expect(
- isChannelUnread({
- archived: true,
- lastMessageAt: after,
- lastReadAt: null,
- joinedAt: j,
- }),
+ isChannelUnread({ archived: true, lastMessageAt: after, hasReadState: false, hasUnreadBeyondSeq: true, joinedAt: j }),
).toBe(false);
});
it("no lastMessageAt → false", () => {
expect(
- isChannelUnread({
- archived: false,
- lastMessageAt: null,
- lastReadAt: null,
- joinedAt: j,
- }),
+ isChannelUnread({ archived: false, lastMessageAt: null, hasReadState: false, hasUnreadBeyondSeq: false, joinedAt: j }),
).toBe(false);
});
- it("has read-state, lastMessageAt > lastReadAt → true", () => {
+ it("has read-state, a message beyond lastReadSeq exists → true", () => {
expect(
- isChannelUnread({
- archived: false,
- lastMessageAt: after,
- lastReadAt: j,
- joinedAt: j,
- }),
+ isChannelUnread({ archived: false, lastMessageAt: after, hasReadState: true, hasUnreadBeyondSeq: true, joinedAt: j }),
).toBe(true);
});
- it("has read-state, lastMessageAt === lastReadAt → false (author's own send)", () => {
+ it("has read-state, nothing beyond lastReadSeq → false (caught up / author's own send)", () => {
+ // createMessage advances the author's own lastReadSeq to the message's seq
+ // in the same batch, so the author's own send yields no seq beyond cursor.
expect(
- isChannelUnread({
- archived: false,
- lastMessageAt: j,
- lastReadAt: j,
- joinedAt: j,
- }),
+ isChannelUnread({ archived: false, lastMessageAt: j, hasReadState: true, hasUnreadBeyondSeq: false, joinedAt: j }),
).toBe(false);
});
it("no read-state, lastMessageAt > joinedAt → true (unread since join)", () => {
expect(
- isChannelUnread({
- archived: false,
- lastMessageAt: after,
- lastReadAt: null,
- joinedAt: j,
- }),
+ isChannelUnread({ archived: false, lastMessageAt: after, hasReadState: false, hasUnreadBeyondSeq: false, joinedAt: j }),
).toBe(true);
});
it("no read-state, lastMessageAt < joinedAt → false (message pre-dates join)", () => {
expect(
- isChannelUnread({
- archived: false,
- lastMessageAt: before,
- lastReadAt: null,
- joinedAt: j,
- }),
+ isChannelUnread({ archived: false, lastMessageAt: before, hasReadState: false, hasUnreadBeyondSeq: false, joinedAt: j }),
).toBe(false);
});
it("no read-state, lastMessageAt === joinedAt → false (equal timestamps, matches > semantics)", () => {
expect(
- isChannelUnread({
- archived: false,
- lastMessageAt: j,
- lastReadAt: null,
- joinedAt: j,
- }),
+ isChannelUnread({ archived: false, lastMessageAt: j, hasReadState: false, hasUnreadBeyondSeq: false, joinedAt: j }),
+ ).toBe(false);
+ });
+
+ it("has read-state takes the seq branch even when lastMessageAt < joinedAt (branch precedence)", () => {
+ // With a read-state row, the joinedAt branch never runs — the seq EXISTS
+ // is authoritative. A pre-join lastMessageAt with hasUnreadBeyondSeq=false
+ // is not unread; the joinedAt comparison is irrelevant here.
+ expect(
+ isChannelUnread({ archived: false, lastMessageAt: before, hasReadState: true, hasUnreadBeyondSeq: false, joinedAt: j }),
).toBe(false);
});
});
/**
- * Behaviour tests for the JS post-filter in `listUnreadChannels`.
- *
- * We can't run a full D1 join in unit tests, so we mock the DB to return the
- * row shape the join produces. What we're really pinning here is the
- * `lastMessageAt > lastReadAt` predicate — the fix in #1 relies on
- * `createMessage` writing both timestamps equal in the same batch, so this
- * predicate is what naturally excludes the author's own send.
- *
- * These fixtures reflect the DB state that WOULD exist after `createMessage`
- * runs for the given (user, channel) pairs. They document the invariant end-
- * to-end without needing a real SQLite backend.
+ * Behaviour tests for the JS post-filter in `listUnreadChannels`. We can't run a
+ * full D1 join in unit tests, so we mock the DB to return the row shape the join
+ * produces — now carrying `hasReadState` / `hasUnreadBeyondSeq` (the SQL-computed
+ * 0/1 flags) rather than `lastReadAt`. These document the seq predicate end-to-end
+ * without a real SQLite backend.
*/
-describe("listUnreadChannels — author read-watermark behaviour", () => {
+describe("listUnreadChannels — seq read-watermark behaviour", () => {
function createUnreadRowMock(rows: any[]) {
- // The query flows: select → from → innerJoin → innerJoin → leftJoin → where
- // and .where(...) resolves to rows.
+ // select → from → innerJoin → innerJoin → leftJoin → where; .where resolves rows.
const chain: any = {};
chain.select = vi.fn(() => chain);
chain.from = vi.fn(() => chain);
@@ -132,53 +108,31 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
const j = "2026-07-06T00:00:00.000Z"; // joinedAt used by all fixtures
- it("after author sends in channel A, listUnreadChannels(author) excludes A (lastMessageAt === lastReadAt)", async () => {
- // Post-createMessage state: channel.lastMessageAt and readState.lastReadAt
- // are the same string — the timestamp alignment invariant from #1.
- const ts = "2026-07-06T00:00:00.000Z";
+ it("author is caught up in channel A (nothing beyond lastReadSeq) → excluded", async () => {
+ // Post-createMessage state: the author's lastReadSeq == the channel's latest
+ // seq, so EXISTS(seq > lastReadSeq) is false (hasUnreadBeyondSeq: 0).
const db = createUnreadRowMock([
{
- channelId: "ch_A",
- channelName: "channel A",
- serverId: "srv_1",
- serverName: "server 1",
- parentChannelId: null,
- lastMessageAt: ts,
- lastReadAt: ts, // author's watermark advanced to this exact message
- archived: false,
- joinedAt: j,
+ channelId: "ch_A", channelName: "channel A", serverId: "srv_1", serverName: "server 1",
+ parentChannelId: null, lastMessageAt: j, hasReadState: 1, hasUnreadBeyondSeq: 0, archived: false, joinedAt: j,
},
]);
const result = await inboxQueries.listUnreadChannels(db, "u_author", ["ch_A"]);
expect(result).toEqual([]);
});
- it("after author's send, then peer's send in channel A: listUnreadChannels(author) DOES include A (watermark bounded, not sticky)", async () => {
- // Author's send set watermark to t1; peer's send bumped channel.lastMessageAt
- // to t2 without touching the author's read-state. Result: t2 > t1, channel
- // resurfaces as unread — exactly the "watermark is bounded, not sticky"
- // behaviour the plan calls out.
- const t1 = "2026-07-06T00:00:00.000Z";
+ it("peer's send beyond the author's cursor → channel A resurfaces (watermark bounded, not sticky)", async () => {
const t2 = "2026-07-06T00:00:05.000Z";
const db = createUnreadRowMock([
{
- channelId: "ch_A",
- channelName: "channel A",
- serverId: "srv_1",
- serverName: "server 1",
- type: "forum",
- parentChannelId: null,
- lastMessageAt: t2,
- lastReadAt: t1,
- archived: false,
- joinedAt: j,
+ channelId: "ch_A", channelName: "channel A", serverId: "srv_1", serverName: "server 1",
+ type: "forum", parentChannelId: null, lastMessageAt: t2, hasReadState: 1, hasUnreadBeyondSeq: 1, archived: false, joinedAt: j,
},
]);
const result = await inboxQueries.listUnreadChannels(db, "u_author", ["ch_A"]);
expect(result).toHaveLength(1);
expect(result[0]!.channelId).toBe("ch_A");
expect(result[0]!.lastMessageAt).toBe(t2);
- expect(result[0]!.lastReadAt).toBe(t1);
// `type` is carried through so the inbox can render the entity icon.
expect(result[0]!.type).toBe("forum");
});
@@ -186,15 +140,8 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
it("archived channels are filtered out even when unread", async () => {
const db = createUnreadRowMock([
{
- channelId: "ch_archived",
- channelName: "old",
- serverId: "srv_1",
- serverName: "server 1",
- parentChannelId: null,
- lastMessageAt: "2026-07-06T00:00:00.000Z",
- lastReadAt: null,
- archived: true,
- joinedAt: j,
+ channelId: "ch_archived", channelName: "old", serverId: "srv_1", serverName: "server 1",
+ parentChannelId: null, lastMessageAt: "2026-07-06T00:00:00.000Z", hasReadState: 0, hasUnreadBeyondSeq: 0, archived: true, joinedAt: j,
},
]);
const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_archived"]);
@@ -202,19 +149,11 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
});
it("channel the user has never opened surfaces as unread when lastMessageAt > joinedAt", async () => {
- // No read-state row for this (user, channel). Message posted AFTER the
- // user joined the server → still unread from their perspective.
+ // No read-state row (hasReadState: 0) → joinedAt branch. Message after join.
const db = createUnreadRowMock([
{
- channelId: "ch_new",
- channelName: "brand new",
- serverId: "srv_1",
- serverName: "server 1",
- parentChannelId: null,
- lastMessageAt: "2026-07-06T00:01:00.000Z",
- lastReadAt: null,
- archived: false,
- joinedAt: j,
+ channelId: "ch_new", channelName: "brand new", serverId: "srv_1", serverName: "server 1",
+ parentChannelId: null, lastMessageAt: "2026-07-06T00:01:00.000Z", hasReadState: 0, hasUnreadBeyondSeq: 0, archived: false, joinedAt: j,
},
]);
const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_new"]);
@@ -223,20 +162,11 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
});
it("channel with messages predating the user's join does NOT surface as unread", async () => {
- // The bug fix: a user who joined a server with pre-existing history
- // shouldn't see every old channel as unread. lastReadAt is null (never
- // opened) but lastMessageAt < joinedAt.
+ // No read-state row, lastMessageAt < joinedAt → joinedAt branch excludes it.
const db = createUnreadRowMock([
{
- channelId: "ch_old",
- channelName: "old history",
- serverId: "srv_1",
- serverName: "server 1",
- parentChannelId: null,
- lastMessageAt: "2026-07-05T00:00:00.000Z", // predates joinedAt
- lastReadAt: null,
- archived: false,
- joinedAt: j,
+ channelId: "ch_old", channelName: "old history", serverId: "srv_1", serverName: "server 1",
+ parentChannelId: null, lastMessageAt: "2026-07-05T00:00:00.000Z", hasReadState: 0, hasUnreadBeyondSeq: 0, archived: false, joinedAt: j,
},
]);
const result = await inboxQueries.listUnreadChannels(db, "u_1", ["ch_old"]);
@@ -245,8 +175,6 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
// Thread unreads are scoped to PARTICIPATION. The function issues a SECOND
// query (listParticipatingThreadIds) when the unread set contains threads.
- // This mock returns the unread rows on the first `.where()` and the
- // participating-thread ids on the second.
function createTwoQueryMock(unreadRows: any[], participatingThreadIds: string[]) {
let call = 0;
const chain: any = {};
@@ -264,16 +192,9 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
}
const unreadThreadRow = (channelId: string) => ({
- channelId,
- channelName: "a thread",
- serverId: "srv_1",
- serverName: "server 1",
- type: "thread",
- parentChannelId: "ch_parent",
- lastMessageAt: "2026-07-06T00:00:05.000Z",
- lastReadAt: "2026-07-06T00:00:00.000Z",
- archived: false,
- joinedAt: j,
+ channelId, channelName: "a thread", serverId: "srv_1", serverName: "server 1",
+ type: "thread", parentChannelId: "ch_parent", lastMessageAt: "2026-07-06T00:00:05.000Z",
+ hasReadState: 1, hasUnreadBeyondSeq: 1, archived: false, joinedAt: j,
});
it("thread the viewer participates in surfaces as unread", async () => {
@@ -289,16 +210,9 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
});
const unreadPostRow = (channelId: string) => ({
- channelId,
- channelName: "a post",
- serverId: "srv_1",
- serverName: "server 1",
- type: "forum_post",
- parentChannelId: "forum_1",
- lastMessageAt: "2026-07-06T00:00:05.000Z",
- lastReadAt: "2026-07-06T00:00:00.000Z",
- archived: false,
- joinedAt: j,
+ channelId, channelName: "a post", serverId: "srv_1", serverName: "server 1",
+ type: "forum_post", parentChannelId: "forum_1", lastMessageAt: "2026-07-06T00:00:05.000Z",
+ hasReadState: 1, hasUnreadBeyondSeq: 1, archived: false, joinedAt: j,
});
it("forum post the viewer participates in surfaces as unread", async () => {
@@ -308,53 +222,39 @@ describe("listUnreadChannels — author read-watermark behaviour", () => {
});
it("public forum post the viewer has NOT joined is filtered out (visible but un-notified)", async () => {
- // A public post is visible to the whole server, so it lands in the unread
- // set, but it must only surface for its participants — an un-joined viewer
- // gets no unread badge.
const db = createTwoQueryMock([unreadPostRow("p_out")], []);
const result = await inboxQueries.listUnreadChannels(db, "u_1", ["p_out"]);
expect(result).toEqual([]);
});
});
-describe("isDmUnread — predicate", () => {
+describe("isDmUnread — predicate (seq)", () => {
it("no lastMessageAt → false (empty conversation)", () => {
- expect(isDmUnread({ lastMessageAt: null, lastReadAt: null })).toBe(false);
+ expect(isDmUnread({ lastMessageAt: null, hasReadState: false, hasUnreadBeyondSeq: false })).toBe(false);
});
it("no read-state, has message → true (counterparty never opened)", () => {
expect(
- isDmUnread({ lastMessageAt: "2026-07-06T00:00:00.000Z", lastReadAt: null })
+ isDmUnread({ lastMessageAt: "2026-07-06T00:00:00.000Z", hasReadState: false, hasUnreadBeyondSeq: false })
).toBe(true);
});
- it("lastMessageAt === lastReadAt → false (author's own send)", () => {
+ it("has read-state, nothing beyond lastReadSeq → false (caught up / own send)", () => {
const t = "2026-07-06T00:00:00.000Z";
- expect(isDmUnread({ lastMessageAt: t, lastReadAt: t })).toBe(false);
+ expect(isDmUnread({ lastMessageAt: t, hasReadState: true, hasUnreadBeyondSeq: false })).toBe(false);
});
- it("lastMessageAt > lastReadAt → true", () => {
+ it("has read-state, a message beyond lastReadSeq → true", () => {
expect(
- isDmUnread({
- lastMessageAt: "2026-07-06T00:00:05.000Z",
- lastReadAt: "2026-07-06T00:00:00.000Z",
- })
+ isDmUnread({ lastMessageAt: "2026-07-06T00:00:05.000Z", hasReadState: true, hasUnreadBeyondSeq: true })
).toBe(true);
});
-
- it("lastMessageAt < lastReadAt → false", () => {
- expect(
- isDmUnread({
- lastMessageAt: "2026-07-06T00:00:00.000Z",
- lastReadAt: "2026-07-06T00:00:05.000Z",
- })
- ).toBe(false);
- });
});
-describe("listUnreadDms — read-watermark behaviour", () => {
+describe("listUnreadDms — seq read-watermark behaviour", () => {
function createUnreadDmRowMock(rows: any[]) {
- // select → from → innerJoin → leftJoin → where
+ // selfRows select → then the main select → from → innerJoin → leftJoin → where.
+ // Both `.where()` resolutions return `rows`; selfRows only reads `channelId`.
const chain: any = {};
chain.select = vi.fn(() => chain);
chain.from = vi.fn(() => chain);
@@ -364,17 +264,11 @@ describe("listUnreadDms — read-watermark behaviour", () => {
return chain;
}
- it("returns DMs where lastMessageAt > lastReadAt", async () => {
- // DMs are type=dm channels now — rows key on `channelId` (the DM's channel),
- // which also feeds the leading selfRows channel-id resolution.
+ it("returns DMs with a message beyond the viewer's lastReadSeq", async () => {
const db = createUnreadDmRowMock([
{
- channelId: "dm_ch_1",
- lastMessageAt: "2026-07-06T00:00:05.000Z",
- lastReadAt: "2026-07-06T00:00:00.000Z",
- otherUserId: "u_alice",
- otherUserName: "Alice",
- otherUserImage: null,
+ channelId: "dm_ch_1", lastMessageAt: "2026-07-06T00:00:05.000Z",
+ hasReadState: 1, hasUnreadBeyondSeq: 1, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: null,
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
@@ -383,31 +277,23 @@ describe("listUnreadDms — read-watermark behaviour", () => {
expect(result[0]!.otherUserId).toBe("u_alice");
});
- it("filters out DMs where author's watermark equals lastMessageAt", async () => {
+ it("filters out DMs where the viewer is caught up (nothing beyond lastReadSeq)", async () => {
const ts = "2026-07-06T00:00:00.000Z";
const db = createUnreadDmRowMock([
{
- channelId: "dm_ch_1",
- lastMessageAt: ts,
- lastReadAt: ts, // viewer sent last, watermark aligned
- otherUserId: "u_alice",
- otherUserName: "Alice",
- otherUserImage: null,
+ channelId: "dm_ch_1", lastMessageAt: ts,
+ hasReadState: 1, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: null,
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
expect(result).toEqual([]);
});
- it("returns DM the viewer has never opened (lastReadAt null, lastMessageAt set)", async () => {
+ it("returns DM the viewer has never opened (no read-state row, message present)", async () => {
const db = createUnreadDmRowMock([
{
- channelId: "dm_ch_1",
- lastMessageAt: "2026-07-06T00:00:00.000Z",
- lastReadAt: null,
- otherUserId: "u_alice",
- otherUserName: "Alice",
- otherUserImage: "https://cdn/a.png",
+ channelId: "dm_ch_1", lastMessageAt: "2026-07-06T00:00:00.000Z",
+ hasReadState: 0, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: "https://cdn/a.png",
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
@@ -416,17 +302,10 @@ describe("listUnreadDms — read-watermark behaviour", () => {
});
it("skips empty conversations (lastMessageAt null)", async () => {
- // The WHERE clause filters this on the DB side (`isNotNull(lastMessageAt)`),
- // but the JS predicate is defensive — pinning both layers together lets us
- // catch a regression where either drops the guard.
const db = createUnreadDmRowMock([
{
- channelId: "dm_ch_1",
- lastMessageAt: null,
- lastReadAt: null,
- otherUserId: "u_alice",
- otherUserName: "Alice",
- otherUserImage: null,
+ channelId: "dm_ch_1", lastMessageAt: null,
+ hasReadState: 0, hasUnreadBeyondSeq: 0, otherUserId: "u_alice", otherUserName: "Alice", otherUserImage: null,
},
]);
const result = await inboxQueries.listUnreadDms(db, "u_viewer");
diff --git a/src/shared/test/queries/community-read-state.test.ts b/src/shared/test/queries/community-read-state.test.ts
index eabb93ac0..ee0842fac 100644
--- a/src/shared/test/queries/community-read-state.test.ts
+++ b/src/shared/test/queries/community-read-state.test.ts
@@ -33,7 +33,7 @@ describe("markReadToMessageBuilder — channel branch", () => {
const result = readStateQueries.markReadToMessageBuilder(db, {
userId: "u_1",
channelId: "c_1",
- message: { id: "m_42", createdAt: "2026-07-03T00:00:00Z" },
+ message: { id: "m_42", createdAt: "2026-07-03T00:00:00Z", seq: 42 },
});
expect(result).toBeDefined();
expect(result).not.toBeInstanceOf(Promise);
@@ -47,7 +47,7 @@ describe("markReadToMessageBuilder — channel branch", () => {
readStateQueries.markReadToMessageBuilder(db, {
userId: "u_1",
channelId: "c_1",
- message: { id: "m_42", createdAt: "2026-07-03T00:00:00Z" },
+ message: { id: "m_42", createdAt: "2026-07-03T00:00:00Z", seq: 42 },
});
const valuesArg = db.values.mock.calls[0][0];
expect(valuesArg).toMatchObject({
@@ -55,6 +55,9 @@ describe("markReadToMessageBuilder — channel branch", () => {
channelId: "c_1",
lastReadAt: "2026-07-03T00:00:00Z",
lastReadMessageId: "m_42",
+ // ref/id seq unification: humans now store lastReadSeq too, or the seq
+ // unread predicate never sees a human's read.
+ lastReadSeq: 42,
});
// The invariant: values and set carry the same aligned tuple.
expect(valuesArg.lastReadAt).toBe(valuesArg.lastReadMessageId ? "2026-07-03T00:00:00Z" : undefined);
@@ -62,6 +65,7 @@ describe("markReadToMessageBuilder — channel branch", () => {
expect(conflictArg.set).toMatchObject({
lastReadAt: "2026-07-03T00:00:00Z",
lastReadMessageId: "m_42",
+ lastReadSeq: 42,
});
});
@@ -70,7 +74,7 @@ describe("markReadToMessageBuilder — channel branch", () => {
readStateQueries.markReadToMessageBuilder(db, {
userId: "u_1",
channelId: "c_1",
- message: { id: "m_1", createdAt: "2026-01-01T00:00:00Z" },
+ message: { id: "m_1", createdAt: "2026-01-01T00:00:00Z", seq: 1 },
});
const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];
expect(conflictArg.target).toEqual([
@@ -87,7 +91,7 @@ describe("markReadToMessageBuilder — channel branch", () => {
readStateQueries.markReadToMessageBuilder(db, {
userId: "u_1",
channelId: "c_1",
- message: { id: "m_42", createdAt: "2026-07-03T00:00:00Z" },
+ message: { id: "m_42", createdAt: "2026-07-03T00:00:00Z", seq: 42 },
});
const conflictArg = db.onConflictDoUpdate.mock.calls[0][0];
// The setWhere is a Drizzle SQL fragment; we can't easily assert its
@@ -111,7 +115,7 @@ describe("markReadToMessageBuilder — DM is a channel", () => {
readStateQueries.markReadToMessageBuilder(db, {
userId: "u_1",
channelId: "dm_ch_1",
- message: { id: "m_9", createdAt: "2026-07-04T00:00:00Z" },
+ message: { id: "m_9", createdAt: "2026-07-04T00:00:00Z", seq: 9 },
});
const valuesArg = db.values.mock.calls[0][0];
expect(valuesArg).toMatchObject({
@@ -243,8 +247,8 @@ describe("markAllServerChannelsRead", () => {
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([
- { channelId: "c_a", id: "m_a_latest", createdAt: "2026-07-05T10:00:00Z" },
- { channelId: "c_b", id: "m_b_latest", createdAt: "2026-07-05T11:00:00Z" },
+ { channelId: "c_a", id: "m_a_latest", createdAt: "2026-07-05T10:00:00Z", seq: 10 },
+ { 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"]);
@@ -261,12 +265,14 @@ describe("markAllServerChannelsRead", () => {
channelId: "c_a",
lastReadAt: "2026-07-05T10:00:00Z",
lastReadMessageId: "m_a_latest",
+ lastReadSeq: 10,
});
expect(byChannel["c_b"]).toMatchObject({
userId: "u_1",
channelId: "c_b",
lastReadAt: "2026-07-05T11:00:00Z",
lastReadMessageId: "m_b_latest",
+ lastReadSeq: 11,
});
spy.mockRestore();
});
@@ -279,8 +285,8 @@ describe("markAllServerChannelsRead", () => {
});
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" },
- { channelId: "c_b", id: "m_b_new", createdAt: "2026-07-05T11:00:00Z" },
+ { 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"]);
@@ -303,6 +309,8 @@ describe("markAllServerChannelsRead", () => {
expect(bTuple).toBeDefined();
expect(aTuple!.lastReadAt).toBe("2026-07-05T10:00:00Z");
expect(bTuple!.lastReadAt).toBe("2026-07-05T11:00:00Z");
+ expect(aTuple!.lastReadSeq).toBe(20);
+ expect(bTuple!.lastReadSeq).toBe(21);
spy.mockRestore();
});
@@ -314,7 +322,7 @@ describe("markAllServerChannelsRead", () => {
});
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" },
+ { channelId: "c_a", id: "m_a_new", createdAt: "2026-07-05T10:00:00Z", seq: 20 },
]);
await readStateQueries.markAllServerChannelsRead(db, "u_1", ["c_a"]);
diff --git a/src/web/migrations/0076_read_state_seq_backfill.sql b/src/web/migrations/0076_read_state_seq_backfill.sql
new file mode 100644
index 000000000..2e4b77479
--- /dev/null
+++ b/src/web/migrations/0076_read_state_seq_backfill.sql
@@ -0,0 +1,51 @@
+-- Read-model seq unification (ref/id §3.4b read-state seq). The inbox unread
+-- predicate switched from the createdAt timestamp compare
+-- (`channel.lastMessageAt > read_state.last_read_at`) to a seq compare
+-- (`EXISTS(message.seq > read_state.last_read_seq)`) — the SAME ruler the agent
+-- inbox already uses — collapsing the bot(seq)/human(createdAt) two-cursor drift
+-- onto one. `last_read_seq` already exists (default 0, migration 0053) and was
+-- maintained only by createMessage's author watermark + agent ack; the human
+-- read routes (mark-read / mark-all) did NOT write it. Those routes now DO, but
+-- every EXISTING read-state row written by a human path still carries
+-- `last_read_seq = 0` while its `last_read_message_id` points at the real
+-- message the user read up to. Under the new predicate a 0 cursor = whole
+-- channel unread = mass "zombie" unread. This backfill fixes those rows.
+--
+-- EXACT, not reset (product red line — migrate, don't reset; already-read stays
+-- read): every row's invariant is `last_read_at === getMessage(last_read_message_id).createdAt`
+-- and `last_read_message_id` is populated, so the correct seq is a precise join
+-- on the message id — no timestamp fuzzing, no "everyone re-reads once".
+--
+-- Rows the seq-aware writers touched (author watermark / ack) already have a
+-- correct `last_read_seq`; the monotone spirit is preserved because we only ever
+-- map to the seq of the message the row already points at (never regress).
+--
+-- IDEMPOTENT: derives `last_read_seq` from the authoritative `last_read_message_id`
+-- (which all read writers set unconditionally), so re-running yields the same
+-- value. This is why the DEPLOY runs it TWICE — once here, and once AGAIN after
+-- the daemon restart — to zero the deploy-window phantom: any human read that
+-- lands after the migration but before the new code is live still advances
+-- `last_read_message_id` (old code writes it) but not `last_read_seq`; the
+-- post-restart re-run maps those freshly-advanced message ids to their seq,
+-- eliminating the transient window phantom rather than leaving it to self-heal.
+--
+-- DEAD-TARGET GUARD (Aigneis/Melly gate-catch): a human historical row can carry
+-- `last_read_seq = 0` (never written by the pre-gap-close human paths) AND a
+-- `last_read_message_id` pointing at a HARD-DELETED message. hardDelete only
+-- reverts the AUTHOR's own read-state row (`user_id = msg.author_id`), so a
+-- NON-author reader keeps a dangling pointer. If this backfill only mapped
+-- live-target rows and left the dead-target ones at 0, the new predicate
+-- `EXISTS(seq > COALESCE(last_read_seq,0))` = `seq > 0` = WHOLE CHANNEL UNREAD =
+-- zombie — the exact opposite of "already-read stays read". So the dead/missing
+-- target case COALESCEs to the channel's latest seq (`community_message_seq.next_seq`
+-- = the most recently issued seq, NOT next_seq-1) — conservatively "all read",
+-- satisfying the invariant "result seq >= true read position, never <". A NULL
+-- last_read_message_id is excluded by the WHERE (no row exists to map / it takes
+-- the no-read-state path); this guard is for a NON-null id whose message is gone.
+UPDATE community_read_state
+SET last_read_seq = COALESCE(
+ (SELECT m.seq FROM community_message m WHERE m.id = community_read_state.last_read_message_id),
+ (SELECT s.next_seq FROM community_message_seq s WHERE s.channel_id = community_read_state.channel_id),
+ last_read_seq
+)
+WHERE last_read_message_id IS NOT NULL;
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 638df5e39..f0d7ad3cd 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
@@ -60,7 +60,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
// Resolve the target message. Both branches align (lastReadAt, lastReadMessageId)
// to a real message — that's the read-state invariant.
- let target: { id: string; createdAt: string } | null
+ let target: { id: string; createdAt: string; seq: number } | null
if (lastReadMessageId) {
const msg = await queries.communityMessage.getMessage(db, lastReadMessageId)
if (!msg) return writeError("message not found", 404)
@@ -69,7 +69,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
if (msg.channelId !== channelId) {
return writeError("message not in channel", 400)
}
- target = { id: msg.id, createdAt: msg.createdAt }
+ target = { id: msg.id, createdAt: msg.createdAt, seq: msg.seq }
} else {
target = await queries.communityMessage.getLatestMessage(db, { channelId })
// Empty channel: no row can be written under the invariant. Nothing to
diff --git a/src/web/src/app/api/community/dm/[id]/read/route.ts b/src/web/src/app/api/community/dm/[id]/read/route.ts
index 01758e14b..22824670d 100644
--- a/src/web/src/app/api/community/dm/[id]/read/route.ts
+++ b/src/web/src/app/api/community/dm/[id]/read/route.ts
@@ -29,13 +29,13 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
// Body is optional
}
- let target: { id: string; createdAt: string } | null
+ let target: { id: string; createdAt: string; seq: number } | null
if (body.lastReadMessageId) {
const msg = await queries.communityMessage.getMessage(db, body.lastReadMessageId)
if (!msg || msg.channelId !== dmId) {
return writeError("lastReadMessageId does not belong to this dm", 400)
}
- target = { id: msg.id, createdAt: msg.createdAt }
+ target = { id: msg.id, createdAt: msg.createdAt, seq: msg.seq }
} else {
target = await queries.communityMessage.getLatestMessage(db, { channelId: dmId })
if (!target) return writeJSON({ ok: true })
diff --git a/src/web/src/app/api/community/threads/[id]/read/route.ts b/src/web/src/app/api/community/threads/[id]/read/route.ts
index 94e013a9e..d25e0b500 100644
--- a/src/web/src/app/api/community/threads/[id]/read/route.ts
+++ b/src/web/src/app/api/community/threads/[id]/read/route.ts
@@ -39,14 +39,14 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {
// Body is optional
}
- let target: { id: string; createdAt: string } | null
+ let target: { id: string; createdAt: string; seq: number } | null
if (body.lastReadMessageId) {
const msg = await queries.communityMessage.getMessage(db, body.lastReadMessageId)
if (!msg) return writeError("message not found", 404)
if (msg.channelId !== channelId) {
return writeError("message not in channel", 400)
}
- target = { id: msg.id, createdAt: msg.createdAt }
+ target = { id: msg.id, createdAt: msg.createdAt, seq: msg.seq }
} else {
target = await queries.communityMessage.getLatestMessage(db, { channelId })
if (!target) return writeJSON({ ok: true })