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
fix(channels): revalidate cached messages after reconnect (#8276)
Sean Ayecaab7c0dcab0
diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.tsindex 2871ec150c..474ab37d6e 100644--- a/apps/web/src/lib/analytics/app-events.ts+++ b/apps/web/src/lib/analytics/app-events.ts@@ -202,16 +202,8 @@ export type AppEvents = {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;+ path: 'full';+ reason: 'no_cache' | 'cache_not_at_latest' | 'load_around' | 'revalidate';};channel_reaction: {emoji: string;diff --git a/apps/web/src/lib/queries/messages/sync.ts b/apps/web/src/lib/queries/messages/sync.tsindex 17e5363e03..b4f88c8c50 100644--- a/apps/web/src/lib/queries/messages/sync.ts+++ b/apps/web/src/lib/queries/messages/sync.ts@@ -1,4 +1,5 @@import { fireAndForget } from '@core/util/fireAndForget';+import { Telemetry } from '@macro-inc/observability';import type { MessageEvent } from '@service-storage/generated/schemas/messageEvent';import type {Message,@@ -31,6 +32,56 @@ import {} from './timeline';import { handleCommsTyping } from './typing';+/**+ * A refetch can have read before this committed event, including on a page that+ * has already resolved while older pages are still loading. Restart the whole+ * fetch after updating the visible cache so its eventual commit cannot undo the+ * event. Idle timelines still apply live updates without making a request.+ */+async function restartPendingChannelTimeline(parent: MessageParent) {+ if (parent.type !== 'channel') return;+ const pending = queryClient.getQueryCache().findAll({+ queryKey: getMessageTimelineQueryKeyPrefix(parent),+ type: 'active',+ predicate: (query) =>+ query.state.data !== undefined && query.state.fetchStatus === 'fetching',+ });+ if (pending.length === 0) return;+ await Telemetry.span('channel.timeline_restart', async (span) => {+ span.setAttr('channel.id', parent.id);+ span.setAttr('query.count', pending.length);+ span.setAttr(+ 'query.fetch_more_directions',+ pending.map(+ (query) => query.state.fetchMeta?.fetchMore?.direction ?? 'refetch'+ )+ );+ // Keep fetchMore direction: replacing pagination with an ordinary refetch+ // would silently discard the user's request for an older/newer page.+ const results = await Promise.allSettled(+ pending.map((query) =>+ query.fetch(undefined, {+ cancelRefetch: true,+ meta: query.state.fetchMeta ?? undefined,+ })+ )+ );+ const rejected = results.filter(+ (result) => result.status === 'rejected'+ ).length;+ span.setAttr(+ 'query.outcomes',+ results.map((result) => result.status)+ );+ span.setAttr('query.fulfilled_count', results.length - rejected);+ span.setAttr('query.rejected_count', rejected);+ if (rejected > 0) {+ // Request errors can contain URLs or message data; record only a category.+ span.error('Channel timeline restart failed');+ }+ });+}+/** Committed timeline activity, delivered whole so loaded history needs no re-read. */export function handleTimelineActivity(event: {parent: MessageParent;@@ -44,6 +95,7 @@ export function handleTimelineActivity(event: {{ queryKey: getMessageTimelineQueryKeyPrefix(event.parent) },(data) => insertActivitiesIntoMessageTimeline(data, event.activities));+ fireAndForget(restartPendingChannelTimeline(event.parent), 'messages-sync');}type ThreadStateListener = (@@ -117,6 +169,7 @@ export function applyMessage(patchTargetMessage(parent, target, normalized);}softInvalidateTargetCaches(parent, target);+ fireAndForget(restartPendingChannelTimeline(parent), 'messages-sync');// Calls have one thread and no mounted timeline to seed its first fetch.// A view may still be showing the empty response when the first post arrives.if (@@ -306,6 +359,8 @@ export function applyThreadState(: undefined);for (const listener of threadStateListeners) listener(parent, state);+ if (!state.deleted_at)+ fireAndForget(restartPendingChannelTimeline(parent), 'messages-sync');if (state.deleted_at) {// Annotation layout also reads tombstones, including roots outside loaded// pages. Fetch the committed state so it survives late document mounting.diff --git a/apps/web/src/lib/queries/messages/tests/revalidation.test.ts b/apps/web/src/lib/queries/messages/tests/revalidation.test.tsnew file mode 100644index 0000000000..26f93d6bfa--- /dev/null+++ b/apps/web/src/lib/queries/messages/tests/revalidation.test.ts@@ -0,0 +1,573 @@+import type { Span } from '@macro-inc/observability';+import type {+ MessageListItem,+ MessageParent,+ MessageTimelinePage,+} from '@service-storage/messages';+import { InfiniteQueryObserver, QueryClient } from '@tanstack/solid-query';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => {+ const setAttr = vi.fn();+ const spanError = vi.fn();+ return {+ timeline: vi.fn(),+ reportError: vi.fn(),+ setAttr,+ spanError,+ trace: vi.fn(+ async (+ _name: string,+ work: (span: Pick<Span, 'setAttr' | 'error'>) => Promise<void>+ ) => {+ await work({ setAttr, error: spanError });+ }+ ),+ };+});+let queryClient: QueryClient;+vi.mock('../../client', () => ({+ get queryClient() {+ return queryClient;+ },+}));+vi.mock('@service-storage/messages', () => ({+ entityMessagesClient: { timeline: mocks.timeline },+}));+vi.mock('@app/lib/analytics', () => ({ analytics: { track: vi.fn() } }));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: { error: mocks.reportError, span: mocks.trace },+}));+vi.mock('../subscription', () => ({ useMessageSubscription() {} }));++import {+ applyThreadState,+ handleMessageEvent,+ handleTimelineActivity,+} from '../sync';+import {+ type MessageTimelineData,+ messageTimelineQueryOptions,+} from '../timeline';+import { timelineMessages } from '../timeline-entries';++const parent: MessageParent = { type: 'channel', id: 'channel-1' };+const root: MessageListItem = {+ id: 'root',+ parent,+ thread_id: null,+ sender_id: 'user-1',+ mentions: [],+ content: 'Existing root',+ created_at: '2026-10-15T14:28:00Z',+ updated_at: '2026-10-15T14:28:00Z',+ attachments: [],+ reactions: [],+ state: {+ root_id: 'root',+ user_id: 'user-1',+ resolved: false,+ anchor: null,+ created_at: '2026-10-15T14:28:00Z',+ updated_at: '2026-10-15T14:28:00Z',+ },+ thread: { reply_count: 0, preview: [], latest_reply_at: null },+};+const missedReply = {+ ...root,+ id: 'missed-reply',+ thread_id: root.id,+ content: 'Missed while disconnected',+ created_at: '2026-10-15T14:29:00Z',+};+const liveReply = {+ ...missedReply,+ id: 'live-reply',+ content: 'Posted during reconnect',+ created_at: '2026-10-15T14:31:00Z',+};+const disposers: (() => void)[] = [];++beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ mocks.timeline.mockReset();+ mocks.reportError.mockReset();+ mocks.trace.mockClear();+ mocks.setAttr.mockClear();+ mocks.spanError.mockClear();+});+afterEach(() => {+ for (const dispose of disposers.splice(0)) dispose();+ queryClient.clear();+ vi.restoreAllMocks();+});++it.each(['message', 'activity', 'thread'] as const)(+ 'reports a failed %s timeline restart instead of leaving its promise unhandled',+ async (event) => {+ const failure = new Error('Unable to restart the timeline');+ const reported = Promise.withResolvers<void>();+ mocks.reportError.mockImplementation(() => reported.resolve());+ const cache = queryClient.getQueryCache();+ const findAll = cache.findAll.bind(cache);+ vi.spyOn(cache, 'findAll').mockImplementation((filters) => {+ if (filters?.type === 'active') throw failure;+ return findAll(filters);+ });++ if (event === 'message') {+ handleMessageEvent({+ parent,+ actor: 'user-2',+ change: {+ type: 'posted',+ message: liveReply,+ mentions: [],+ notification_policy: 'Default',+ },+ });+ } else if (event === 'activity') {+ handleTimelineActivity({+ parent,+ activities: [+ {+ id: 'activity',+ actor_id: 'user-2',+ action: 'renamed',+ occurred_at: '2026-10-15T14:33:00Z',+ payload: { to: 'Renamed channel' },+ },+ ],+ });+ } else {+ applyThreadState(parent, { ...root.state, resolved: true });+ }++ await reported.promise;+ expect(mocks.reportError).toHaveBeenCalledExactlyOnceWith(failure, {+ surface: 'messages-sync',+ });+ }+);++it.each(['reaction', 'reply'] as const)(+ 'recovers missed replies even when a live %s changes the same root during refresh',+ async (change) => {+ const options = messageTimelineQueryOptions(parent, null);+ const initial: MessageTimelinePage = {+ entries: [{ type: 'message', message: root }],+ next_cursor: null,+ previous_cursor: null,+ };+ queryClient.setQueryData<MessageTimelineData>(options.queryKey, {+ pages: [initial],+ pageParams: [null],+ });+ const observer = new InfiniteQueryObserver(queryClient, options);+ disposers.push(observer.subscribe(() => {}));+ const outdated = Promise.withResolvers<MessageTimelinePage>();+ const refreshed = {+ ...root,+ reactions:+ change === 'reaction' ? [{ emoji: '❤️', users: ['user-2'] }] : [],+ thread: {+ reply_count: change === 'reply' ? 2 : 1,+ preview: change === 'reply' ? [missedReply, liveReply] : [missedReply],+ latest_reply_at:+ change === 'reply' ? liveReply.created_at : missedReply.created_at,+ },+ };+ mocks.timeline.mockReturnValueOnce(outdated.promise).mockResolvedValueOnce({+ ...initial,+ entries: [{ type: 'message', message: refreshed }],+ });++ const firstFetch = observer.refetch();+ handleMessageEvent({+ parent,+ actor: 'user-2',+ change:+ change === 'reaction'+ ? {+ type: 'reaction_changed',+ message: { ...root, reactions: refreshed.reactions },+ added: true,+ emoji: '❤️',+ }+ : {+ type: 'posted',+ message: liveReply,+ mentions: [],+ notification_policy: 'Default',+ },+ });+ const finalFetch = queryClient+ .getQueryCache()+ .find({ queryKey: options.queryKey })?.promise;+ outdated.resolve(initial);+ await Promise.all([firstFetch, finalFetch]);++ expect(mocks.timeline).toHaveBeenCalledTimes(2);+ expect(mocks.trace).toHaveBeenCalledExactlyOnceWith(+ 'channel.timeline_restart',+ expect.any(Function)+ );+ await mocks.trace.mock.results[0].value;+ expect(mocks.setAttr.mock.calls).toEqual([+ ['channel.id', parent.id],+ ['query.count', 1],+ ['query.fetch_more_directions', ['refetch']],+ ['query.outcomes', ['fulfilled']],+ ['query.fulfilled_count', 1],+ ['query.rejected_count', 0],+ ]);+ expect(mocks.spanError).not.toHaveBeenCalled();+ const data = queryClient.getQueryData<MessageTimelineData>(+ options.queryKey+ );+ expect(data?.pages[0].entries).toMatchObject([+ { type: 'message', message: refreshed },+ ]);+ }+);++it.each(['root', 'reply', 'edit', 'delete', 'thread', 'activity'] as const)(+ 'restarts the whole paginated refresh when a live %s arrives after page one resolves',+ async (change) => {+ const older = { ...root, id: 'older', created_at: '2026-10-15T14:00:00Z' };+ const live = {+ ...root,+ id: 'new-root',+ created_at: '2026-10-15T14:32:00Z',+ };+ const cursor = { id: root.id, created_at: root.created_at };+ const latest: MessageTimelinePage = {+ entries: [{ type: 'message', message: root }],+ next_cursor: cursor,+ previous_cursor: null,+ };+ const history: MessageTimelinePage = {+ entries: [{ type: 'message', message: older }],+ next_cursor: null,+ previous_cursor: null,+ };+ const options = messageTimelineQueryOptions(parent, null);+ queryClient.setQueryData<MessageTimelineData>(options.queryKey, {+ pages: [latest, history],+ pageParams: [null, { next_cursor: cursor, previous_cursor: null }],+ });+ const observer = new InfiniteQueryObserver(queryClient, options);+ disposers.push(observer.subscribe(() => {}));+ const historyRequested = Promise.withResolvers<void>();+ const outdatedHistory = Promise.withResolvers<MessageTimelinePage>();+ const activity = {+ id: 'activity',+ actor_id: 'user-2',+ action: 'renamed' as const,+ occurred_at: '2026-10-15T14:33:00Z',+ payload: { to: 'Renamed channel' },+ };+ const updatedRoot =+ change === 'reply'+ ? {+ ...root,+ thread: {+ reply_count: 1,+ preview: [liveReply],+ latest_reply_at: liveReply.created_at,+ },+ }+ : change === 'thread'+ ? { ...root, state: { ...root.state, resolved: true } }+ : root;+ const refreshed: MessageTimelinePage = {+ ...latest,+ entries: [+ ...(change === 'root'+ ? [{ type: 'message' as const, message: live }]+ : []),+ ...(change === 'activity'+ ? [{ type: 'activity' as const, activity }]+ : []),+ { type: 'message', message: updatedRoot },+ ],+ };+ const refreshedHistory: MessageTimelinePage = {+ ...history,+ entries:+ change === 'delete'+ ? []+ : [+ {+ type: 'message',+ message:+ change === 'edit'+ ? { ...older, content: 'Live edit on older page' }+ : older,+ },+ ],+ };+ mocks.timeline+ .mockResolvedValueOnce(latest)+ .mockImplementationOnce(() => {+ historyRequested.resolve();+ return outdatedHistory.promise;+ })+ .mockResolvedValueOnce(refreshed)+ .mockResolvedValueOnce(refreshedHistory);++ const firstFetch = observer.refetch();+ await historyRequested.promise;+ if (change === 'activity') {+ handleTimelineActivity({ parent, activities: [activity] });+ } else if (change === 'thread') {+ applyThreadState(parent, updatedRoot.state);+ } else {+ handleMessageEvent({+ parent,+ actor: 'user-2',+ change:+ change === 'root' || change === 'reply'+ ? {+ type: 'posted',+ message: change === 'root' ? live : liveReply,+ mentions: [],+ notification_policy: 'Default',+ }+ : change === 'edit'+ ? {+ type: 'edited',+ message: { ...older, content: 'Live edit on older page' },+ previous_attachments: [],+ mentions: [],+ notification_policy: 'Default',+ }+ : {+ type: 'message_deleted',+ message: { ...older, deleted_at: '2026-10-15T14:33:00Z' },+ },+ });+ }+ const finalFetch = queryClient+ .getQueryCache()+ .find({ queryKey: options.queryKey })?.promise;+ outdatedHistory.resolve(history);+ await Promise.all([firstFetch, finalFetch]);++ expect(mocks.timeline).toHaveBeenCalledTimes(4);+ const data = queryClient.getQueryData<MessageTimelineData>(+ options.queryKey+ );+ expect(data?.pages).toMatchObject([refreshed, refreshedHistory]);+ expect(+ data?.pages.flatMap(timelineMessages).map((message) => message.id)+ ).toEqual(+ change === 'root'+ ? ['new-root', 'root', 'older']+ : change === 'delete'+ ? ['root']+ : ['root', 'older']+ );+ }+);++it.each(['older', 'newer'] as const)(+ 'preserves pending %s pagination when a live edit restarts its request',+ async (direction) => {+ const cursor = { id: root.id, created_at: root.created_at };+ const options = messageTimelineQueryOptions(parent, null);+ queryClient.setQueryData<MessageTimelineData>(options.queryKey, {+ pages: [+ {+ entries: [{ type: 'message', message: root }],+ next_cursor: direction === 'older' ? cursor : null,+ previous_cursor: direction === 'newer' ? cursor : null,+ },+ ],+ pageParams: [null],+ });+ const observer = new InfiniteQueryObserver(queryClient, options);+ disposers.push(observer.subscribe(() => {}));+ const delayed = Promise.withResolvers<MessageTimelinePage>();+ const next = {+ ...root,+ id: direction,+ created_at:+ direction === 'older' ? '2026-10-15T14:00:00Z' : '2026-10-15T14:32:00Z',+ };+ const page: MessageTimelinePage = {+ entries: [{ type: 'message', message: next }],+ next_cursor: null,+ previous_cursor: null,+ };+ mocks.timeline+ .mockReturnValueOnce(delayed.promise)+ .mockResolvedValueOnce(page);++ const firstFetch =+ direction === 'older'+ ? observer.fetchNextPage()+ : observer.fetchPreviousPage();+ handleMessageEvent({+ parent,+ actor: 'user-2',+ change: {+ type: 'edited',+ message: { ...root, content: 'Live edit' },+ mentions: [],+ notification_policy: 'Default',+ previous_attachments: [],+ },+ });+ const finalFetch = queryClient+ .getQueryCache()+ .find({ queryKey: options.queryKey })?.promise;+ delayed.resolve(page);+ await Promise.all([firstFetch, finalFetch]);++ expect(mocks.timeline).toHaveBeenCalledTimes(2);+ await mocks.trace.mock.results[0].value;+ expect(mocks.setAttr).toHaveBeenCalledWith('query.fetch_more_directions', [+ direction === 'older' ? 'forward' : 'backward',+ ]);+ expect(mocks.setAttr).toHaveBeenCalledWith('query.outcomes', ['fulfilled']);+ for (const call of mocks.timeline.mock.calls) {+ expect(call).toEqual([+ parent,+ {+ limit: 100,+ cursor,+ direction,+ around: null,+ include_deleted_threads: false,+ },+ ]);+ }+ const data = queryClient.getQueryData<MessageTimelineData>(+ options.queryKey+ );+ expect(data?.pages).toHaveLength(2);+ expect(+ data?.pages.flatMap(timelineMessages).map((message) => message.id)+ ).toEqual(direction === 'older' ? ['root', 'older'] : ['newer', 'root']);+ expect(+ data?.pages+ .flatMap(timelineMessages)+ .find((message) => message.id === root.id)?.content+ ).toBe('Live edit');+ }+);++it.each(['partial', 'all'] as const)(+ 'records %s restart failures without exposing request errors or rejecting the flow',+ async (failed) => {+ const page: MessageTimelinePage = {+ entries: [{ type: 'message', message: root }],+ next_cursor: null,+ previous_cursor: null,+ };+ const options = [+ messageTimelineQueryOptions(parent, null),+ messageTimelineQueryOptions(parent, root.id),+ ];+ const observers = options.map((queryOptions) => {+ queryClient.setQueryData<MessageTimelineData>(queryOptions.queryKey, {+ pages: [page],+ pageParams: [null],+ });+ const observer = new InfiniteQueryObserver(queryClient, {+ ...queryOptions,+ retry: false,+ });+ disposers.push(observer.subscribe(() => {}));+ return observer;+ });+ const oldFirst = Promise.withResolvers<MessageTimelinePage>();+ const oldSecond = Promise.withResolvers<MessageTimelinePage>();+ const failure = new Error('Request error containing private data');+ mocks.timeline+ .mockReturnValueOnce(oldFirst.promise)+ .mockReturnValueOnce(oldSecond.promise);+ if (failed === 'all') mocks.timeline.mockRejectedValueOnce(failure);+ else+ mocks.timeline.mockResolvedValueOnce({+ ...page,+ entries: [+ {+ type: 'message',+ message: { ...root, state: { ...root.state, resolved: true } },+ },+ ],+ });+ mocks.timeline.mockRejectedValueOnce(failure);+ const initialFetches = observers.map((observer) => observer.refetch());++ applyThreadState(parent, { ...root.state, resolved: true });+ oldFirst.resolve(page);+ oldSecond.resolve(page);+ await Promise.all(initialFetches);+ expect(mocks.trace).toHaveBeenCalledExactlyOnceWith(+ 'channel.timeline_restart',+ expect.any(Function)+ );+ await mocks.trace.mock.results[0].value;++ expect(mocks.setAttr.mock.calls).toEqual([+ ['channel.id', parent.id],+ ['query.count', 2],+ ['query.fetch_more_directions', ['refetch', 'refetch']],+ [+ 'query.outcomes',+ [failed === 'all' ? 'rejected' : 'fulfilled', 'rejected'],+ ],+ ['query.fulfilled_count', failed === 'all' ? 0 : 1],+ ['query.rejected_count', failed === 'all' ? 2 : 1],+ ]);+ expect(mocks.spanError).toHaveBeenCalledExactlyOnceWith(+ 'Channel timeline restart failed'+ );+ expect(mocks.reportError).not.toHaveBeenCalled();+ expect(queryClient.getQueryState(options[1].queryKey)?.error).toBe(failure);+ }+);++it('does not fetch idle channels for ordinary live updates', () => {+ const options = messageTimelineQueryOptions(parent, null);+ queryClient.setQueryData<MessageTimelineData>(options.queryKey, {+ pages: [+ {+ entries: [{ type: 'message', message: root }],+ next_cursor: null,+ previous_cursor: null,+ },+ ],+ pageParams: [null],+ });+ const observer = new InfiniteQueryObserver(queryClient, options);+ disposers.push(observer.subscribe(() => {}));++ handleMessageEvent({+ parent,+ actor: 'user-2',+ change: {+ type: 'posted',+ message: liveReply,+ mentions: [],+ notification_policy: 'Default',+ },+ });++ expect(mocks.timeline).not.toHaveBeenCalled();+ expect(mocks.trace).not.toHaveBeenCalled();+ expect(+ queryClient.getQueryData<MessageTimelineData>(options.queryKey)?.pages[0]+ .entries+ ).toMatchObject([+ {+ type: 'message',+ message: { thread: { reply_count: 1, preview: [liveReply] } },+ },+ ]);+});diff --git a/apps/web/src/lib/queries/messages/tests/timeline.test.ts b/apps/web/src/lib/queries/messages/tests/timeline.test.tsindex 5f3e0b1b8c..2f7b9a01c0 100644--- a/apps/web/src/lib/queries/messages/tests/timeline.test.ts+++ b/apps/web/src/lib/queries/messages/tests/timeline.test.ts@@ -11,7 +11,7 @@ import type {MessageTimelineEntry,TimelineActivity,} from '@service-storage/messages';-import { QueryClient } from '@tanstack/solid-query';+import { InfiniteQueryObserver, QueryClient } from '@tanstack/solid-query';import { createRoot } from 'solid-js';import { createStore, reconcile } from 'solid-js/store';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -130,7 +130,10 @@ function seedLatestCache(],pageParams: [extras?.pageParam ?? null],};- testQueryClient.setQueryData(getMessageTimelineQueryKey(parent, null), data);+ testQueryClient.setQueryData(+ getMessageTimelineQueryKey(items[0]?.parent ?? parent, null),+ data+ );}function fullPage(@@ -261,44 +264,81 @@ describe('messageTimelineQueryOptions', () => {expect(mocks.track).not.toHaveBeenCalled();});- it('cache at latest fetches only roots newer than the newest cached root', async () => {- const older = createMessage('msg-older', '2026-09-10T13:19:00.123456Z');- const newer = createMessage('msg-newer', '2026-09-10T13:19:00.123457Z');+ it('recovers missed replies, reactions, edits, and deletions on cached channel roots', async () => {+ const root = createMessage('root', '2026-09-10T13:19:00Z');+ const deleted = createMessage('deleted', '2026-09-10T13:18:00Z');+ const reply = createMessage('reply', '2026-09-10T13:20:00Z', {+ thread_id: root.id,+ content: 'Posted while disconnected',+ });+ const refreshed = {+ ...root,+ content: 'Edited while disconnected',+ reactions: [{ emoji: '❤️', users: ['user-2'] }],+ thread: {+ reply_count: 1,+ preview: [reply],+ latest_reply_at: reply.created_at,+ },+ };+ seedLatestCache([root, deleted]);+ // A created-at delta is empty: only an existing root changed.+ mocks.timeline.mockImplementation(async (_parent, selection) =>+ fullPage(selection.cursor ? [] : [refreshed])+ );++ const result = await messageTimelineQueryOptions(parent, null).queryFn({+ pageParam: null,+ });++ expect(timelineMessages(result)).toEqual([refreshed]);+ expect(mocks.timeline).toHaveBeenCalledOnce();+ expect(mocks.timeline).toHaveBeenCalledWith(parent, fullSelection);+ });++ it('document catch-up still fetches only roots newer than the newest cached root', async () => {+ const older = createMessage('msg-older', '2026-09-10T13:19:00.123456Z', {+ parent: document,+ });+ const newer = createMessage('msg-newer', '2026-09-10T13:19:00.123457Z', {+ parent: document,+ });seedLatestCache([older, newer]);- const deltaItem = createMessage('msg-delta', '2026-09-10T13:20:00.000000Z');+ const deltaItem = createMessage(+ 'msg-delta',+ '2026-09-10T13:20:00.000000Z',+ {+ parent: document,+ }+ );mocks.timeline.mockResolvedValueOnce({entries: entries([deltaItem]),next_cursor: cursor('msg-delta', '2026-09-10T13:20:00.000000Z'),previous_cursor: null,});- const result = await messageTimelineQueryOptions(parent, null).queryFn({+ const result = await messageTimelineQueryOptions(document, null).queryFn({pageParam: null,});expect(mocks.timeline).toHaveBeenCalledTimes(1);- expect(mocks.timeline).toHaveBeenCalledWith(parent, {+ expect(mocks.timeline).toHaveBeenCalledWith(document, {cursor: { created_at: '2026-09-10T13:19:00.123457Z', id: 'msg-newer' },direction: 'newer',limit: 50,- include_deleted_threads: false,+ include_deleted_threads: true,});expect(ids(result)).toEqual(['msg-delta', 'msg-newer', 'msg-older']);expect(result.next_cursor).toEqual(cachedNext);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',- });+ expect(mocks.track).not.toHaveBeenCalled();});- it('breaks created_at ties with the larger root id', async () => {+ it('document catch-up breaks created_at ties with the larger root id', async () => {const time = '2026-09-10T13:19:00.000000Z';seedLatestCache([- createMessage('msg-a', time),- createMessage('msg-b', time),+ createMessage('msg-a', time, { parent: document }),+ createMessage('msg-b', time, { parent: document }),]);mocks.timeline.mockResolvedValueOnce({entries: [],@@ -306,18 +346,22 @@ describe('messageTimelineQueryOptions', () => {previous_cursor: null,});- await messageTimelineQueryOptions(parent, null).queryFn({+ await messageTimelineQueryOptions(document, null).queryFn({pageParam: null,});expect(mocks.timeline).toHaveBeenCalledWith(- parent,+ document,expect.objectContaining({ cursor: { created_at: time, id: 'msg-b' } }));});- it('delta overflow falls back to the full timeline', async () => {- seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00.123456Z')]);+ it('document delta overflow falls back to the full timeline', async () => {+ seedLatestCache([+ createMessage('msg-1', '2026-09-10T13:19:00.123456Z', {+ parent: document,+ }),+ ]);mocks.timeline.mockResolvedValueOnce({entries: entries(Array.from({ length: 50 }, (_, i) =>@@ -330,18 +374,16 @@ describe('messageTimelineQueryOptions', () => {const page = fullPage();mocks.timeline.mockResolvedValueOnce(page);- const result = await messageTimelineQueryOptions(parent, null).queryFn({+ const result = await messageTimelineQueryOptions(document, null).queryFn({pageParam: null,});- expect(mocks.timeline).toHaveBeenLastCalledWith(parent, fullSelection);- expect(ids(result)).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',+ expect(mocks.timeline).toHaveBeenLastCalledWith(document, {+ ...fullSelection,+ include_deleted_threads: true,});+ expect(ids(result)).toEqual(['full-1']);+ expect(mocks.track).not.toHaveBeenCalled();});it('cache away from latest uses the full timeline', async () => {@@ -401,37 +443,36 @@ describe('messageTimelineQueryOptions', () => {});});- it('catch-up failure falls back except on auth errors', async () => {- seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00.123456Z')]);+ it('document catch-up failure falls back except on auth errors', async () => {+ seedLatestCache([+ createMessage('msg-1', '2026-09-10T13:19:00.123456Z', {+ parent: document,+ }),+ ]);mocks.timeline.mockRejectedValueOnce(resultError('INTERNAL'));mocks.timeline.mockResolvedValueOnce(fullPage());- const result = await messageTimelineQueryOptions(parent, null).queryFn({+ const result = await messageTimelineQueryOptions(document, null).queryFn({pageParam: null,});expect(ids(result)).toEqual(['full-1']);expect(mocks.timeline).toHaveBeenCalledTimes(2);- expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {- channelId: 'channel-1',- path: 'full',- reason: 'catch_up_error',- after: '2026-09-10T13:19:00.123456Z',- });+ expect(mocks.track).not.toHaveBeenCalled();mocks.timeline.mockClear();mocks.track.mockClear();mocks.timeline.mockRejectedValueOnce(resultError('UNAUTHORIZED'));await expect(- messageTimelineQueryOptions(parent, null).queryFn({+ messageTimelineQueryOptions(document, null).queryFn({pageParam: null,})).rejects.toBeInstanceOf(ThrownResultError);expect(mocks.timeline).toHaveBeenCalledTimes(1);});- it('list ahead sets the reason', async () => {+ it('revalidates channels even when their list advertises a newer root', async () => {seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00.123456Z')]);testQueryClient.setQueryData(channelKeys.listChannels.queryKey, [{@@ -458,14 +499,15 @@ describe('messageTimelineQueryOptions', () => {expect(mocks.track).toHaveBeenCalledWith('channel_messages_load', {channelId: 'channel-1',- path: 'catch_up',- reason: 'list_ahead',- after: '2026-09-10T13:19:00.123456Z',+ path: 'full',+ reason: 'revalidate',});});- 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');+ it('document catch-up retains a root posted while its request was in flight', async () => {+ const cached = createMessage('msg-1', '2026-09-10T13:19:00.123456Z', {+ parent: document,+ });seedLatestCache([cached]);let releaseCatchUp!: () => void;const holdCatchUp = new Promise<void>((resolve) => {@@ -476,18 +518,20 @@ describe('messageTimelineQueryOptions', () => {return {entries: entries([createMessage('msg-delta', '2026-09-10T13:20:00.000000Z'),+ cached,]),next_cursor: null,previous_cursor: null,};});- const pending = messageTimelineQueryOptions(parent, null).queryFn({+ const pending = messageTimelineQueryOptions(document, null).queryFn({pageParam: null,});await Promise.resolve();seedLatestCache([createMessage('msg-live', '2026-09-10T13:21:00.000000Z', {+ parent: document,content: 'from websocket',}),cached,@@ -499,6 +543,77 @@ describe('messageTimelineQueryOptions', () => {expect(timelineMessages(result)[0]?.content).toBe('from websocket');});+ it('revalidates every loaded channel page using the refreshed pagination cursor', async () => {+ const newest = createMessage('newest', '2026-09-10T14:00:00Z');+ const oldest = createMessage('oldest', '2026-09-10T12:00:00Z');+ const deleted = createMessage('deleted', '2026-09-10T11:00:00Z');+ const next = cursor(newest.id, newest.created_at);+ const options = messageTimelineQueryOptions(parent, null);+ testQueryClient.setQueryData<MessageTimelineData>(options.queryKey, {+ pages: [+ { ...fullPage([newest]), next_cursor: next },+ fullPage([oldest, deleted]),+ ],+ pageParams: [null, { next_cursor: next, previous_cursor: null }],+ });+ const observer = new InfiniteQueryObserver(testQueryClient, options);+ const refreshedNext = cursor('page-boundary', '2026-09-10T13:00:00Z');+ mocks.timeline+ .mockResolvedValueOnce({+ ...fullPage([newest]),+ next_cursor: refreshedNext,+ })+ .mockResolvedValueOnce(+ fullPage([{ ...oldest, content: 'Edited while disconnected' }])+ );++ await testQueryClient.invalidateQueries({+ queryKey: options.queryKey,+ refetchType: 'all',+ });++ expect(mocks.timeline).toHaveBeenCalledTimes(2);+ expect(mocks.timeline).toHaveBeenNthCalledWith(1, parent, fullSelection);+ expect(mocks.timeline).toHaveBeenNthCalledWith(2, parent, {+ ...fullSelection,+ limit: 100,+ cursor: refreshedNext,+ });+ const data = testQueryClient.getQueryData<MessageTimelineData>(+ options.queryKey+ );+ expect(+ data?.pages.flatMap(timelineMessages).map((item) => item.content)+ ).toEqual([newest.content, 'Edited while disconnected']);+ observer.destroy();+ });++ it.each(['INTERNAL', 'UNAUTHORIZED', 'FORBIDDEN'])(+ 'keeps cached channel messages after a failed revalidation: %s',+ async (code) => {+ const root = createMessage('root', '2026-09-10T13:19:00Z');+ seedLatestCache([root]);+ const options = messageTimelineQueryOptions(parent, null);+ const observer = new InfiniteQueryObserver(testQueryClient, {+ ...options,+ retryDelay: 0,+ });+ mocks.timeline.mockRejectedValue(resultError(code));++ await testQueryClient.refetchQueries({ queryKey: options.queryKey });++ expect(+ testQueryClient.getQueryData<MessageTimelineData>(options.queryKey)+ ?.pages[0].entries+ ).toEqual(entries([root]));+ expect(+ testQueryClient.getQueryState(options.queryKey)?.error+ ).toBeInstanceOf(ThrownResultError);+ expect(mocks.timeline).toHaveBeenCalledTimes(code === 'INTERNAL' ? 2 : 1);+ observer.destroy();+ }+ );+it('later pages keep using the full timeline without an event', async () => {mocks.timeline.mockResolvedValueOnce(fullPage());const older = cursor('page-2', '2026-09-10T12:00:00Z');@@ -619,11 +734,13 @@ describe('channel activity entries', () => {};}- it('catch-up merges activity newer than the newest cached root', async () => {- seedLatestCache([createMessage('msg-1', '2026-09-10T13:19:00Z')]);+ it('channel revalidation includes activity and refreshed roots', async () => {+ const cached = createMessage('msg-1', '2026-09-10T13:19:00Z');+ seedLatestCache([cached]);mocks.timeline.mockResolvedValueOnce({entries: [{ type: 'activity', activity: activity('a', '2026-09-10T13:20:00Z') },+ { type: 'message', message: cached },],next_cursor: null,previous_cursor: null,diff --git a/apps/web/src/lib/queries/messages/timeline.ts b/apps/web/src/lib/queries/messages/timeline.tsindex 746f044c85..6d79e0a200 100644--- a/apps/web/src/lib/queries/messages/timeline.ts+++ b/apps/web/src/lib/queries/messages/timeline.ts@@ -1,7 +1,6 @@import { analytics } from '@app/lib/analytics';import { compareTimelinePositions } from '@core/util/message-timeline';import { ThrownResultError, thrownResultErrorHasCode } from '@core/util/result';-import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';import type {Message as EntityMessage,MessageListItem,@@ -22,7 +21,6 @@ import {} from '@tanstack/solid-query';import { type Accessor, createEffect, on } from 'solid-js';import { createStore, reconcile } from 'solid-js/store';-import { channelKeys } from '../channel/keys';import { queryClient } from '../client';import { messageKeys } from './keys';import {@@ -108,13 +106,10 @@ export function fetchResolvedChannelMessage(}export type MessageTimelineLoadReason =- | 'watermark'- | 'list_ahead'| 'no_cache'| 'cache_not_at_latest'| 'load_around'- | 'delta_overflow'- | 'catch_up_error';+ | 'revalidate';export type MessageTimelineWatermark =| { kind: 'no_cache' }@@ -123,7 +118,6 @@ export type MessageTimelineWatermark =kind: 'ready';after: MessageCursor;firstPage: MessageTimelinePage;- listAhead: boolean;};function newestRoot(items: MessageListItem[]): MessageListItem | null {@@ -143,8 +137,8 @@ function newestRoot(items: MessageListItem[]): MessageListItem | null {}/**- * Describes what a reconnecting timeline can reuse. A cache sitting at the- * bottom of the conversation only needs the roots newer than its newest one.+ * Describes the cached latest page. Channels revalidate it; other parents may+ * use its newest root as a catch-up cursor.*/export function readMessageTimelineWatermark(parent: MessageParent@@ -164,20 +158,10 @@ export function readMessageTimelineWatermark(if (!newest) {return { kind: 'no_cache' };}- const cachedIds = new Set(messages.map((item) => item.id));- const list =- parent.type === 'channel'- ? queryClient.getQueryData<ApiChannelWithLatest[]>(- channelKeys.listChannels.queryKey- )- : undefined;- const latestId = list?.find((channel) => channel.id === parent.id)- ?.latest_non_thread_message?.message_id;return {kind: 'ready',after: { created_at: newest.created_at, id: newest.id },firstPage,- listAhead: latestId != null && !cachedIds.has(latestId),};}@@ -195,9 +179,8 @@ export function mergeCatchUpPage(function trackMessageTimelineLoad(parent: MessageParent,payload: {- path: 'catch_up' | 'full';+ path: 'full';reason: MessageTimelineLoadReason;- after?: string;}) {if (parent.type !== 'channel') return;@@ -232,9 +215,13 @@ export function messageTimelineQueryOptions(queryKey: messageKeys.messages(parent, loadAroundMessageId).queryKey,queryFn: async ({pageParam,+ signal,}: {pageParam: MessageTimelinePageParam | null;+ signal?: AbortSignal;}) => {+ // Observe cancellation so a restarted refetch stops paging its old result.+ signal?.throwIfAborted();if (pageParam) {return fetchMessageTimelinePage(parent, pageParam, null);}@@ -264,6 +251,16 @@ export function messageTimelineQueryOptions(});return page;}+ if (parent.type === 'channel') {+ // Replies, reactions, edits and deletions do not advance a root's+ // created-at cursor. Revalidate its preview even when no root is new.+ const page = await fetchMessageTimelinePage(parent, null, null);+ trackMessageTimelineLoad(parent, {+ path: 'full',+ reason: 'revalidate',+ });+ return page;+ }try {const delta = normalizeMessageTimelinePageSenders(await entityMessagesClient.timeline(parent, {@@ -275,11 +272,6 @@ export function messageTimelineQueryOptions();if (delta.previous_cursor) {const page = await fetchMessageTimelinePage(parent, null, null);- trackMessageTimelineLoad(parent, {- path: 'full',- reason: 'delta_overflow',- after: watermark.after.created_at,- });return page;}const liveFirstPage = queryClient.getQueryData<MessageTimelineData>(@@ -289,11 +281,6 @@ export function messageTimelineQueryOptions(delta,liveFirstPage ?? watermark.firstPage);- trackMessageTimelineLoad(parent, {- path: 'catch_up',- reason: watermark.listAhead ? 'list_ahead' : 'watermark',- after: watermark.after.created_at,- });return merged;} catch (error) {if (@@ -303,11 +290,6 @@ export function messageTimelineQueryOptions(throw error;}const page = await fetchMessageTimelinePage(parent, null, null);- trackMessageTimelineLoad(parent, {- path: 'full',- reason: 'catch_up_error',- after: watermark.after.created_at,- });return page;}},diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 5a577d9983..74c8a2736b 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -619,14 +619,32 @@ reaction, and typing routes no longer exist. Live updates arrive as oneframes are no longer sent. Documents share the same client, cache, andcomponents (see documents.md).-Reopening a channel already loaded this session requests-`GET /dss/messages/channel/<id>?selection=<cursor of the newest cached root, direction newer, 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 load-the latest page with the default selection. 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`).+Reopening a cached channel, reconnecting its live subscription, or returning+from an absence past the presence window revalidates its timeline with+`GET /dss/messages/channel/<id>/timeline?selection=<default latest-page selection>`.+This replaces stale roots and their reply previews, reactions, and edits, and+removes deleted roots even when no newer top-level message exists. Loaded older+pages are also refetched using the refreshed cursors. A committed live change+restarts any in-flight channel timeline refresh, including when older pages are+still loading, so its result cannot overwrite that change. Idle channels still+apply live events without fetching; cached content stays visible if a refresh+fails. Message links still load around the targeted message.+The `channel_messages_load` event records `path: full` and `reason`+(`revalidate`, `no_cache`, `cache_not_at_latest`, or `load_around`).+Actual in-flight restarts emit a `channel.timeline_restart` span, searchable by+`channel.id`. `query.count` records the number of restarted queries;+`query.fetch_more_directions` and `query.outcomes` are arrays in the same query+order (`refetch`/`forward`/`backward` and `fulfilled`/`rejected`). The span also+records fulfilled/rejected counts and is marked as an error if any restart fails.+Idle channels emit no restart span. Request error text and message content are+not included.++To verify recovery, open a root with no replies, disconnect that client's live+updates, then add replies and reactions, edit another root, and delete a root+from a second client without posting a new top-level message. Reconnect the first+client: the collapsed preview, reply count, reactions, text, and deleted row must+all catch up without a reload. Repeat with older pages loaded and after a mobile+background/foreground cycle.## Message reaction notifications