fix: fix crypto, sliding sync echo and back button (#1868)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
Erwan Leboucher authored and GitHub committed 2026-08-19 18:15:06 +02:00
commit f2dad92990
13 files changed
+646 -26

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Reload instead of retrying in place after a crypto store mismatch, which corrupted the crypto engine.
@@ -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.
@@ -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 <output data-testid="pathname">{location.pathname}</output>;
}
function BackButton() {
const goBack = useBackRoute();
return (
<button type="button" onClick={goBack}>
go back
</button>
);
}
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(
<JotaiProvider store={store}>
<MatrixClientProvider value={makeClient(options.clientRooms ?? [])}>
<MemoryRouter initialEntries={[options.initialPath]}>
<LocationProbe />
<BackButton />
</MemoryRouter>
</MatrixClientProvider>
</JotaiProvider>
);
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');
});
});
+22 -5
View File
@@ -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) {
@@ -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({
<PageHeader balance>
<Box grow="Yes" gap="200">
<Box shrink="No">
{screenSize === ScreenSize.Mobile && (
<BackRouteHandler>
{(onBack) => <IconButton onClick={onBack}>{composerIcon(ArrowLeft)}</IconButton>}
</BackRouteHandler>
)}
<BackRouteHandler>
{(onBack) => (
<IconButton aria-label="Back" onClick={onBack}>
{composerIcon(ArrowLeft)}
</IconButton>
)}
</BackRouteHandler>
</Box>
<Box grow="Yes" justifyContent="Center" alignItems="Center" gap="200">
<Text size="H3" truncate>
+5
View File
@@ -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(
<Route
element={
+3
View File
@@ -206,6 +206,8 @@ export type SectionNav = {
listPath: string;
/** Builds the path to a room within this section, or null when the section has no rooms. */
getRoomPath: ((roomIdOrAlias: string) => 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;
+97
View File
@@ -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();
}
);
});
+44
View File
@@ -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);
}
+7 -11
View File
@@ -361,7 +361,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
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<MatrixClient> => {
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);
+1
View File
@@ -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({
+77
View File
@@ -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<string, unknown>)
.toSorted()
.map(
(key) => `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[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<string>();
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();
@@ -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<typeof message>): 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<string, unknown> => ({
...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();
});
});