direct messages are listed in m.direct before the join is sent, from the invite event's is_direct; the arrival-time filer, its hook and the member-flag rewrite are deleted (Soul s4 converttoroom-refiled-by-filer, dm-mark-lost-after-member-rewrite)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-31 20:11:45 +01:00
commit 2827699439
9 changed files with 127 additions and 217 deletions

View file

@ -1,43 +1,13 @@
import { describe, expect, it } from 'vitest';
import { addRoomIdToMDirect, fileDirectRooms, removeRoomIdFromMDirect } from './matrix';
import { wasInvitedAsDirect } from './room';
import { addRoomIdToMDirect, removeRoomIdFromMDirect } from './matrix';
const ME = '@me:test';
type Content = Record<string, string[]>;
type FakeRoomOpts = {
membership?: string;
content?: Record<string, unknown>;
prev?: Record<string, unknown>;
friend?: string | null;
};
/** A joined room as the store holds it: my member event, and the friend once synced. */
const fakeRoom = (roomId: string, o: FakeRoomOpts = {}) => {
const memberEvent = {
getContent: () => o.content ?? { membership: 'join' },
getPrevContent: () => o.prev ?? {},
};
const friend = o.friend === undefined ? '@friend:test' : o.friend;
return {
roomId,
getMyMembership: () => o.membership ?? 'join',
getMember: () => ({ events: { member: memberEvent } }),
getJoinedMembers: () =>
friend ? [{ userId: friend, events: { member: { getTs: () => 1 } } }] : [],
getLiveTimeline: () => ({ getState: () => undefined }),
};
};
const lateDm = (roomId: string, o: FakeRoomOpts = {}) =>
fakeRoom(roomId, { prev: { membership: 'invite', is_direct: true }, ...o });
/** A client whose account-data write takes a while and lands only when it completes. */
const fakeClient = (rooms: ReturnType<typeof fakeRoom>[], initial?: Content) => {
const fakeClient = (initial?: Content) => {
let direct: Content | undefined = initial;
const writes: Content[] = [];
const mx = {
getSafeUserId: () => ME,
getRooms: () => rooms,
getAccountData: () => (direct ? { getContent: () => direct } : undefined),
setAccountData: async (_type: string, content: Content) => {
await new Promise((r) => {
@ -47,102 +17,12 @@ const fakeClient = (rooms: ReturnType<typeof fakeRoom>[], initial?: Content) =>
direct = structuredClone(content);
},
};
return { mx: mx as never, raw: mx, writes, current: () => direct };
return { mx: mx as never, writes, current: () => direct };
};
describe('wasInvitedAsDirect', () => {
it('reads the mark from the join event or from the invite it replaced', () => {
expect(wasInvitedAsDirect(fakeRoom('!a', { content: { is_direct: true } }) as never, ME)).toBe(
true
);
expect(wasInvitedAsDirect(lateDm('!b') as never, ME)).toBe(true);
expect(wasInvitedAsDirect(fakeRoom('!c') as never, ME)).toBe(false);
});
it('ignores a mark on a state the member event has since left', () => {
const room = fakeRoom('!d', {
prev: { membership: 'join', is_direct: true },
content: { is_direct: false },
});
expect(wasInvitedAsDirect(room as never, ME)).toBe(false);
});
});
describe('fileDirectRooms', () => {
it('files two DMs that arrive in the same sync, none lost', async () => {
const c = fakeClient([lateDm('!dm2:test'), lateDm('!dm3:test')]);
await fileDirectRooms(c.mx);
expect(c.writes).toHaveLength(1);
expect(c.current()).toEqual({ '@friend:test': ['!dm2:test', '!dm3:test'] });
});
it('serializes overlapping runs so a later write builds on the earlier one', async () => {
const c = fakeClient([lateDm('!dm2:test'), fakeRoom('!room:test')]);
await Promise.all([
fileDirectRooms(c.mx),
addRoomIdToMDirect(c.mx, '!made:test', '@other:test'),
fileDirectRooms(c.mx),
]);
expect(c.current()).toEqual({ '@friend:test': ['!dm2:test'], '@other:test': ['!made:test'] });
expect(c.writes).toHaveLength(2);
});
it('files a DM found at startup, after a reload while the join was in flight', async () => {
const reloaded = fakeClient([lateDm('!dm3:test')], { '@friend:test': ['!dm1:test'] });
await fileDirectRooms(reloaded.mx);
expect(reloaded.current()).toEqual({ '@friend:test': ['!dm1:test', '!dm3:test'] });
});
it('writes nothing when every marked room is already filed', async () => {
const c = fakeClient([lateDm('!dm2:test')], { '@friend:test': ['!dm2:test'] });
await fileDirectRooms(c.mx);
expect(c.writes).toHaveLength(0);
});
it('skips rooms that are not joined, not marked, or whose other party has not synced', async () => {
const c = fakeClient([
lateDm('!invited:test', { membership: 'invite' }),
fakeRoom('!plain:test'),
lateDm('!nofriend:test', { friend: null }),
]);
await fileDirectRooms(c.mx);
expect(c.writes).toHaveLength(0);
// the next sync delivers the friend; the same call files it
const later = fakeClient([lateDm('!nofriend:test')]);
await fileDirectRooms(later.mx);
expect(later.current()).toEqual({ '@friend:test': ['!nofriend:test'] });
});
it('does not file a room whose mark was cleared when it was converted to a room', async () => {
const converted = fakeRoom('!conv:test', {
content: { membership: 'join', is_direct: false },
prev: { membership: 'join', is_direct: true },
});
const c = fakeClient([converted]);
await fileDirectRooms(c.mx);
expect(c.writes).toHaveLength(0);
});
it('keeps going after a failed write', async () => {
const c = fakeClient([lateDm('!dm2:test')]);
const original = c.raw.setAccountData;
let fail = true;
c.raw.setAccountData = async (...a: [string, Content]) => {
if (fail) {
fail = false;
throw new Error('offline');
}
return original(...a);
};
await expect(fileDirectRooms(c.mx)).rejects.toThrow('offline');
await fileDirectRooms(c.mx);
expect(c.current()).toEqual({ '@friend:test': ['!dm2:test'] });
});
});
describe('m.direct edits', () => {
it('moves a room between users and removes it, one write at a time', async () => {
const c = fakeClient([], { '@a:test': ['!r:test'] });
const c = fakeClient({ '@a:test': ['!r:test'] });
await Promise.all([
addRoomIdToMDirect(c.mx, '!r:test', '@b:test'),
removeRoomIdFromMDirect(c.mx, '!gone:test'),
@ -151,4 +31,31 @@ describe('m.direct edits', () => {
await removeRoomIdFromMDirect(c.mx, '!r:test');
expect(c.current()).toEqual({ '@a:test': [], '@b:test': [] });
});
it('serializes overlapping edits so each builds on the content the last one wrote', async () => {
const c = fakeClient();
await Promise.all([
addRoomIdToMDirect(c.mx, '!dm2:test', '@friend:test'),
addRoomIdToMDirect(c.mx, '!dm3:test', '@friend:test'),
addRoomIdToMDirect(c.mx, '!dm4:test', '@other:test'),
]);
expect(c.current()).toEqual({
'@friend:test': ['!dm2:test', '!dm3:test'],
'@other:test': ['!dm4:test'],
});
expect(c.writes).toHaveLength(3);
});
it('keeps going after a failed write', async () => {
const c = fakeClient();
const raw = c.mx as unknown as { setAccountData: (t: string, x: Content) => Promise<void> };
const original = raw.setAccountData;
raw.setAccountData = async () => {
raw.setAccountData = original;
throw new Error('offline');
};
await expect(addRoomIdToMDirect(c.mx, '!a:test', '@f:test')).rejects.toThrow('offline');
await addRoomIdToMDirect(c.mx, '!a:test', '@f:test');
expect(c.current()).toEqual({ '@f:test': ['!a:test'] });
});
});

View file

@ -16,7 +16,7 @@ import {
import to from 'await-to-js';
import { IImageInfo, IThumbnailContent, IVideoInfo } from '../../types/matrix/common';
import { AccountDataEvent } from '../../types/matrix/accountData';
import { getStateEvent, wasInvitedAsDirect } from './room';
import { getStateEvent } from './room';
import { Membership, StateEvent } from '../../types/matrix/room';
const DOMAIN_REGEX = /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}\b/;
@ -226,7 +226,6 @@ export const guessDmRoomUserId = (room: Room, myUserId: string): string => {
};
type MDirectContent = Record<string, string[]>;
type DirectEntry = { roomId: string; userId: string };
const mDirectWrites = new WeakMap<MatrixClient, Promise<unknown>>();
@ -252,12 +251,13 @@ export const updateMDirect = (
};
/** A room can be a DM for one person only: it leaves every other user's list. */
export const withDirectEntries = (
current: MDirectContent,
entries: DirectEntry[]
): MDirectContent => {
const next = structuredClone(current);
entries.forEach(({ roomId, userId }) => {
export const addRoomIdToMDirect = (
mx: MatrixClient,
roomId: string,
userId: string
): Promise<void> =>
updateMDirect(mx, (current) => {
const next = structuredClone(current);
Object.keys(next).forEach((targetUserId) => {
if (targetUserId !== userId) {
next[targetUserId] = next[targetUserId].filter((id) => id !== roomId);
@ -266,41 +266,8 @@ export const withDirectEntries = (
const roomIds = next[userId] ?? [];
if (!roomIds.includes(roomId)) roomIds.push(roomId);
next[userId] = roomIds;
return next;
});
return next;
};
export const addRoomIdToMDirect = (
mx: MatrixClient,
roomId: string,
userId: string
): Promise<void> =>
updateMDirect(mx, (current) => withDirectEntries(current, [{ roomId, userId }]));
/**
* The one filer of direct messages. Files every joined room whose invite was
* marked is_direct and which m.direct does not list, in a single write, once
* the other party is known. Run on startup and on every sync: a DM that
* arrives late, in a burst or after a reload is filed by the same check.
*/
export const fileDirectRooms = (mx: MatrixClient): Promise<void> => {
const me = mx.getSafeUserId();
return updateMDirect(mx, (current) => {
const filed = new Set(Object.values(current).flat());
const entries = mx
.getRooms()
.filter(
(room: Room) =>
room.getMyMembership() === 'join' &&
!filed.has(room.roomId) &&
wasInvitedAsDirect(room, me)
)
.map((room: Room) => ({ roomId: room.roomId, userId: guessDmRoomUserId(room, me) }))
// The other party's membership has not synced yet; a later sync files it.
.filter((entry: DirectEntry) => entry.userId !== me);
return entries.length > 0 ? withDirectEntries(current, entries) : undefined;
});
};
export const removeRoomIdFromMDirect = (mx: MatrixClient, roomId: string): Promise<void> =>
updateMDirect(mx, (current) => {

View file

@ -72,18 +72,6 @@ export const isDirectInvite = (room: Room | null, myUserId: string | null): bool
return content?.is_direct === true;
};
/**
* Whether the invite that brought this user into the room was marked is_direct.
* The join event keeps the mark in its own content when the server copies it,
* and otherwise in the invite it replaced (unsigned.prev_content).
*/
export const wasInvitedAsDirect = (room: Room, myUserId: string): boolean => {
const event = room.getMember(myUserId)?.events?.member;
if (event?.getContent()?.is_direct === true) return true;
const prev = event?.getPrevContent();
return prev?.membership === 'invite' && prev.is_direct === true;
};
export const isSpace = (room: Room | null): boolean => {
if (!room) return false;
const event = getStateEvent(room, StateEvent.RoomCreate);