mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 17:11:17 -08:00
fix(sliding-sync): drop stale invite state for joined rooms in sidebar cache (#1284)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description On homeservers that keep sending invite_state for a room the user has already joined (e.g. Continuwuity), accepting a local invite left the room "half-joined": after a restart it reappeared as a pending invite. The sidebar cache persisted the stale invite_state, and matrix-js-sdk treats invite_state as authoritative (it short-circuits to invite membership and ignores required_state), so hydration kept resurrecting the invite. Fixes #1283 #### 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: - [x] My code follows the style guidelines of this project - [x] I have performed a self-review of my own code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings ### AI disclosure: - [x] 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. --> code review and autocomplete
This commit is contained in:
5 files changed
+207
-21
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fixed accepted invites reappearing after restart on homeservers that keep sending invite state for joined rooms.
|
||||
@@ -805,6 +805,33 @@ describe('SlidingSyncManager local membership reconciliation', () => {
|
||||
expect(reconcileRooms).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-asserts join for a joined room hydrated from cache as invite', async () => {
|
||||
const updateMyMembership = vi.fn<(m: string) => void>();
|
||||
const room = {
|
||||
getMyMembership: vi.fn<() => string>().mockReturnValue(KnownMembership.Invite),
|
||||
updateMyMembership,
|
||||
};
|
||||
const getJoinedRooms = vi
|
||||
.fn<() => Promise<{ joined_rooms: string[] }>>()
|
||||
.mockResolvedValue({ joined_rooms: ['!joined:example.com'] });
|
||||
const manager = makeManager(
|
||||
makeMockMx({
|
||||
getJoinedRooms,
|
||||
getRoom: vi.fn<() => typeof room>().mockReturnValue(room),
|
||||
})
|
||||
);
|
||||
const internals = manager as unknown as {
|
||||
reconcileSidebarCacheMembership: () => void;
|
||||
sidebarCache: { reconcileRooms: (roomIds: ReadonlySet<string>) => string[] };
|
||||
};
|
||||
vi.spyOn(internals.sidebarCache, 'reconcileRooms').mockReturnValue([]);
|
||||
|
||||
internals.reconcileSidebarCacheMembership();
|
||||
await vi.waitFor(() => expect(getJoinedRooms).toHaveBeenCalledOnce());
|
||||
|
||||
expect(updateMyMembership).toHaveBeenCalledWith(KnownMembership.Join);
|
||||
});
|
||||
|
||||
it('subscribes an optimistically joined room and tracks it for re-assertion', () => {
|
||||
const updateMyMembership = vi.fn<() => void>();
|
||||
const manager = makeManager(
|
||||
|
||||
@@ -689,6 +689,15 @@ export class SlidingSyncManager {
|
||||
|
||||
const validRoomIds = new Set([...this.serverMembershipRoomIds, ...joinedRoomIds]);
|
||||
|
||||
this.sidebarCache.clearInviteStateForRooms(joinedRoomIds);
|
||||
|
||||
joinedRoomIds.forEach((roomId) => {
|
||||
const room = this.mx.getRoom(roomId);
|
||||
if (room?.getMyMembership() === (KnownMembership.Invite as string)) {
|
||||
room.updateMyMembership(KnownMembership.Join);
|
||||
}
|
||||
});
|
||||
|
||||
const removedRoomIds = this.sidebarCache.reconcileRooms(validRoomIds);
|
||||
removedRoomIds.forEach((roomId) => {
|
||||
this.mx.getRoom(roomId)?.updateMyMembership(KnownMembership.Leave);
|
||||
|
||||
@@ -15,6 +15,21 @@ const stateEvent = (type: string, stateKey: string, content: Record<string, unkn
|
||||
origin_server_ts: 1,
|
||||
});
|
||||
|
||||
const hydrateRoom = async (roomId: string): Promise<MSC3575RoomData> => {
|
||||
const emitPromised = vi
|
||||
.fn<(event: SlidingSyncEvent, roomId: string, data: MSC3575RoomData) => Promise<boolean>>()
|
||||
.mockResolvedValue(true);
|
||||
const restored = new SlidingSyncSidebarCache(userId);
|
||||
await restored.hydrate(
|
||||
{
|
||||
store: { storeAccountDataEvents: vi.fn<(events: MatrixEvent[]) => void>() },
|
||||
} as unknown as MatrixClient,
|
||||
{ emitPromised } as unknown as SlidingSync
|
||||
);
|
||||
const call = emitPromised.mock.calls.find(([, id]) => id === roomId);
|
||||
return call?.[2] as MSC3575RoomData;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
@@ -129,4 +144,78 @@ describe('SlidingSyncSidebarCache', () => {
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('drops invite_state once required_state shows the user joined', async () => {
|
||||
// A server (e.g. Continuwuity) keeps sending invite_state after a join.
|
||||
const cache = new SlidingSyncSidebarCache(userId);
|
||||
cache.cacheRoom('!room:example.com', {
|
||||
required_state: [stateEvent(EventType.RoomMember, userId, { membership: 'join' })],
|
||||
invite_state: [stateEvent(EventType.RoomMember, userId, { membership: 'invite' })],
|
||||
timeline: [],
|
||||
} as unknown as MSC3575RoomData);
|
||||
cache.dispose();
|
||||
|
||||
const hydratedRoom = await hydrateRoom('!room:example.com');
|
||||
expect(hydratedRoom.invite_state).toBeUndefined();
|
||||
});
|
||||
|
||||
it('keeps invite_state for a genuine pending invite', async () => {
|
||||
const cache = new SlidingSyncSidebarCache(userId);
|
||||
cache.cacheRoom('!invite:example.com', {
|
||||
required_state: [stateEvent(EventType.RoomMember, userId, { membership: 'invite' })],
|
||||
invite_state: [stateEvent(EventType.RoomMember, userId, { membership: 'invite' })],
|
||||
timeline: [],
|
||||
} as unknown as MSC3575RoomData);
|
||||
// A later partial update without invite_state must not drop the invite.
|
||||
cache.cacheRoom('!invite:example.com', {
|
||||
required_state: [],
|
||||
timeline: [],
|
||||
} as unknown as MSC3575RoomData);
|
||||
cache.dispose();
|
||||
|
||||
const hydratedRoom = await hydrateRoom('!invite:example.com');
|
||||
expect(hydratedRoom.invite_state).toContainEqual(
|
||||
expect.objectContaining({ type: EventType.RoomMember, state_key: userId })
|
||||
);
|
||||
});
|
||||
|
||||
it('heals a cached invite_state on hydrate when required_state shows join', async () => {
|
||||
// Simulate a cache corrupted by an older build: persist invite_state
|
||||
// alongside a join membership by writing storage directly.
|
||||
const key = `sable.slidingSyncSidebarCache.${encodeURIComponent(userId)}`;
|
||||
localStorage.setItem(
|
||||
key,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
accountData: {},
|
||||
rooms: {
|
||||
'!room:example.com': {
|
||||
name: 'Space',
|
||||
required_state: [stateEvent(EventType.RoomMember, userId, { membership: 'join' })],
|
||||
invite_state: [stateEvent(EventType.RoomMember, userId, { membership: 'invite' })],
|
||||
timeline: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const hydratedRoom = await hydrateRoom('!room:example.com');
|
||||
expect(hydratedRoom.invite_state).toBeUndefined();
|
||||
});
|
||||
|
||||
it('clears invite_state for rooms confirmed joined via the authoritative backstop', async () => {
|
||||
const cache = new SlidingSyncSidebarCache(userId);
|
||||
// required_state still shows invite (e.g. joined on another client), so the
|
||||
// required_state healing cannot catch it; the joined-rooms backstop does.
|
||||
cache.cacheRoom('!room:example.com', {
|
||||
required_state: [stateEvent(EventType.RoomMember, userId, { membership: 'invite' })],
|
||||
invite_state: [stateEvent(EventType.RoomMember, userId, { membership: 'invite' })],
|
||||
timeline: [],
|
||||
} as unknown as MSC3575RoomData);
|
||||
cache.clearInviteStateForRooms(['!room:example.com']);
|
||||
cache.dispose();
|
||||
|
||||
const hydratedRoom = await hydrateRoom('!room:example.com');
|
||||
expect(hydratedRoom.invite_state).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MatrixClient, MSC3575RoomData, SlidingSync } from '$types/matrix-sdk';
|
||||
import { EventType, MatrixEvent, SlidingSyncEvent } from '$types/matrix-sdk';
|
||||
import { EventType, KnownMembership, MatrixEvent, SlidingSyncEvent } from '$types/matrix-sdk';
|
||||
import { CustomAccountDataEvent } from '$types/matrix/accountData';
|
||||
import { CustomStateEvent } from '$types/matrix/room';
|
||||
|
||||
@@ -74,31 +74,58 @@ const mergeStateEvents = (
|
||||
return [...merged.values()];
|
||||
};
|
||||
|
||||
const selfMembership = (events: StateEvent[] | undefined, userId: string): string | undefined => {
|
||||
const event = events?.find((e) => e.type === 'm.room.member' && e.state_key === userId);
|
||||
const content = event?.content;
|
||||
return content && typeof content === 'object'
|
||||
? (content as { membership?: string }).membership
|
||||
: undefined;
|
||||
};
|
||||
|
||||
// The SDK derives an invite from invite_state and ignores required_state, so a
|
||||
// server that keeps sending invite_state after a join (Continuwuity) would
|
||||
// resurrect a stale invite. required_state membership is authoritative here.
|
||||
const resolveInviteState = (
|
||||
requiredState: StateEvent[] | undefined,
|
||||
inviteState: StateEvent[] | undefined,
|
||||
userId: string
|
||||
): StateEvent[] | undefined =>
|
||||
selfMembership(requiredState, userId) === KnownMembership.Join ? undefined : inviteState;
|
||||
|
||||
const mergeRoomData = (
|
||||
previous: MSC3575RoomData | undefined,
|
||||
incoming: MSC3575RoomData,
|
||||
userId: string
|
||||
): MSC3575RoomData => ({
|
||||
...previous,
|
||||
...incoming,
|
||||
name: incoming.name ?? previous?.name ?? '',
|
||||
heroes: incoming.heroes ?? previous?.heroes,
|
||||
notification_count: incoming.notification_count ?? previous?.notification_count,
|
||||
highlight_count: incoming.highlight_count ?? previous?.highlight_count,
|
||||
joined_count: incoming.joined_count ?? previous?.joined_count,
|
||||
invited_count: incoming.invited_count ?? previous?.invited_count,
|
||||
is_dm: incoming.is_dm ?? previous?.is_dm,
|
||||
bump_stamp: incoming.bump_stamp ?? previous?.bump_stamp,
|
||||
required_state: mergeStateEvents(previous?.required_state, incoming.required_state, userId),
|
||||
invite_state: incoming.invite_state
|
||||
): MSC3575RoomData => {
|
||||
const required_state = mergeStateEvents(
|
||||
previous?.required_state,
|
||||
incoming.required_state,
|
||||
userId
|
||||
);
|
||||
const invite_state = incoming.invite_state
|
||||
? mergeStateEvents(previous?.invite_state, incoming.invite_state, userId)
|
||||
: previous?.invite_state,
|
||||
timeline: [],
|
||||
initial: true,
|
||||
limited: false,
|
||||
num_live: 0,
|
||||
prev_batch: undefined,
|
||||
});
|
||||
: previous?.invite_state;
|
||||
|
||||
return {
|
||||
...previous,
|
||||
...incoming,
|
||||
name: incoming.name ?? previous?.name ?? '',
|
||||
heroes: incoming.heroes ?? previous?.heroes,
|
||||
notification_count: incoming.notification_count ?? previous?.notification_count,
|
||||
highlight_count: incoming.highlight_count ?? previous?.highlight_count,
|
||||
joined_count: incoming.joined_count ?? previous?.joined_count,
|
||||
invited_count: incoming.invited_count ?? previous?.invited_count,
|
||||
is_dm: incoming.is_dm ?? previous?.is_dm,
|
||||
bump_stamp: incoming.bump_stamp ?? previous?.bump_stamp,
|
||||
required_state,
|
||||
invite_state: resolveInviteState(required_state, invite_state, userId),
|
||||
timeline: [],
|
||||
initial: true,
|
||||
limited: false,
|
||||
num_live: 0,
|
||||
prev_batch: undefined,
|
||||
};
|
||||
};
|
||||
|
||||
const parseCache = (value: string | null): SidebarCacheData => {
|
||||
if (!value) return emptyCache();
|
||||
@@ -179,6 +206,34 @@ export class SlidingSyncSidebarCache {
|
||||
return removedRoomIds;
|
||||
}
|
||||
|
||||
// Backstop for rooms the server confirms joined but whose required_state still
|
||||
// reads invite (e.g. joined on another client), which resolveInviteState misses.
|
||||
public clearInviteStateForRooms(roomIds: readonly string[]): void {
|
||||
let changed = false;
|
||||
for (const roomId of roomIds) {
|
||||
const room = this.data.rooms[roomId];
|
||||
if (room?.invite_state !== undefined) {
|
||||
room.invite_state = undefined;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) this.scheduleWrite();
|
||||
}
|
||||
|
||||
// Heal a cache that persisted invite_state for a room required_state already
|
||||
// shows as joined, so recovery happens offline on hydration.
|
||||
private sanitizeInviteState(): void {
|
||||
let changed = false;
|
||||
for (const room of Object.values(this.data.rooms)) {
|
||||
if (room.invite_state === undefined) continue;
|
||||
if (resolveInviteState(room.required_state, room.invite_state, this.userId) === undefined) {
|
||||
room.invite_state = undefined;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) this.scheduleWrite();
|
||||
}
|
||||
|
||||
public cacheAccountData(event: MatrixEvent): void {
|
||||
if (!CACHED_ACCOUNT_DATA_TYPES.has(event.getType())) return;
|
||||
this.data.accountData[event.getType()] = event.getContent<Record<string, unknown>>();
|
||||
@@ -186,6 +241,7 @@ export class SlidingSyncSidebarCache {
|
||||
}
|
||||
|
||||
public async hydrate(mx: MatrixClient, slidingSync: SlidingSync): Promise<boolean> {
|
||||
this.sanitizeInviteState();
|
||||
const rooms = Object.entries(this.data.rooms);
|
||||
const accountData = Object.entries(this.data.accountData);
|
||||
if (rooms.length === 0 && accountData.length === 0) return false;
|
||||
|
||||
Reference in new issue
Block a user