From f2c3930da64759b77677120b3d986965525c6fe4 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 19 Aug 2026 16:55:02 +0200 Subject: [PATCH 1/3] fix: back out of space previews opened by address An unjoined space renders the preview on every route of its section, so the back button's section list path looped onto the same screen. useBackRoute now escapes to home when the space is not joined (replace, so the dead end does not linger in history). The preview back button also renders on desktop and tablet sizes, and Tauri loads that start on a deep-linked page get a home entry placed underneath it so webview back / iOS edge-swipe has somewhere to land. --- .../fix-space-preview-back-navigation.md | 5 + src/app/components/BackRouteHandler.test.tsx | 154 ++++++++++++++++++ src/app/components/BackRouteHandler.tsx | 27 ++- .../JoinBeforeNavigate.tsx | 14 +- src/app/pages/Router.tsx | 5 + src/app/pages/pathUtils.ts | 3 + src/app/pages/tauriHistoryRoot.test.ts | 97 +++++++++++ src/app/pages/tauriHistoryRoot.ts | 44 +++++ 8 files changed, 337 insertions(+), 12 deletions(-) create mode 100644 .changeset/fix-space-preview-back-navigation.md create mode 100644 src/app/components/BackRouteHandler.test.tsx create mode 100644 src/app/pages/tauriHistoryRoot.test.ts create mode 100644 src/app/pages/tauriHistoryRoot.ts diff --git a/.changeset/fix-space-preview-back-navigation.md b/.changeset/fix-space-preview-back-navigation.md new file mode 100644 index 000000000..2b915bf3d --- /dev/null +++ b/.changeset/fix-space-preview-back-navigation.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix being unable to back out of a space preview opened by address, and give Tauri webview back/swipe somewhere to land on deep-linked launches. diff --git a/src/app/components/BackRouteHandler.test.tsx b/src/app/components/BackRouteHandler.test.tsx new file mode 100644 index 000000000..d24d563cf --- /dev/null +++ b/src/app/components/BackRouteHandler.test.tsx @@ -0,0 +1,154 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { MemoryRouter, useLocation } from 'react-router-dom'; +import { Provider as JotaiProvider, createStore } from 'jotai'; +import type { MatrixClient, Room } from '$types/matrix-sdk'; +import { MatrixClientProvider } from '$hooks/useMatrixClient'; +import { allRoomsAtom } from '$state/room-list/roomList'; +import { useBackRoute } from './BackRouteHandler'; + +vi.mock('$utils/androidBack', () => ({ + useAndroidBackHandler: vi.fn<() => void>(), +})); + +function LocationProbe() { + const location = useLocation(); + return {location.pathname}; +} + +function BackButton() { + const goBack = useBackRoute(); + return ( + + ); +} + +const makeRoom = (roomId: string, canonicalAlias?: string) => + ({ + roomId, + getCanonicalAlias: () => canonicalAlias, + getLiveTimeline: () => ({ getState: () => undefined }), + }) as unknown as Room; + +const makeClient = (rooms: Room[] = []) => + ({ + getRooms: () => rooms, + }) as unknown as MatrixClient; + +function renderBackRoute(options: { + initialPath: string; + joinedRoomIds?: string[]; + clientRooms?: Room[]; +}) { + const store = createStore(); + store.set(allRoomsAtom, { type: 'INITIALIZE', rooms: options.joinedRoomIds ?? [] }); + + render( + + + + + + + + + ); + + return { + goBack: () => fireEvent.click(screen.getByRole('button', { name: 'go back' })), + pathname: () => screen.getByTestId('pathname').textContent, + }; +} + +describe('useBackRoute', () => { + it('backs out of a room to its section list', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/home/!room:example.org/', + joinedRoomIds: ['!room:example.org'], + }); + + goBack(); + + expect(pathname()).toBe('/home/'); + }); + + it('backs out of a space room to the space lobby when the space is joined', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/!space:example.org/!room:example.org/', + joinedRoomIds: ['!space:example.org', '!room:example.org'], + }); + + goBack(); + + expect(pathname()).toBe('/!space%3Aexample.org'); + }); + + it('backs out of a joined space lobby to the space root', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/!space:example.org/lobby/', + joinedRoomIds: ['!space:example.org'], + }); + + goBack(); + + expect(pathname()).toBe('/!space%3Aexample.org'); + }); + + it('backs out of a space preview to home instead of looping onto the preview', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/!space:example.org/lobby/', + joinedRoomIds: ['!other:example.org'], + }); + + goBack(); + + expect(pathname()).toBe('/home/'); + }); + + it('backs out of a space preview reached by bare address to home', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/!space:example.org/', + joinedRoomIds: ['!other:example.org'], + }); + + goBack(); + + expect(pathname()).toBe('/home/'); + }); + + it('backs out of a space preview reached by alias to home', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/%23space%3Aexample.org/lobby/', + joinedRoomIds: ['!other:example.org'], + }); + + goBack(); + + expect(pathname()).toBe('/home/'); + }); + + it('treats a space as joined when its canonical alias resolves to a joined room', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/%23space%3Aexample.org/lobby/', + joinedRoomIds: ['!space:example.org'], + clientRooms: [makeRoom('!space:example.org', '#space:example.org')], + }); + + goBack(); + + expect(pathname()).toBe('/%23space%3Aexample.org'); + }); + + it('backs from an unjoined space room preview up to the space preview', () => { + const { goBack, pathname } = renderBackRoute({ + initialPath: '/!space:example.org/!room:example.org/', + joinedRoomIds: ['!other:example.org'], + }); + + goBack(); + + expect(pathname()).toBe('/!space%3Aexample.org'); + }); +}); diff --git a/src/app/components/BackRouteHandler.tsx b/src/app/components/BackRouteHandler.tsx index 82ebc138e..cd165d92e 100644 --- a/src/app/components/BackRouteHandler.tsx +++ b/src/app/components/BackRouteHandler.tsx @@ -1,8 +1,8 @@ import type { ReactNode } from 'react'; import { useCallback } from 'react'; -import { useSetAtom } from 'jotai'; +import { useAtomValue, useSetAtom } from 'jotai'; import { matchPath, useLocation, useNavigate } from 'react-router-dom'; -import { resolveSection } from '$pages/pathUtils'; +import { getHomePath, resolveSection } from '$pages/pathUtils'; import { DIRECT_ROOM_FORUM_PATH, DIRECT_ROOM_PATH, @@ -12,7 +12,9 @@ import { SPACE_ROOM_PATH, } from '$pages/paths'; import { lastVisitedRoomAtom } from '$state/room/lastRoom'; -import { isRoomAlias, isRoomId } from '$utils/matrix'; +import { allRoomsAtom } from '$state/room-list/roomList'; +import { useMatrixClient } from '$hooks/useMatrixClient'; +import { getCanonicalAliasRoomId, isRoomAlias, isRoomId } from '$utils/matrix'; import { useAndroidBackHandler } from '$utils/androidBack'; type BackRouteHandlerProps = { @@ -22,6 +24,8 @@ type BackRouteHandlerProps = { export function useBackRoute(): () => void { const navigate = useNavigate(); const location = useLocation(); + const mx = useMatrixClient(); + const allRooms = useAtomValue(allRoomsAtom); const setLastRoom = useSetAtom(lastVisitedRoomAtom); return useCallback(() => { @@ -42,12 +46,25 @@ export function useBackRoute(): () => void { const currentRoomIdOrAlias = roomMatch?.params.roomIdOrAlias; const decoded = currentRoomIdOrAlias && decodeURIComponent(currentRoomIdOrAlias); - if (section.getRoomPath && decoded && (isRoomId(decoded) || isRoomAlias(decoded))) { + const inRoomRoute = !!decoded && (isRoomId(decoded) || isRoomAlias(decoded)); + if (section.getRoomPath && inRoomRoute && decoded) { setLastRoom((prev) => ({ ...prev, [section.key]: decoded })); } + // An unjoined space renders the preview screen on every route of its section, + // so its own list path loops back onto the same screen: escape to home instead. + if (!inRoomRoute && section.spaceIdOrAlias) { + const spaceId = isRoomId(section.spaceIdOrAlias) + ? section.spaceIdOrAlias + : getCanonicalAliasRoomId(mx, section.spaceIdOrAlias); + if (!spaceId || !allRooms.includes(spaceId)) { + navigate(getHomePath(), { replace: true }); + return; + } + } + navigate(section.listPath); - }, [navigate, location, setLastRoom]); + }, [navigate, location, setLastRoom, mx, allRooms]); } export function BackRouteHandler({ children }: BackRouteHandlerProps) { diff --git a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx index 488a16aa1..b91265776 100644 --- a/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx +++ b/src/app/features/join-before-navigate/JoinBeforeNavigate.tsx @@ -9,7 +9,6 @@ import { RoomSummaryLoader } from '$components/RoomSummaryLoader'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { allRoomsAtom } from '$state/room-list/roomList'; -import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; import { BackRouteHandler } from '$components/BackRouteHandler'; type JoinBeforeNavigateProps = { roomIdOrAlias: string; eventId?: string; viaServers?: string[] }; @@ -21,7 +20,6 @@ export function JoinBeforeNavigate({ const mx = useMatrixClient(); const allRooms = useAtomValue(allRoomsAtom); const { navigateRoom, navigateSpace } = useRoomNavigate(); - const screenSize = useScreenSizeContext(); const handleView = (roomId: string, roomType?: string) => { if (mx.getRoom(roomId)?.isSpaceRoom() || roomType === RoomType.Space) { @@ -36,11 +34,13 @@ export function JoinBeforeNavigate({ - {screenSize === ScreenSize.Mobile && ( - - {(onBack) => {composerIcon(ArrowLeft)}} - - )} + + {(onBack) => ( + + {composerIcon(ArrowLeft)} + + )} + diff --git a/src/app/pages/Router.tsx b/src/app/pages/Router.tsx index b9212ad07..13244c9b6 100644 --- a/src/app/pages/Router.tsx +++ b/src/app/pages/Router.tsx @@ -107,6 +107,7 @@ const PublicRooms = lazy(() => ); import { setAfterLoginRedirectPath } from './afterLoginRedirectPath'; import { legacyAuthLoader } from './legacyAuthRedirect'; +import { ensureTauriHistoryRoot } from './tauriHistoryRoot'; import { WelcomePage } from './client/WelcomePage'; import { SidebarNav } from './client/SidebarNav'; import { MobileFriendlySidebarNav, MobileFriendlyBottomNav } from './MobileFriendly'; @@ -151,6 +152,10 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) const { hashRouter } = clientConfig; const mobile = screenSize === ScreenSize.Mobile; + // Before the router reads the initial location, give webview-level back + // navigation somewhere to land on a fresh deep-linked load. + ensureTauriHistoryRoot(hashRouter); + const routes = createRoutesFromElements( string) | null; + /** Decoded space id or alias, present only when the section is a space. */ + spaceIdOrAlias?: string; }; /** @@ -247,6 +249,7 @@ export const resolveSection = (pathname: string): SectionNav | null => { getRoomPath: isForum ? (roomIdOrAlias) => getSpaceForumPath(spaceId, roomIdOrAlias) : (roomIdOrAlias) => getSpaceRoomPath(spaceId, roomIdOrAlias), + spaceIdOrAlias: spaceId, }; } return null; diff --git a/src/app/pages/tauriHistoryRoot.test.ts b/src/app/pages/tauriHistoryRoot.test.ts new file mode 100644 index 000000000..fccbd07fc --- /dev/null +++ b/src/app/pages/tauriHistoryRoot.test.ts @@ -0,0 +1,97 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ensureTauriHistoryRoot } from './tauriHistoryRoot'; + +const mocks = vi.hoisted(() => ({ isTauri: true })); + +vi.mock('@tauri-apps/api/core', () => ({ + isTauri: () => mocks.isTauri, +})); +vi.mock('@tauri-apps/plugin-os', () => ({ + type: () => 'ios', +})); + +const DEEP_PATH = '/!space%3Aexample.org/lobby/'; + +/** Position the window, then spy so setup mutations are not counted. */ +const loadAt = (path: string, state: unknown = null) => { + window.history.replaceState(state, '', path); + const replaceSpy = vi.spyOn(window.history, 'replaceState'); + const pushSpy = vi.spyOn(window.history, 'pushState'); + vi.spyOn(window.history, 'length', 'get').mockReturnValue(1); + return { replaceSpy, pushSpy, href: window.location.href }; +}; + +afterEach(() => { + mocks.isTauri = true; + vi.restoreAllMocks(); +}); + +describe('ensureTauriHistoryRoot', () => { + it('places home under a fresh deep-linked entry', () => { + const { replaceSpy, pushSpy, href } = loadAt(DEEP_PATH); + + ensureTauriHistoryRoot(); + + expect(replaceSpy).toHaveBeenCalledWith({}, '', '/home/'); + expect(pushSpy).toHaveBeenCalledWith({ idx: 1 }, '', href); + }); + + it('keeps the router state of the original entry', () => { + const state = { idx: 0, usr: { from: 'test' } }; + const { replaceSpy, pushSpy, href } = loadAt(DEEP_PATH, state); + + ensureTauriHistoryRoot(); + + expect(replaceSpy).toHaveBeenCalledWith(state, '', '/home/'); + expect(pushSpy).toHaveBeenCalledWith({ ...state, idx: 1 }, '', href); + }); + + it('builds a hash-router home href when the hash router is enabled', () => { + const { replaceSpy } = loadAt(`/#${DEEP_PATH}`); + + ensureTauriHistoryRoot({ enabled: true, basename: '/' }); + + expect(replaceSpy).toHaveBeenCalledWith({}, '', '#/home/'); + }); + + it('does nothing when the load already has history', () => { + const { replaceSpy, pushSpy } = loadAt(DEEP_PATH); + vi.spyOn(window.history, 'length', 'get').mockReturnValue(2); + + ensureTauriHistoryRoot(); + + expect(replaceSpy).not.toHaveBeenCalled(); + expect(pushSpy).not.toHaveBeenCalled(); + }); + + it('does nothing when the router state says we are past the first entry', () => { + const { replaceSpy, pushSpy } = loadAt(DEEP_PATH, { idx: 3 }); + + ensureTauriHistoryRoot(); + + expect(replaceSpy).not.toHaveBeenCalled(); + expect(pushSpy).not.toHaveBeenCalled(); + }); + + it('does nothing outside tauri', () => { + mocks.isTauri = false; + const { replaceSpy, pushSpy } = loadAt(DEEP_PATH); + + ensureTauriHistoryRoot(); + + expect(replaceSpy).not.toHaveBeenCalled(); + expect(pushSpy).not.toHaveBeenCalled(); + }); + + it.each(['/', '/home/', '/login', '/login?server=matrix.org', '/register', '/reset-password'])( + 'does nothing on root, home and auth paths (%s)', + (path) => { + const { replaceSpy, pushSpy } = loadAt(path); + + ensureTauriHistoryRoot(); + + expect(replaceSpy).not.toHaveBeenCalled(); + expect(pushSpy).not.toHaveBeenCalled(); + } + ); +}); diff --git a/src/app/pages/tauriHistoryRoot.ts b/src/app/pages/tauriHistoryRoot.ts new file mode 100644 index 000000000..c8c1bd39a --- /dev/null +++ b/src/app/pages/tauriHistoryRoot.ts @@ -0,0 +1,44 @@ +import { isTauri } from '@tauri-apps/api/core'; +import type { HashRouterConfig } from '$hooks/useClientConfig'; +import { createLogger } from '$utils/debug'; +import { + HOME_PATH, + LOGIN_PATH, + REGISTER_PATH, + RESET_PASSWORD_PATH, + ROOT_PATH, + SSO_CALLBACK_PATH, +} from './paths'; +import { getAppPathFromHref, getOriginBaseUrl } from './pathUtils'; + +const log = createLogger('tauriHistoryRoot'); + +export function ensureTauriHistoryRoot(hashRouter?: HashRouterConfig): void { + if (!isTauri()) return; + if (window.history.length > 1) return; + const state = (window.history.state ?? {}) as { idx?: number }; + if (state.idx) return; + + const appPath = getAppPathFromHref(getOriginBaseUrl(hashRouter), window.location.href); + const pathname = appPath.split('?')[0] ?? ''; + if ( + !pathname || + pathname === ROOT_PATH || + pathname === HOME_PATH || + pathname.startsWith(LOGIN_PATH) || + pathname.startsWith(REGISTER_PATH) || + pathname.startsWith(RESET_PASSWORD_PATH) || + pathname.startsWith(SSO_CALLBACK_PATH) + ) { + return; + } + + const homeHref = hashRouter?.enabled + ? `#${(hashRouter.basename ?? '/').replace(/\/$/, '')}${HOME_PATH}` + : `${import.meta.env.BASE_URL}${HOME_PATH.slice(1)}`; + + const currentHref = window.location.href; + window.history.replaceState(state, '', homeHref); + window.history.pushState({ ...state, idx: 1 }, '', currentHref); + log.log('Placed home under the initial deep-link entry', currentHref); +} From dfbf9828d89ec6bf8fab23900ad99667f0a2a0f8 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 19 Aug 2026 17:02:44 +0200 Subject: [PATCH 2/3] fix(crypto): reload instead of retrying in place after a store mismatch --- .changeset/fix-crypto-mismatch-reload.md | 5 +++++ src/client/initMatrix.ts | 18 +++++++----------- 2 files changed, 12 insertions(+), 11 deletions(-) create mode 100644 .changeset/fix-crypto-mismatch-reload.md diff --git a/.changeset/fix-crypto-mismatch-reload.md b/.changeset/fix-crypto-mismatch-reload.md new file mode 100644 index 000000000..c04451348 --- /dev/null +++ b/.changeset/fix-crypto-mismatch-reload.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Reload instead of retrying in place after a crypto store mismatch, which corrupted the crypto engine. diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 8cb97147f..b2aa1bf74 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -361,7 +361,7 @@ export const initClient = async (session: Session): Promise => { const initStartTime = performance.now(); let initOutcome = 'success'; try { - let result = await initializeClient(session, storeName.rustCryptoPrefix); + const result = await initializeClient(session, storeName.rustCryptoPrefix); if (!result.ok) { if (!isMismatch(result.error)) { debugLog.error('sync', 'Failed to initialize client', { @@ -371,20 +371,16 @@ export const initClient = async (session: Session): Promise => { throw result.error; } - log.warn(`initClient: mismatch during ${result.phase} — wiping and retrying:`, result.error); - debugLog.warn('sync', 'Client initialization mismatch - wiping stores and retrying', { + log.warn(`initClient: mismatch during ${result.phase} — wiping and reloading:`, result.error); + debugLog.warn('sync', 'Client initialization mismatch - wiping stores and reloading', { phase: result.phase, error: result.error, }); await wipeAllStores(); - result = await initializeClient(session, storeName.rustCryptoPrefix); - if (!result.ok) { - debugLog.error('sync', 'Failed to initialize client after store reset', { - phase: result.phase, - error: result.error, - }); - throw result.error; - } + // Reload instead of re-initing in place: the failed init leaks its WASM + // store handle, which blocks the wipe and corrupts the shared crypto heap. + window.location.reload(); + throw result.error; } result.mx.setMaxListeners(50); From d6051e4af06974698b69a2ef48e0d26fc00c3b69 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Wed, 19 Aug 2026 17:24:13 +0200 Subject: [PATCH 3/3] fix(sliding-sync): merge local echoes with unlinked remote echoes --- src/client/slidingSync.test.ts | 1 + src/client/slidingSync.ts | 77 ++++++ .../slidingSyncTimelineReconciliation.test.ts | 222 +++++++++++++++++- 3 files changed, 297 insertions(+), 3 deletions(-) diff --git a/src/client/slidingSync.test.ts b/src/client/slidingSync.test.ts index 48f280f24..bb9dd9da7 100644 --- a/src/client/slidingSync.test.ts +++ b/src/client/slidingSync.test.ts @@ -459,6 +459,7 @@ describe('SlidingSyncManager initial request', () => { const room = { getMember: vi.fn<() => undefined>(), currentState: { setStateEvents: vi.fn<() => void>() }, + getLiveTimeline: () => ({ getEvents: () => [] }), }; const manager = makeManager( makeMockMx({ diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index a18389f40..57c6c0858 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -475,6 +475,80 @@ export const prepareSlidingSyncTimelines = ( }; }; +const LOCAL_ECHO_MATCH_MAX_CLOCK_SKEW_MS = 60_000; + +const canonicalJson = (value: unknown): string => { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; + if (value !== null && typeof value === 'object') { + const entries = Object.keys(value as Record) + .toSorted() + .map( + (key) => `${JSON.stringify(key)}:${canonicalJson((value as Record)[key])}` + ); + return `{${entries.join(',')}}`; + } + return JSON.stringify(value); +}; + +export const reconcileLocalEchoes = (room: Room | null | undefined): void => { + if (!room) return; + const liveEvents = room.getLiveTimeline().getEvents(); + const pendingEchoes = liveEvents.filter( + (event) => + event.status !== null && + event.status !== EventStatus.CANCELLED && + event.status !== EventStatus.SENT + ); + if (pendingEchoes.length === 0) return; + + const claimedEventIds = new Set(); + const isMergeCandidate = (candidate: MatrixEvent, echo: MatrixEvent): boolean => { + const candidateId = candidate.getId(); + if (!candidateId || candidate === echo || claimedEventIds.has(candidateId)) return false; + if (candidate.status !== null) return false; + if (candidate.getSender() !== echo.getSender()) return false; + return !candidate.isRedacted(); + }; + + for (const echo of pendingEchoes) { + const txnId = echo.getTxnId(); + let match = txnId + ? liveEvents.find( + (candidate) => + isMergeCandidate(candidate, echo) && candidate.getUnsigned()?.transaction_id === txnId + ) + : undefined; + if (!match) { + const wireType = echo.getWireType(); + const wireContent = canonicalJson(echo.getWireContent()); + match = liveEvents.find((candidate) => { + if (!isMergeCandidate(candidate, echo)) return false; + if (candidate.getWireType() !== wireType) return false; + const candidateTxn = candidate.getUnsigned()?.transaction_id; + if (typeof candidateTxn === 'string' && candidateTxn !== txnId) return false; + if (candidate.getTs() < echo.getTs() - LOCAL_ECHO_MATCH_MAX_CLOCK_SKEW_MS) return false; + return canonicalJson(candidate.getWireContent()) === wireContent; + }); + } + const matchId = match?.getId(); + if (!match || !matchId) continue; + claimedEventIds.add(matchId); + + const unsigned = match.getUnsigned(); + if (txnId && typeof unsigned.transaction_id !== 'string') { + unsigned.transaction_id = txnId; + match.setUnsigned(unsigned); + } + room.removeEvent(matchId); + room.handleRemoteEcho(match, echo); + debugLog.info('sync', 'Reconciled unlinked local echo', { + roomId: room.roomId, + localEchoId: echo.getId(), + remoteEventId: matchId, + }); + } +}; + export class SlidingSyncManager { private disposed = false; @@ -717,6 +791,9 @@ export class SlidingSyncManager { this.timelineResetCompletions.get(resp)?.(); this.timelineResetCompletions.delete(resp); + for (const roomId of Object.keys(resp.rooms ?? {})) { + reconcileLocalEchoes(this.mx.getRoom(roomId)); + } this.recordServerMembershipRooms(resp); this.reassertOptimisticJoins(); diff --git a/src/client/slidingSyncTimelineReconciliation.test.ts b/src/client/slidingSyncTimelineReconciliation.test.ts index 7f9907eda..7d1ece9c2 100644 --- a/src/client/slidingSyncTimelineReconciliation.test.ts +++ b/src/client/slidingSyncTimelineReconciliation.test.ts @@ -8,8 +8,14 @@ import { EventTimeline, MatrixEvent, RoomEvent, + SlidingSyncEvent, + SlidingSyncState, } from '$types/matrix-sdk'; -import { prepareSlidingSyncTimelines } from './slidingSync'; +import { + prepareSlidingSyncTimelines, + reconcileLocalEchoes, + SlidingSyncManager, +} from './slidingSync'; const userId = '@me:example.com'; const roomId = '!dm:example.com'; @@ -51,12 +57,12 @@ const makeSdk = (): { mx: MatrixClient; sdk: SlidingSyncSdk; deliver: RoomDataHa return { mx, sdk, deliver: roomDataHandler }; }; -const message = (id: string, ts: number) => ({ +const message = (id: string, ts: number, body: string = id) => ({ type: 'm.room.message', event_id: id, sender: '@them:example.com', origin_server_ts: ts, - content: { msgtype: 'm.text', body: id }, + content: { msgtype: 'm.text', body }, }); const initialRoomData = (newest: ReturnType): MSC3575RoomData => @@ -106,6 +112,9 @@ const linkedTimelineIds = (timeline: EventTimeline): string[] => { const history = [message('$e1', 100), message('$e2', 200), message('$e3', 300)]; const newest = history[history.length - 1]!; +const ECHO_BODY = 'duplicate me'; +const ECHO_TS = 1_700_000_000_000; + describe('timeline reconciliation in matrix-js-sdk', () => { it('appends the expanded history out of order when only Synapse flags it', async () => { const { mx, deliver } = makeSdk(); @@ -710,3 +719,210 @@ describe('a window from a room we just subscribed to', () => { expect(liveTimeline.getPaginationToken(EventTimeline.BACKWARDS)).toBe('t1-9'); }); }); + +describe('reconcileLocalEchoes', () => { + const addPendingEcho = ( + mx: MatrixClient, + txnId: string, + body = ECHO_BODY, + ts = ECHO_TS + ): MatrixEvent => { + const room = mx.getRoom(roomId)!; + const echo = new MatrixEvent({ + type: 'm.room.message', + event_id: `~${roomId}:${txnId}`, + sender: userId, + room_id: roomId, + origin_server_ts: ts, + content: { msgtype: 'm.text', body }, + }); + echo.setTxnId(txnId); + echo.setStatus(EventStatus.SENDING); + room.addPendingEvent(echo, txnId); + return echo; + }; + + const confirmedCopy = (id: string, body = ECHO_BODY, ts = ECHO_TS): Record => ({ + ...message(id, ts, body), + sender: userId, + }); + + it('merges a pending echo with an unlinked remote copy after a gapped reset', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, initialRoomData(newest)); + const room = mx.getRoom(roomId)!; + const echo = addPendingEcho(mx, 'm1700000000000000001'); + room.updatePendingEvent(echo, EventStatus.NOT_SENT); + room.updatePendingEvent(echo, EventStatus.SENDING); + + const resp = { + pos: 'p3', + rooms: { + [roomId]: { + required_state: [], + timeline: [confirmedCopy('$mine')], + limited: true, + num_live: 1, + prev_batch: 'gap-token', + }, + }, + } as unknown as MSC3575SlidingSyncResponse; + const completeTimelineReset = prepareSlidingSyncTimelines(resp, mx); + await deliver(roomId, resp.rooms[roomId]!); + completeTimelineReset?.(); + + expect(timelineIds(mx)).toContain('$mine'); + expect(timelineIds(mx)).toContain(echo.getId()); + + reconcileLocalEchoes(room); + + expect(timelineIds(mx).filter((id) => id === '$mine')).toHaveLength(1); + expect(timelineIds(mx)).not.toContain('~' + roomId + ':m1700000000000000001'); + expect(echo.getId()).toBe('$mine'); + expect(echo.status).toBeNull(); + }); + + it('merges an echo delivered incrementally alongside the pending local echo', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, initialRoomData(newest)); + const room = mx.getRoom(roomId)!; + const echo = addPendingEcho(mx, 'm1700000000000000002'); + + await deliver(roomId, { + required_state: [], + timeline: [confirmedCopy('$mine')], + num_live: 1, + } as unknown as MSC3575RoomData); + + expect(timelineIds(mx)).toContain('$mine'); + expect(timelineIds(mx)).toContain(echo.getId()); + + reconcileLocalEchoes(room); + + expect(timelineIds(mx).filter((id) => id === '$mine')).toHaveLength(1); + expect(timelineIds(mx)).not.toContain('~' + roomId + ':m1700000000000000002'); + expect(echo.getId()).toBe('$mine'); + expect(echo.status).toBeNull(); + }); + + it('prefers the transaction id over a same-body decoy', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, initialRoomData(newest)); + const room = mx.getRoom(roomId)!; + const echo = addPendingEcho(mx, 'm1700000000000000003'); + + const mapEvent = mx.getEventMapper(); + room.addEventsToTimeline( + [ + mapEvent({ ...message('$decoy', ECHO_TS, ECHO_BODY), sender: userId } as never), + mapEvent({ + ...message('$mine', ECHO_TS, 'something else entirely'), + sender: userId, + unsigned: { transaction_id: 'm1700000000000000003' }, + } as never), + ], + true, + false, + room.getLiveTimeline() + ); + + reconcileLocalEchoes(room); + + expect(timelineIds(mx)).toContain('$mine'); + expect(timelineIds(mx)).toContain('$decoy'); + expect(echo.getId()).toBe('$mine'); + expect(echo.status).toBeNull(); + }); + + it('does not steal an older identical message for a pending echo', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, initialRoomData(newest)); + const room = mx.getRoom(roomId)!; + + await deliver(roomId, { + required_state: [], + timeline: [confirmedCopy('$old', ECHO_BODY, ECHO_TS - 120_000)], + num_live: 1, + } as unknown as MSC3575RoomData); + + const echo = addPendingEcho(mx, 'm1700000000000000004'); + reconcileLocalEchoes(room); + + expect(timelineIds(mx)).toContain('$old'); + expect(timelineIds(mx)).toContain(echo.getId()); + expect(echo.status).toBe(EventStatus.SENDING); + }); + + it('leaves a pending echo alone when no confirmation was delivered', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, initialRoomData(newest)); + const room = mx.getRoom(roomId)!; + const echo = addPendingEcho(mx, 'm1700000000000000005'); + + reconcileLocalEchoes(room); + + expect(timelineIds(mx)).toContain(echo.getId()); + expect(echo.status).toBe(EventStatus.SENDING); + }); + + it('does not merge an echo into an identical message from a different send', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, initialRoomData(newest)); + const room = mx.getRoom(roomId)!; + + await deliver(roomId, { + required_state: [], + timeline: [ + { + ...message('$earlier', ECHO_TS, ECHO_BODY), + sender: userId, + unsigned: { transaction_id: 'mOTHER' }, + }, + ], + num_live: 1, + } as unknown as MSC3575RoomData); + + const echo = addPendingEcho(mx, 'm1700000000000000006'); + reconcileLocalEchoes(room); + + expect(timelineIds(mx)).toContain('$earlier'); + expect(timelineIds(mx)).toContain(echo.getId()); + expect(echo.status).toBe(EventStatus.SENDING); + }); +}); + +describe('sync-complete reconciliation wiring', () => { + it('reconciles local echoes for every room in a completed response', async () => { + const { mx, deliver } = makeSdk(); + await deliver(roomId, initialRoomData(newest)); + const room = mx.getRoom(roomId)!; + const echo = new MatrixEvent({ + type: 'm.room.message', + event_id: `~${roomId}:m1700000000000000006`, + sender: userId, + room_id: roomId, + origin_server_ts: ECHO_TS, + content: { msgtype: 'm.text', body: 'wired' }, + }); + echo.setTxnId('m1700000000000000006'); + echo.setStatus(EventStatus.SENDING); + room.addPendingEvent(echo, 'm1700000000000000006'); + + await deliver(roomId, { + required_state: [], + timeline: [{ ...message('$mine', ECHO_TS, 'wired'), sender: userId }], + num_live: 1, + } as unknown as MSC3575RoomData); + expect(timelineIds(mx)).toContain('~' + roomId + ':m1700000000000000006'); + + const manager = new SlidingSyncManager(mx, 'https://sliding.example.com'); + manager.attach(); + const resp = { pos: 'p9', rooms: { [roomId]: {} } } as unknown as MSC3575SlidingSyncResponse; + manager.slidingSync.emit(SlidingSyncEvent.Lifecycle, SlidingSyncState.Complete, resp); + + expect(timelineIds(mx)).toContain('$mine'); + expect(timelineIds(mx)).not.toContain('~' + roomId + ':m1700000000000000006'); + expect(echo.getId()).toBe('$mine'); + manager.dispose(); + }); +});