From 282769943931fd1f3cf91c7f02803dcda1789a0b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 31 Oct 2026 20:11:45 +0100 Subject: [PATCH] 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 --- src/app/features/estate/EstateNavigator.tsx | 3 +- .../features/estate/joinEstateRoom.test.ts | 63 +++++++ src/app/features/estate/joinEstateRoom.ts | 28 +++- src/app/hooks/useCommands.ts | 12 +- src/app/hooks/useFileDirectRooms.ts | 20 --- src/app/pages/client/ClientNonUIFeatures.tsx | 2 - src/app/utils/mDirect.test.ts | 155 ++++-------------- src/app/utils/matrix.ts | 51 +----- src/app/utils/room.ts | 12 -- 9 files changed, 128 insertions(+), 218 deletions(-) delete mode 100644 src/app/hooks/useFileDirectRooms.ts diff --git a/src/app/features/estate/EstateNavigator.tsx b/src/app/features/estate/EstateNavigator.tsx index bf5cfc24..6fa4bf48 100644 --- a/src/app/features/estate/EstateNavigator.tsx +++ b/src/app/features/estate/EstateNavigator.tsx @@ -64,8 +64,7 @@ function JoinRow({ room }: { room: EstateRoom }) { if (result.kind === 'refused') throw new Error(result.message); // joinRoom resolves before the store holds the room; opening it now shows the invite card. if (!(await awaitMyJoin(mx, room.roomId, JOIN_ARRIVAL_TIMEOUT_MS))) { - // The join is accepted; when the room arrives the row becomes a joined row by itself - // and a direct message is filed by useFileDirectRooms. + // The join is accepted; when the room arrives the row becomes a joined row by itself. throw new Error('Joined. The room is still on its way and will open from this list.'); } navigate(estateRoomPath(mx, room)); diff --git a/src/app/features/estate/joinEstateRoom.test.ts b/src/app/features/estate/joinEstateRoom.test.ts index 9bfddf1a..bf96a4af 100644 --- a/src/app/features/estate/joinEstateRoom.test.ts +++ b/src/app/features/estate/joinEstateRoom.test.ts @@ -18,6 +18,8 @@ const recordingClient = (joinRoom = vi.fn().mockResolvedValue({ roomId: '!r:game return joinRoom(...args); }; } + if (prop === 'getRoom') return () => null; + if (prop === 'getSafeUserId') return () => '@me:test'; return () => { calls.push(prop); throw new Error(`unexpected client call: ${prop}`); @@ -72,6 +74,67 @@ describe('activateEstateRoom', () => { }); }); +/** A client holding DM invites as the server sends them: the mark is in the invite event only. */ +const dmClient = (opts: { refuse?: boolean; invites: Record }) => { + let direct: Record | undefined; + const writes: Record[] = []; + const joined: string[] = []; + const mx = { + getSafeUserId: () => '@me:test', + getRoom: (roomId: string) => ({ + getMember: () => ({ + events: { + member: { + getContent: () => ({ membership: 'invite', is_direct: true }), + getSender: () => opts.invites[roomId], + }, + }, + }), + }), + getAccountData: () => (direct ? { getContent: () => direct } : undefined), + setAccountData: async (_t: string, content: Record) => { + await new Promise((r) => { + setTimeout(r, 5); + }); + writes.push(structuredClone(content)); + direct = structuredClone(content); + }, + joinRoom: async (roomId: string) => { + // the join lands only after m.direct has been written: record what it held + joined.push(JSON.stringify(direct ?? {})); + if (opts.refuse) throw new Error('M_FORBIDDEN'); + return { roomId }; + }, + }; + return { mx: mx as never, writes, joined, current: () => direct }; +}; +const tap = (id: string) => ({ roomId: id, state: 'invited' as const, via: ['test'] }); + +describe('activateEstateRoom for a direct message invite', () => { + it('lists the room under the inviter before the join is sent', async () => { + const c = dmClient({ invites: { '!dm1:test': '@friend:test' } }); + await activateEstateRoom(c.mx, tap('!dm1:test')); + expect(c.joined).toEqual([JSON.stringify({ '@friend:test': ['!dm1:test'] })]); + }); + + it('keeps both rooms when two DM joins are tapped together', async () => { + const c = dmClient({ invites: { '!dm2:test': '@friend:test', '!dm3:test': '@friend:test' } }); + const results = await Promise.all([ + activateEstateRoom(c.mx, tap('!dm2:test')), + activateEstateRoom(c.mx, tap('!dm3:test')), + ]); + expect(results.map((r) => r.kind)).toEqual(['joined', 'joined']); + expect(c.current()).toEqual({ '@friend:test': ['!dm2:test', '!dm3:test'] }); + }); + + it('takes the room out again when the join is refused', async () => { + const c = dmClient({ refuse: true, invites: { '!dm1:test': '@friend:test' } }); + const result = await activateEstateRoom(c.mx, tap('!dm1:test')); + expect(result).toEqual({ kind: 'refused', message: 'M_FORBIDDEN' }); + expect(c.current()).toEqual({ '@friend:test': [] }); + }); +}); + describe('awaitMyJoin', () => { /** A store that gains the room when the test says so, emitting like the SDK. */ const store = () => { diff --git a/src/app/features/estate/joinEstateRoom.ts b/src/app/features/estate/joinEstateRoom.ts index df5284e3..36a9166e 100644 --- a/src/app/features/estate/joinEstateRoom.ts +++ b/src/app/features/estate/joinEstateRoom.ts @@ -1,31 +1,49 @@ import { EstateRoom } from './buildEstate'; +import { addRoomIdToMDirect, removeRoomIdFromMDirect } from '../../utils/matrix'; +import { isDirectInvite } from '../../utils/room'; export type EstateActivation = | { kind: 'open'; roomId: string } | { kind: 'joined'; roomId: string } | { kind: 'refused'; message: string }; -type JoinClient = { - joinRoom(roomId: string, opts: { viaServers: string[] }): Promise<{ roomId: string }>; -}; +type JoinClient = Parameters[0]; /** * What a tap on an estate row does. A joined room opens; any other room is * joined, and only here (plus a first post in the room view). Opening a room * never joins it and the client has no peek path. The server decides whether * the join is allowed; its refusal is reported, the row is not hidden. + * + * An invite marked is_direct carries the mark in the invite event the client + * already holds, and the join event does not repeat it. So the room is listed + * in m.direct under the inviter before the join is sent, and taken out again if + * the join is refused. Nothing needs to recognise the DM after it arrives. */ export const activateEstateRoom = async ( mx: JoinClient, room: Pick ): Promise => { if (room.state === 'joined') return { kind: 'open', roomId: room.roomId }; + const refusal = (e: unknown): EstateActivation => { + const err = e as { data?: { error?: string }; message?: string }; + return { kind: 'refused', message: err.data?.error ?? err.message ?? 'Could not join' }; + }; + const invite = room.state === 'invited' ? mx.getRoom(room.roomId) : null; + const inviter = isDirectInvite(invite, mx.getSafeUserId()) + ? invite?.getMember(mx.getSafeUserId())?.events?.member?.getSender() + : undefined; + try { + if (inviter) await addRoomIdToMDirect(mx, room.roomId, inviter); + } catch (e) { + return refusal(e); + } try { const joined = await mx.joinRoom(room.roomId, { viaServers: room.via }); return { kind: 'joined', roomId: joined.roomId }; } catch (e) { - const err = e as { data?: { error?: string }; message?: string }; - return { kind: 'refused', message: err.data?.error ?? err.message ?? 'Could not join' }; + if (inviter) await removeRoomIdFromMDirect(mx, room.roomId).catch(() => undefined); + return refusal(e); } }; diff --git a/src/app/hooks/useCommands.ts b/src/app/hooks/useCommands.ts index 798423c4..c02b0e94 100644 --- a/src/app/hooks/useCommands.ts +++ b/src/app/hooks/useCommands.ts @@ -24,7 +24,7 @@ import { } from '../utils/matrix'; import { useRoomNavigate } from './useRoomNavigate'; import { Membership, StateEvent } from '../../types/matrix/room'; -import { getStateEvent, wasInvitedAsDirect } from '../utils/room'; +import { getStateEvent } from '../utils/room'; import { splitWithSpace } from '../utils/common'; import { createRoomEncryptionState } from '../components/create-room'; @@ -411,16 +411,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => { description: 'Convert direct message to room', exe: async () => { await removeRoomIdFromMDirect(mx, room.roomId); - // The filer reads the invite's mark; clear it so the room stays a room. - const me = mx.getSafeUserId(); - if (wasInvitedAsDirect(room, me)) { - await mx.sendStateEvent( - room.roomId, - StateEvent.RoomMember as any, - { ...room.getMember(me)?.events?.member?.getContent(), is_direct: false }, - me - ); - } }, }, [Command.Delete]: { diff --git a/src/app/hooks/useFileDirectRooms.ts b/src/app/hooks/useFileDirectRooms.ts deleted file mode 100644 index 023316b5..00000000 --- a/src/app/hooks/useFileDirectRooms.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { useEffect } from 'react'; -import { useMatrixClient } from './useMatrixClient'; -import { fileDirectRooms } from '../utils/matrix'; - -/** Keeps direct messages filed in m.direct: on startup, on every sync, on every membership change. */ -export const useFileDirectRooms = (): void => { - const mx = useMatrixClient(); - useEffect(() => { - const file = () => { - fileDirectRooms(mx).catch(() => undefined); - }; - file(); - mx.on('sync' as never, file); - mx.on('Room.myMembership' as never, file); - return () => { - mx.off('sync' as never, file); - mx.off('Room.myMembership' as never, file); - }; - }, [mx]); -}; diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 5af097e4..ce952bfc 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -26,7 +26,6 @@ import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix'; import { useSelectedRoom } from '../../hooks/router/useSelectedRoom'; import { useInboxNotificationsSelected } from '../../hooks/router/useInbox'; import { useMediaAuthentication } from '../../hooks/useMediaAuthentication'; -import { useFileDirectRooms } from '../../hooks/useFileDirectRooms'; function SystemEmojiFeature() { const [twitterEmoji] = useSetting(settingsAtom, 'twitterEmoji'); @@ -259,7 +258,6 @@ type ClientNonUIFeaturesProps = { }; export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { - useFileDirectRooms(); return ( <> diff --git a/src/app/utils/mDirect.test.ts b/src/app/utils/mDirect.test.ts index 55fc8602..1deaf37e 100644 --- a/src/app/utils/mDirect.test.ts +++ b/src/app/utils/mDirect.test.ts @@ -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; -type FakeRoomOpts = { - membership?: string; - content?: Record; - prev?: Record; - 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[], 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[], 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 }; + 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'] }); + }); }); diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index f176764a..2859dbc3 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -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; -type DirectEntry = { roomId: string; userId: string }; const mDirectWrites = new WeakMap>(); @@ -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 => + 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 => - 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 => { - 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 => updateMDirect(mx, (current) => { diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index d4cd757c..05dfeb29 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -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);