Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(messages): the backfill watermark has to mean complete, not biggest (#279)
Xialie Zhuang025b425ede05
diff --git a/src/stores/messages.ts b/src/stores/messages.tsindex ae70777..33d2731 100644--- a/src/stores/messages.ts+++ b/src/stores/messages.ts@@ -328,13 +328,41 @@ function mergeFetchedMessages(current: Message[] | undefined, incoming: Message[return sortMessagesStable(merged)}-async function fetchMessagesSinceCache(id: string, current: Message[] = []): Promise<ApiMessage[]> {- let latest: number | null = null- for (const message of current) {- const seq = sequenceOf(message)+/** The newest sequence below which the cache is known COMPLETE — not simply+ * the biggest number it holds.+ *+ * Those differ after an outage. On reconnect the store invalidates `loaded`+ * for every conversation except the open one, so a cached-but-unopened+ * conversation backfills when the user next opens it. `applyEvent` appends+ * live `message.new` rows to byConvo for ANY cached conversation though, and+ * those land first. Taking the max then reads that lone new row as proof the+ * history is caught up, the bridging loop below never runs, and the outage+ * stays as a hole that nothing else fills for the rest of the session.+ *+ * So walk the cache oldest-first and stop at the first discontinuity: that+ * run is what we can actually vouch for, and a message that arrived after the+ * gap is the island it should be. A rolled-back sequence leaves a real hole+ * and truncates the answer early — which only costs an extra page, and the+ * merge drops what we already hold. Erring toward re-fetching is the safe+ * direction; erring toward "caught up" loses messages. */+function completeThrough(current: Message[]): number | null {+ const sequences = current+ .map(sequenceOf)// Optimistic messages use MAX_SAFE_INTEGER until their WS echo arrives.- if (seq !== null && seq !== Number.MAX_SAFE_INTEGER && (latest === null || seq > latest)) latest = seq+ .filter((seq): seq is number => seq !== null && seq !== Number.MAX_SAFE_INTEGER)+ .sort((a, b) => a - b)+ if (sequences.length === 0) return null+ let through = sequences[0]+ for (const seq of sequences) {+ if (seq === through || seq === through + 1) through = seq+ else break}+ return through+}++async function fetchMessagesSinceCache(id: string, current: Message[] = []): Promise<ApiMessage[]> {+ const latest = completeThrough(current)+ const held = new Set(current.map((message) => message.id))let page = await api.getMessages(id, { limit: MESSAGES_PAGE_SIZE })const messages = [...page]@@ -342,7 +370,9 @@ async function fetchMessagesSinceCache(id: string, current: Message[] = []): Prowhile (latest !== null && page.length === MESSAGES_PAGE_SIZE && page[0].sequence > latest) {page = await api.getMessages(id, { before: page[0].sequence, limit: MESSAGES_PAGE_SIZE })// Only fill the gap; leave older history and its scroll anchor to loadOlder.- messages.unshift(...page.filter((message) => message.sequence > latest))+ // By id, not by sequence: a hole in the run above means some of what comes+ // back is already here, and re-adding it would duplicate rows.+ messages.unshift(...page.filter((message) => !held.has(message.id) && message.sequence > latest))}return messages}diff --git a/tests/messages-history.test.ts b/tests/messages-history.test.tsindex 6101b08..cf060a6 100644--- a/tests/messages-history.test.ts+++ b/tests/messages-history.test.ts@@ -95,6 +95,24 @@ describe('message history after reconnect', () => {assert.equal(store.getState().byConvo.chat.at(-1), optimistic)})+ it('backfills even when a live message arrived after the reconnect', async () => {+ // On reconnect the store invalidates `loaded` for every conversation+ // except the open one, so this one backfills when the user next opens+ // it. But `applyEvent` appends live `message.new` rows to byConvo for+ // ANY cached conversation, and that lands before the user gets there.+ // One such row raises max(sequence) past the outage, the loop's+ // `page[0].sequence > latest` goes false, and the whole backfill is+ // skipped — a silent permanent hole.+ const live = messages(300, 300)+ const { store, sequences } = setup(300, [...messages(1, 80), ...live])+ await store.getState()[method]('chat')++ assert.deepEqual(+ sequences(), messages(1, 300).map((m) => m.sequence),+ 'the outage was never bridged because one live message raised the watermark past it',+ )+ })+it('keeps the cache intact on a failed backfill and fills the gap on retry', async () => {const { store, api, sequences } = setup(200)const originalCache = store.getState().byConvo.chat@@ -114,6 +132,20 @@ describe('message history after reconnect', () => {})}+ it('bridges across a hole in the cache without duplicating what is held', async () => {+ // A rolled-back INSERT leaves a real hole in `sequence`. The completeness+ // watermark stops at it, so the bridge re-fetches rows we already hold —+ // which is the safe direction, as long as the merge does not duplicate.+ const holed = [...messages(1, 40), ...messages(42, 80)]+ const { store, sequences } = setup(200, holed)+ await store.getState().loadConversation('chat')++ const got = sequences()+ assert.deepEqual(got, [...got].sort((a, b) => a - b), 'the merge left the list out of order')+ assert.equal(new Set(got).size, got.length, 'the bridge duplicated messages it already held')+ assert.ok(got.includes(200) && got.includes(81), 'the gap after the hole was not bridged')+ })+it('preserves messages received while the backfill request is in flight', async () => {const { store, api, sequences } = setup(200)const getMessages = api.getMessages