Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(channels): channel catchup frontend (#6325)
Will Hutchinson98cb3e3ba430
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.tsindex 0b88c7e422..68b07116c9 100644--- a/apps/web/src/lib/analytics/app-events.ts+++ b/apps/web/src/lib/analytics/app-events.ts@@ -183,6 +183,19 @@ export type AppEvents = {email_message_sent: Record<string, unknown>;channel_message_sent: Record<string, unknown>;+ channel_messages_load: {+ channelId: string;+ path: 'catch_up' | 'full';+ reason:+ | 'watermark'+ | 'list_ahead'+ | 'no_cache'+ | 'cache_not_at_latest'+ | 'load_around'+ | 'delta_overflow'+ | 'catch_up_error';+ after?: string;+ };channel_reaction: {emoji: string;action: 'add' | 'remove';diff --git a/apps/web/src/lib/queries/channel/channel-messages.ts b/apps/web/src/lib/queries/channel/channel-messages.tsindex 523100301e..fcc0b51033 100644--- a/apps/web/src/lib/queries/channel/channel-messages.ts+++ b/apps/web/src/lib/queries/channel/channel-messages.ts@@ -1,8 +1,10 @@+import { analytics } from '@app/lib/analytics';import {ThrownResultError,thrownResultErrorHasCode,throwOnErr,} from '@core/util/result';+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';import {type ApiChannelMessage,type ApiResolvedChannelMessage,@@ -29,6 +31,7 @@ import {captureThreadPreviewReplySnapshot,insertReplyIntoThreadPreview,removeReplyFromThreadPreview,+ replaceReplyCreatedAtInThreadPreview,replaceReplyIdInThreadPreview,replaceReplyReactionsInThreadPreview,restoreReplyToThreadPreview,@@ -59,6 +62,122 @@ type ChannelMessagesPageParam = {previous_cursor: string | null;};+export type ChannelMessagesLoadReason =+ | 'watermark'+ | 'list_ahead'+ | 'no_cache'+ | 'cache_not_at_latest'+ | 'load_around'+ | 'delta_overflow'+ | 'catch_up_error';++export type ChannelWatermark =+ | { kind: 'no_cache' }+ | { kind: 'cache_not_at_latest' }+ | {+ kind: 'ready';+ after: string;+ firstPage: ChannelMessagesPage;+ listAhead: boolean;+ };++function isNewerCreatedAt(candidate: string, current: string): boolean {+ const candidateMs = Date.parse(candidate);+ const currentMs = Date.parse(current);+ if (candidateMs !== currentMs) {+ return candidateMs > currentMs;+ }+ return candidate > current;+}++function newestCreatedAt(items: ApiChannelMessage[]): string | null {+ let newest: string | null = null;+ for (const item of items) {+ if (newest === null || isNewerCreatedAt(item.created_at, newest)) {+ newest = item.created_at;+ }+ }+ return newest;+}++export function readChannelWatermark(channelId: string): ChannelWatermark {+ const cached = queryClient.getQueryData<ChannelMessagesData>(+ getChannelMessagesQueryKey(channelId, null)+ );+ const firstPage = cached?.pages[0];+ if (!cached || !firstPage || firstPage.items.length === 0) {+ return { kind: 'no_cache' };+ }+ if (cached.pageParams[0] != null || firstPage.previous_cursor) {+ return { kind: 'cache_not_at_latest' };+ }+ const after = newestCreatedAt(cached.pages.flatMap((page) => page.items));+ if (!after) {+ return { kind: 'no_cache' };+ }+ const cachedIds = new Set(+ cached.pages.flatMap((page) => page.items.map((item) => item.id))+ );+ const list = queryClient.getQueryData<ApiChannelWithLatest[]>(+ channelKeys.listChannels.queryKey+ );+ const latestId = list?.find((channel) => channel.id === channelId)+ ?.latest_non_thread_message?.message_id;+ return {+ kind: 'ready',+ after,+ firstPage,+ listAhead: latestId != null && !cachedIds.has(latestId),+ };+}++export function mergeCatchUpPage(+ delta: ChannelMessagesPage,+ firstPage: ChannelMessagesPage+): ChannelMessagesPage {+ const deltaIds = new Set(delta.items.map((item) => item.id));+ const items = [+ ...delta.items,+ ...firstPage.items.filter((item) => !deltaIds.has(item.id)),+ ];+ items.sort((left, right) => {+ if (isNewerCreatedAt(left.created_at, right.created_at)) return -1;+ if (isNewerCreatedAt(right.created_at, left.created_at)) return 1;+ return 0;+ });+ return {+ items,+ next_cursor: firstPage.next_cursor,+ previous_cursor: null,+ };+}++function trackChannelMessagesLoad(payload: {+ channelId: string;+ path: 'catch_up' | 'full';+ reason: ChannelMessagesLoadReason;+ after?: string;+}) {+ analytics.track('channel_messages_load', payload);+}++async function fetchChannelMessagesPage(+ channelId: string,+ pageParam: ChannelMessagesPageParam | null,+ loadAroundMessageId: string | null+): Promise<ChannelMessagesPage> {+ const page = await throwOnErr(async () =>+ storageServiceClient.getChannelMessages({+ channel_id: channelId,+ limit: pageParam ? 100 : 50,+ next_cursor: pageParam?.next_cursor ?? null,+ previous_cursor: pageParam?.previous_cursor ?? null,+ load_around_message_id: !pageParam ? loadAroundMessageId : null,+ })+ );+ return normalizeChannelMessagesPageSenders(page);+}+export function isMissingChannelMessageError(error: unknown): boolean {return (error instanceof ThrownResultError &&@@ -100,17 +219,84 @@ export function channelMessagesQueryOptions(}: {pageParam: ChannelMessagesPageParam | null;}) => {- const page = await throwOnErr(- async () =>- await storageServiceClient.getChannelMessages({- channel_id: channelId,- limit: pageParam ? 100 : 50,- next_cursor: pageParam?.next_cursor ?? null,- previous_cursor: pageParam?.previous_cursor ?? null,- load_around_message_id: !pageParam ? loadAroundMessageId : null,- })- );- return normalizeChannelMessagesPageSenders(page);+ if (pageParam) {+ return fetchChannelMessagesPage(channelId, pageParam, null);+ }+ if (loadAroundMessageId) {+ const page = await fetchChannelMessagesPage(+ channelId,+ null,+ loadAroundMessageId+ );+ trackChannelMessagesLoad({+ channelId,+ path: 'full',+ reason: 'load_around',+ });+ return page;+ }+ const watermark = readChannelWatermark(channelId);+ if (watermark.kind !== 'ready') {+ const page = await fetchChannelMessagesPage(channelId, null, null);+ trackChannelMessagesLoad({+ channelId,+ path: 'full',+ reason: watermark.kind,+ });+ return page;+ }+ try {+ const delta = normalizeChannelMessagesPageSenders(+ await throwOnErr(() =>+ storageServiceClient.getChannelMessagesCatchUp({+ channel_id: channelId,+ after: watermark.after,+ limit: 50,+ next_cursor: null,+ previous_cursor: null,+ })+ )+ );+ if (delta.next_cursor) {+ const page = await fetchChannelMessagesPage(channelId, null, null);+ trackChannelMessagesLoad({+ channelId,+ path: 'full',+ reason: 'delta_overflow',+ after: watermark.after,+ });+ return page;+ }+ const liveFirstPage = queryClient.getQueryData<ChannelMessagesData>(+ getChannelMessagesQueryKey(channelId, null)+ )?.pages[0];+ const merged = mergeCatchUpPage(+ delta,+ liveFirstPage ?? watermark.firstPage+ );+ trackChannelMessagesLoad({+ channelId,+ path: 'catch_up',+ reason: watermark.listAhead ? 'list_ahead' : 'watermark',+ after: watermark.after,+ });+ return merged;+ } catch (error) {+ if (+ thrownResultErrorHasCode(error, 'UNAUTHORIZED') ||+ thrownResultErrorHasCode(error, 'FORBIDDEN')+ ) {+ throw error;+ }+ const page = await fetchChannelMessagesPage(channelId, null, null);+ trackChannelMessagesLoad({+ channelId,+ path: 'full',+ reason: 'catch_up_error',+ after: watermark.after,+ });+ return page;+ }},initialPageParam: null as ChannelMessagesPageParam | null,getNextPageParam: (lastPage: ChannelMessagesPage) =>@@ -315,6 +501,21 @@ export function replaceTopLevelMessageIdInChannelMessages();}+export function replaceTopLevelMessageCreatedAtInChannelMessages(+ data: ChannelMessagesData | undefined,+ messageIds: readonly string[],+ createdAt: string+): ChannelMessagesData | undefined {+ if (!data || messageIds.length === 0) return data;+ const ids = new Set(messageIds);++ return mapChannelMessagesItems(data, (message) =>+ ids.has(message.id) && message.created_at !== createdAt+ ? { ...message, created_at: createdAt }+ : message+ );+}+export function replaceTopLevelMessageReactionsInChannelMessages(data: ChannelMessagesData | undefined,messageId: string,@@ -457,6 +658,25 @@ export function removeThreadReplyFromChannelMessages(});}+export function replaceThreadReplyCreatedAtInChannelMessages(+ data: ChannelMessagesData | undefined,+ threadId: string,+ replyIds: readonly string[],+ createdAt: string+): ChannelMessagesData | undefined {+ if (!data) return data;++ return mapChannelMessagesItems(data, (message) => {+ if (message.id !== threadId) return message;+ const thread = replaceReplyCreatedAtInThreadPreview(+ message.thread,+ replyIds,+ createdAt+ );+ return thread === message.thread ? message : { ...message, thread };+ });+}+export function replaceThreadReplyIdInChannelMessages(data: ChannelMessagesData | undefined,threadId: string,diff --git a/apps/web/src/lib/queries/channel/reconcile.ts b/apps/web/src/lib/queries/channel/reconcile.tsindex 537a56112c..033657c930 100644--- a/apps/web/src/lib/queries/channel/reconcile.ts+++ b/apps/web/src/lib/queries/channel/reconcile.ts@@ -20,11 +20,13 @@ import {removeThreadReplyFromChannelMessages,removeTopLevelMessageFromChannelMessages,replaceThreadReplyAttachmentsInChannelMessages,+ replaceThreadReplyCreatedAtInChannelMessages,replaceThreadReplyIdInChannelMessages,replaceThreadReplyReactionsInChannelMessages,replaceThreadReplyStateInChannelMessages,replaceTopLevelMessageAttachmentsInChannelMessages,replaceTopLevelMessageAttachmentsInChannelMessagesByIds,+ replaceTopLevelMessageCreatedAtInChannelMessages,replaceTopLevelMessageIdInChannelMessages,replaceTopLevelMessageReactionsInChannelMessages,replaceTopLevelMessageReactionsInChannelMessagesByIds,@@ -46,6 +48,7 @@ import {insertThreadReply,removeThreadReply,replaceThreadReplyAttachments,+ replaceThreadReplyCreatedAt,replaceThreadReplyId,replaceThreadReplyReactions,replaceThreadReplyState,@@ -352,6 +355,36 @@ export function replaceTargetMessageId();}+export function replaceTargetCreatedAt(+ channelId: string,+ target: MessageTarget,+ createdAt: string,+ optimisticId?: string | null+) {+ const ids = [target.messageId, optimisticId].filter(+ (id): id is string => id != null && id !== ''+ );+ if (target.kind === 'thread_reply') {+ queryClient.setQueryData<Array<ApiThreadReply>>(+ getThreadRepliesQueryKey(channelId, target.threadId),+ (prev) => replaceThreadReplyCreatedAt(prev, ids, createdAt)+ );+ setChannelMessagesData(channelId, (prev) =>+ replaceThreadReplyCreatedAtInChannelMessages(+ prev,+ target.threadId,+ ids,+ createdAt+ )+ );+ return;+ }++ setChannelMessagesData(channelId, (prev) =>+ replaceTopLevelMessageCreatedAtInChannelMessages(prev, ids, createdAt)+ );+}+/** Replaces reactions for a target message across all rendered caches. */export function replaceTargetReactions(channelId: string,diff --git a/apps/web/src/lib/queries/channel/sync.ts b/apps/web/src/lib/queries/channel/sync.tsindex f21c3f2fc6..f1eb360722 100644--- a/apps/web/src/lib/queries/channel/sync.ts+++ b/apps/web/src/lib/queries/channel/sync.ts@@ -12,6 +12,7 @@ import {markTopLevelMessageDeletedInTargetCaches,removeMessageFromTargetCaches,replaceTargetAttachments,+ replaceTargetCreatedAt,replaceTargetMessageState,replaceTargetReactions,resolveMessageTarget,@@ -45,9 +46,9 @@ type CommsAttachmentPayload = {/*** Handle incoming message from websocket.*- * If the nonce was registered by this client (optimistic update), we skip the cache- * update since it was already applied. Otherwise, this is an external update- * (other user, other tab, or server-initiated) and we apply it to the cache.+ * If the nonce was registered by this client (optimistic update), we keep the+ * cached row and only adopt the server `created_at`. Otherwise this is an+ * external update and we apply it to the cache.** We always call softInvalidateTargetCaches to ensure eventual consistency:* - Marks query as stale for background refetch when component remounts@@ -60,7 +61,20 @@ export function handleCommsMessage(payload: CommsMessagePayload): void {payload.nonce);- if (isExternalUpdate) {+ if (!isExternalUpdate) {+ if (payload.created_at && !payload.deleted_at) {+ replaceTargetCreatedAt(+ payload.channel_id,+ resolveMessageTarget({+ channelId: payload.channel_id,+ messageId: payload.id,+ threadId: payload.thread_id ?? undefined,+ }),+ payload.created_at,+ payload.nonce+ );+ }+ } else {try {if (payload.deleted_at) {const target = resolveMessageTarget({diff --git a/apps/web/src/lib/queries/channel/tests/channel-messages.test.ts b/apps/web/src/lib/queries/channel/tests/channel-messages.test.tsindex 74d7d0fbd6..70eed4a8d0 100644--- a/apps/web/src/lib/queries/channel/tests/channel-messages.test.ts+++ b/apps/web/src/lib/queries/channel/tests/channel-messages.test.ts@@ -1,14 +1,18 @@-import { err as resultErr } from 'neverthrow';+import { ok, err as resultErr } from 'neverthrow';/*** @vitest-environment jsdom*/import { ThrownResultError } from '@core/util/result';+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';+import type { ApiChannelMessage } from '@service-storage/client';import { QueryClient } from '@tanstack/solid-query';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({getChannelMessages: vi.fn(),+ getChannelMessagesCatchUp: vi.fn(),+ track: vi.fn(),}));let testQueryClient: QueryClient;@@ -22,17 +26,90 @@ vi.mock('../../client', () => ({vi.mock('@service-storage/client', () => ({storageServiceClient: {getChannelMessages: mocks.getChannelMessages,+ getChannelMessagesCatchUp: mocks.getChannelMessagesCatchUp,+ },+}));++vi.mock('@app/lib/analytics', () => ({+ analytics: {+ track: mocks.track,},}));import {+ type ChannelMessagesData,channelMessagesQueryOptions,+ getChannelMessagesQueryKey,isMissingChannelMessageError,+ mergeCatchUpPage,} from '../channel-messages';+import { channelKeys } from '../keys';+import { normalizeChannelMessageSender } from '../message-sender';++function createMessage(+ id: string,+ createdAt: string,+ overrides: Partial<ApiChannelMessage> = {}+): ApiChannelMessage {+ return normalizeChannelMessageSender({+ id,+ channel_id: 'channel-1',+ sender_id: 'user-1',+ content: `Message ${id}`,+ created_at: createdAt,+ updated_at: createdAt,+ deleted_at: undefined,+ edited_at: undefined,+ attachments: [],+ reactions: [],+ thread: {+ preview: [],+ reply_count: 0,+ latest_reply_at: null,+ },+ ...overrides,+ });+}++function seedLatestCache(+ items: ApiChannelMessage[],+ extras?: {+ nextCursor?: string | null;+ previousCursor?: string | null;+ pageParam?: { next_cursor: string | null; previous_cursor: string | null };+ }+) {+ const data: ChannelMessagesData = {+ pages: [+ {+ items,+ next_cursor: extras?.nextCursor ?? 'cached-next',+ previous_cursor: extras?.previousCursor ?? null,+ },+ ],+ pageParams: [extras?.pageParam ?? null],+ };+ testQueryClient.setQueryData(+ getChannelMessagesQueryKey('channel-1', null),+ data+ );+}++function fullPage(+ items: ApiChannelMessage[] = [createMessage('full-1', '2026-09-10T14:00:00Z')]+) {+ return {+ items,+ next_cursor: null,+ previous_cursor: null,+ };+}beforeEach(() => {testQueryClient = new QueryClient();mocks.getChannelMessages.mockReset();+ mocks.getChannelMessagesCatchUp.mockReset();+ mocks.track.mockReset();});afterEach(() => {@@ -83,4 +160,335 @@ describe('channelMessagesQueryOptions', () => {expect(options.retry(0, new Error('network'))).toBe(true);expect(options.retry(1, new Error('network'))).toBe(false);});++ it('first load without cache uses the full endpoint', async () => {+ const page = fullPage();+ mocks.getChannelMessages.mockResolvedValueOnce(ok(page));++ const result = await channelMessagesQueryOptions('channel-1', null).queryFn(+ { pageParam: null }+ );++ expect(mocks.getChannelMessages).toHaveBeenCalledTimes(1);+ expect(mocks.getChannelMessages).toHaveBeenCalledWith({+ channel_id: 'channel-1',+ limit: 50,+ next_cursor: null,+ previous_cursor: null,+ load_around_message_id: null,+ });+ expect(mocks.getChannelMessagesCatchUp).not.toHaveBeenCalled();+ expect(result.items.map((item) => item.id)).toEqual(['full-1']);+ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'full',+ reason: 'no_cache',+ });+ });++ it('cache at latest uses catch-up with the newest cached created_at', async () => {+ const older = createMessage('msg-older', '2026-09-10T13:19:00.123456Z');+ const newer = createMessage('msg-newer', '2026-09-10T13:19:00.123457Z');+ seedLatestCache([older, newer]);+ const deltaItem = createMessage('msg-delta', '2026-09-10T13:20:00.000000Z');+ mocks.getChannelMessagesCatchUp.mockResolvedValueOnce(+ ok({+ items: [deltaItem],+ next_cursor: null,+ previous_cursor: null,+ })+ );++ const result = await channelMessagesQueryOptions('channel-1', null).queryFn(+ { pageParam: null }+ );++ expect(mocks.getChannelMessagesCatchUp).toHaveBeenCalledWith({+ channel_id: 'channel-1',+ after: '2026-09-10T13:19:00.123457Z',+ limit: 50,+ next_cursor: null,+ previous_cursor: null,+ });+ expect(mocks.getChannelMessages).not.toHaveBeenCalled();+ expect(result.items.map((item) => item.id)).toEqual([+ 'msg-delta',+ 'msg-newer',+ 'msg-older',+ ]);+ expect(result.next_cursor).toBe('cached-next');+ expect(result.previous_cursor).toBeNull();+ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'catch_up',+ reason: 'watermark',+ after: '2026-09-10T13:19:00.123457Z',+ });+ });++ it('delta overflow falls back to the full endpoint', async () => {+ seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00.123456Z')]);+ mocks.getChannelMessagesCatchUp.mockResolvedValueOnce(+ ok({+ items: Array.from({ length: 50 }, (_, i) =>+ createMessage(`delta-${i}`, '2026-09-10T13:20:00Z')+ ),+ next_cursor: 'overflow',+ previous_cursor: null,+ })+ );+ const page = fullPage();+ mocks.getChannelMessages.mockResolvedValueOnce(ok(page));++ const result = await channelMessagesQueryOptions('channel-1', null).queryFn(+ { pageParam: null }+ );++ expect(mocks.getChannelMessages).toHaveBeenCalledWith({+ channel_id: 'channel-1',+ limit: 50,+ next_cursor: null,+ previous_cursor: null,+ load_around_message_id: null,+ });+ expect(result.items.map((item) => item.id)).toEqual(['full-1']);+ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'full',+ reason: 'delta_overflow',+ after: '2026-09-10T13:19:00.123456Z',+ });+ });++ it('cache away from latest uses the full endpoint', async () => {+ const page = fullPage();+ mocks.getChannelMessages.mockResolvedValue(ok(page));++ seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00Z')], {+ pageParam: { next_cursor: 'older', previous_cursor: null },+ });+ await channelMessagesQueryOptions('channel-1', null).queryFn({+ pageParam: null,+ });+ expect(mocks.getChannelMessagesCatchUp).not.toHaveBeenCalled();+ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'full',+ reason: 'cache_not_at_latest',+ });++ mocks.track.mockClear();+ mocks.getChannelMessages.mockClear();+ seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00Z')], {+ previousCursor: 'newer',+ });+ await channelMessagesQueryOptions('channel-1', null).queryFn({+ pageParam: null,+ });+ expect(mocks.getChannelMessagesCatchUp).not.toHaveBeenCalled();+ expect(mocks.getChannelMessages).toHaveBeenCalledTimes(1);+ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'full',+ reason: 'cache_not_at_latest',+ });+ });++ it('load-around stays on the full endpoint', async () => {+ seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00Z')]);+ mocks.getChannelMessages.mockResolvedValueOnce(ok(fullPage()));++ await channelMessagesQueryOptions('channel-1', 'message-42').queryFn({+ pageParam: null,+ });++ expect(mocks.getChannelMessages).toHaveBeenCalledWith({+ channel_id: 'channel-1',+ limit: 50,+ next_cursor: null,+ previous_cursor: null,+ load_around_message_id: 'message-42',+ });+ expect(mocks.getChannelMessagesCatchUp).not.toHaveBeenCalled();+ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'full',+ reason: 'load_around',+ });+ });++ it('catch-up failure falls back except on auth errors', async () => {+ seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00.123456Z')]);+ mocks.getChannelMessagesCatchUp.mockResolvedValueOnce(+ resultErr([{ code: 'INTERNAL', message: 'boom' }])+ );+ mocks.getChannelMessages.mockResolvedValueOnce(ok(fullPage()));++ const result = await channelMessagesQueryOptions('channel-1', null).queryFn(+ { pageParam: null }+ );++ expect(result.items.map((item) => item.id)).toEqual(['full-1']);+ expect(mocks.getChannelMessages).toHaveBeenCalledTimes(1);+ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'full',+ reason: 'catch_up_error',+ after: '2026-09-10T13:19:00.123456Z',+ });++ mocks.getChannelMessages.mockClear();+ mocks.track.mockClear();+ mocks.getChannelMessagesCatchUp.mockResolvedValueOnce(+ resultErr([{ code: 'UNAUTHORIZED', message: 'nope' }])+ );++ await expect(+ channelMessagesQueryOptions('channel-1', null).queryFn({+ pageParam: null,+ })+ ).rejects.toBeInstanceOf(ThrownResultError);+ expect(mocks.getChannelMessages).not.toHaveBeenCalled();+ });++ it('list ahead sets the reason', async () => {+ seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00.123456Z')]);+ testQueryClient.setQueryData(channelKeys.listChannels.queryKey, [+ {+ id: 'channel-1',+ latest_non_thread_message: {+ message_id: 'msg-from-list',+ created_at: '2026-09-10T14:00:00Z',+ content: 'ahead',+ mentions: [],+ sender_id: 'user-1',+ updated_at: '2026-09-10T14:00:00Z',+ },+ },+ ] as unknown as ApiChannelWithLatest[]);+ mocks.getChannelMessagesCatchUp.mockResolvedValueOnce(+ ok({+ items: [createMessage('msg-delta', '2026-09-10T13:20:00Z')],+ next_cursor: null,+ previous_cursor: null,+ })+ );++ await channelMessagesQueryOptions('channel-1', null).queryFn({+ pageParam: null,+ });++ expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {+ channelId: 'channel-1',+ path: 'catch_up',+ reason: 'list_ahead',+ after: '2026-09-10T13:19:00.123456Z',+ });+ });++ it('catch-up merge uses the live first page, not the pre-request snapshot', async () => {+ const cached = createMessage('msg-1', '2026-09-10T13:19:00.123456Z');+ seedLatestCache([cached]);+ let releaseCatchUp!: () => void;+ const holdCatchUp = new Promise<void>((resolve) => {+ releaseCatchUp = resolve;+ });+ mocks.getChannelMessagesCatchUp.mockImplementationOnce(async () => {+ await holdCatchUp;+ return ok({+ items: [createMessage('msg-delta', '2026-09-10T13:20:00.000000Z')],+ next_cursor: null,+ previous_cursor: null,+ });+ });++ const pending = channelMessagesQueryOptions('channel-1', null).queryFn({+ pageParam: null,+ });+ await Promise.resolve();+ seedLatestCache([+ createMessage('msg-live', '2026-09-10T13:21:00.000000Z', {+ content: 'from websocket',+ }),+ cached,+ ]);+ releaseCatchUp();++ const result = await pending;+ expect(result.items.map((item) => item.id)).toEqual([+ 'msg-live',+ 'msg-delta',+ 'msg-1',+ ]);+ expect(result.items[0]?.content).toBe('from websocket');+ });++ it('later pages keep using the full endpoint without an event', async () => {+ mocks.getChannelMessages.mockResolvedValueOnce(ok(fullPage()));++ await channelMessagesQueryOptions('channel-1', null).queryFn({+ pageParam: { next_cursor: 'page-2', previous_cursor: null },+ });++ expect(mocks.getChannelMessages).toHaveBeenCalledWith({+ channel_id: 'channel-1',+ limit: 100,+ next_cursor: 'page-2',+ previous_cursor: null,+ load_around_message_id: null,+ });+ expect(mocks.getChannelMessagesCatchUp).not.toHaveBeenCalled();+ expect(mocks.track).not.toHaveBeenCalled();+ });+});++describe('mergeCatchUpPage', () => {+ it('merge drops duplicates by id', () => {+ const cached = createMessage('msg-1', '2026-09-10T13:19:00Z');+ const deltaDup = createMessage('msg-1', '2026-09-10T13:19:00Z', {+ content: 'from delta',+ });+ const deltaNew = createMessage('msg-2', '2026-09-10T13:20:00Z');+ const merged = mergeCatchUpPage(+ {+ items: [deltaNew, deltaDup],+ next_cursor: 'ignore-me',+ previous_cursor: 'also-ignore',+ },+ {+ items: [cached],+ next_cursor: 'cached-next',+ previous_cursor: 'cached-prev',+ }+ );++ expect(merged.items.map((item) => item.id)).toEqual(['msg-2', 'msg-1']);+ expect(merged.items[1]?.content).toBe('from delta');+ expect(merged.next_cursor).toBe('cached-next');+ expect(merged.previous_cursor).toBeNull();+ });++ it('keeps a newer live insert ahead of older delta rows', () => {+ const cached = createMessage('msg-1', '2026-09-10T13:19:00Z');+ const live = createMessage('msg-live', '2026-09-10T13:21:00Z');+ const delta = createMessage('msg-delta', '2026-09-10T13:20:00Z');+ const merged = mergeCatchUpPage(+ {+ items: [delta],+ next_cursor: null,+ previous_cursor: null,+ },+ {+ items: [live, cached],+ next_cursor: 'cached-next',+ previous_cursor: null,+ }+ );++ expect(merged.items.map((item) => item.id)).toEqual([+ 'msg-live',+ 'msg-delta',+ 'msg-1',+ ]);+ });});diff --git a/apps/web/src/lib/queries/channel/tests/sync.test.ts b/apps/web/src/lib/queries/channel/tests/sync.test.tsindex 85770f70dc..8eb1ee6490 100644--- a/apps/web/src/lib/queries/channel/tests/sync.test.ts+++ b/apps/web/src/lib/queries/channel/tests/sync.test.ts@@ -22,8 +22,10 @@ vi.mock('@service-storage/client', () => ({storageServiceClient: {},}));+import { registerNonce } from '../../nonce';import type { ChannelMessagesData } from '../channel-messages';import { getChannelMessagesQueryKey } from '../channel-messages';+import { ChannelNonceKeys } from '../keys';import {normalizeChannelMessageSender,normalizeThreadReplySender,@@ -248,4 +250,33 @@ describe('channel sync', () => {{ emoji: '👍', users: ['user-1'] },]);});++ it('adopts server created_at on an own message echo', () => {+ registerNonce(ChannelNonceKeys.MESSAGE, 'own-nonce');+ testQueryClient.setQueryData(+ getChannelMessagesQueryKey('channel-1'),+ createChannelMessagesData([+ [createPaginatedMessage('own-nonce', '2026-09-10T13:20:00.000Z')],+ ])+ );++ handleCommsMessage({+ channel_id: 'channel-1',+ id: 'server-msg',+ thread_id: null,+ created_at: '2026-09-10T13:19:00.500Z',+ updated_at: '2026-09-10T13:19:00.500Z',+ nonce: 'own-nonce',+ sender_id: 'user-1',+ content: 'hello',+ } as Parameters<typeof handleCommsMessage>[0]);++ const cached = testQueryClient.getQueryData<ChannelMessagesData>(+ getChannelMessagesQueryKey('channel-1')+ );+ expect(cached?.pages[0].items[0].id).toBe('own-nonce');+ expect(cached?.pages[0].items[0].created_at).toBe(+ '2026-09-10T13:19:00.500Z'+ );+ });});diff --git a/apps/web/src/lib/queries/channel/thread-preview.ts b/apps/web/src/lib/queries/channel/thread-preview.tsindex 0b4bd2668e..8accf9e1ba 100644--- a/apps/web/src/lib/queries/channel/thread-preview.ts+++ b/apps/web/src/lib/queries/channel/thread-preview.ts@@ -48,6 +48,23 @@ export function removeReplyFromThreadPreview(};}+export function replaceReplyCreatedAtInThreadPreview(+ thread: ThreadPreviewState,+ replyIds: readonly string[],+ createdAt: string+): ThreadPreviewState {+ if (replyIds.length === 0) return thread;+ const ids = new Set(replyIds);+ let didChange = false;+ const preview = thread.preview.map((reply) => {+ if (!ids.has(reply.id) || reply.created_at === createdAt) return reply;+ didChange = true;+ return { ...reply, created_at: createdAt };+ });++ return didChange ? { ...thread, preview } : thread;+}+export function replaceReplyIdInThreadPreview(thread: ThreadPreviewState,optimisticId: string,diff --git a/apps/web/src/lib/queries/channel/thread-replies.ts b/apps/web/src/lib/queries/channel/thread-replies.tsindex 97e992e555..4e0baaed0b 100644--- a/apps/web/src/lib/queries/channel/thread-replies.ts+++ b/apps/web/src/lib/queries/channel/thread-replies.ts@@ -90,6 +90,24 @@ export function removeThreadReply(return nextReplies.length === data.length ? data : nextReplies;}+export function replaceThreadReplyCreatedAt(+ data: Array<ApiThreadReply> | undefined,+ replyIds: readonly string[],+ createdAt: string+): Array<ApiThreadReply> | undefined {+ if (!data || replyIds.length === 0) return data;+ const ids = new Set(replyIds);++ let didChange = false;+ const nextReplies = data.map((reply) => {+ if (!ids.has(reply.id) || reply.created_at === createdAt) return reply;+ didChange = true;+ return { ...reply, created_at: createdAt };+ });++ return didChange ? nextReplies : data;+}+export function replaceThreadReplyId(data: Array<ApiThreadReply> | undefined,optimisticId: string,diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex 3d59803edd..ae495610af 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -1020,6 +1020,31 @@ export const storageServiceClient = {).map((result) => result);},+ async getChannelMessagesCatchUp(+ args: WithChannelId & {+ after: string;+ limit: number;+ next_cursor: string | null;+ previous_cursor: string | null;+ }+ ) {+ const { channel_id, after, limit, next_cursor, previous_cursor } = args;+ const params = new URLSearchParams();+ params.append('after', after);+ params.append('limit', limit.toString());+ if (next_cursor) {+ params.append('cursor', next_cursor);+ } else if (previous_cursor) {+ params.append('previous_cursor', previous_cursor);+ }+ return (+ await dssFetch<ApiChannelMessagesPage>(+ `/channels/${channel_id}/messages/catch-up?${params.toString()}`,+ { method: 'GET' }+ )+ ).map((result) => result);+ },+async postChannelMessages(args: WithChannelId & { filters: ChannelMessageFilters; limit?: number }) {diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 4c9511996f..ee122c773a 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -101,6 +101,15 @@ A touch tap leaves pending navigation intact; a vertical finger drag cancels it.The `[data-channel-scroll]` element is the scroll surface. Its virtualized rows arekeyed by message ID; offscreen rows are normally absent from the DOM.+Reopening a channel already loaded this session requests+`GET /dss/channels/<id>/messages/catch-up?after=<newest cached created_at>&limit=50`+and merges the result into the cached first page. A first open, a message link,+a channel cached away from its latest page, and a delta longer than one page use+`GET /dss/channels/<id>/messages`. The `channel_messages_load` event records+`path` (`catch_up` or `full`) and `reason`+(`watermark`, `list_ahead`, `no_cache`, `cache_not_at_latest`, `load_around`,+`delta_overflow`, or `catch_up_error`).+## Chat navigation railOn desktop, the Chat rail has `Browse` and `Recents` tabs. Browse contains