Files
cinny/src/app/hooks/useThreadNotifications.ts
T
jaredandClaude Opus 4.8 a267e9e960 fix: low-tail correctness — thread notifs, call audio, OIDC expiry
Verify-then-fix batch of minor bugs; each staged diff reviewed by 2 agents
(both SHIP). Two listed items (N6 receipt-avatar refresh, H10 room-name
length reject) were already handled and left unchanged.

Threads:
- T5: a just-sent reply no longer under-notifies — `participated` also checks
  the local thread timeline for our own events, since the server-bundle
  `hasCurrentUserParticipated` lags.
- T6: a room set to "Mentions & Keywords only" no longer over-notifies Default
  thread replies — new `roomMentionsOnly` gate (behavior-identical when false;
  +4 unit tests).
- T7: thread-mode account-data writes are serialized with content carried
  forward (setAccountData is a bare PUT whose result lags the /sync echo, so
  plain serialization wouldn't stop the lost update); carry only on success.

Calls / audio:
- C-L2: a real incoming ring cancels a lingering Settings ringtone preview.
- C-L3: the ringtone AudioContext is primed on the first page gesture (via the
  always-mounted CallEmbedProvider) so the first ring after a cold load isn't
  silent.
- C-L5: useCallSpeakers depends on a stable boolean, so the tile MutationObserver
  + io.lotus.call_state subscription aren't rebuilt on every membership change.

Crypto:
- F5: the OIDC refresher forwards the freshly-refreshed token expiry
  (passed on the tokens object at runtime) as expiresInMs, so the persisted
  expiresAt no longer goes stale across reloads.

Gates: tsc 0, eslint 0, prettier clean, 860/860 tests, build ok.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-19 02:47:27 -04:00

131 lines
4.4 KiB
TypeScript

import { useCallback } from 'react';
import { useAtomValue } from 'jotai';
import { MatrixClient } from 'matrix-js-sdk';
import { AccountDataEvent } from '../../types/matrix/accountData';
import { threadNotificationsAtom } from '../state/threadNotifications';
import {
getThreadNotificationMode,
pruneThreadNotifications,
ThreadNotificationEntry,
ThreadNotificationMode,
ThreadNotificationsContent,
} from '../utils/threadNotifications';
import { useMatrixClient } from './useMatrixClient';
import { AsyncState, useAsyncCallback } from './useAsyncCallback';
import { getAccountData, setAccountData } from '../utils/accountData';
/** Read the current notification mode for a thread from the bound atom. */
export function useThreadNotificationMode(
roomId: string,
threadRootId: string,
): ThreadNotificationMode {
const content = useAtomValue(threadNotificationsAtom);
return getThreadNotificationMode(content, roomId, threadRootId);
}
const readContent = (mx: MatrixClient): ThreadNotificationsContent =>
getAccountData<ThreadNotificationsContent>(mx, AccountDataEvent.LotusThreadNotifications) ?? {};
const getJoinedRoomIds = (mx: MatrixClient): Set<string> => {
const joined = new Set<string>();
mx.getRooms().forEach((room) => {
if (room.getMyMembership() === 'join') {
joined.add(room.roomId);
}
});
return joined;
};
// Apply a single mode change to a base content object, returning a fresh clone
// (never mutates the input).
const applyThreadMode = (
base: ThreadNotificationsContent,
roomId: string,
threadRootId: string,
mode: ThreadNotificationMode,
now: number,
): ThreadNotificationsContent => {
const next: ThreadNotificationsContent = {
...base,
rooms: Object.fromEntries(
Object.entries(base.rooms ?? {}).map(([rid, entries]) => [rid, { ...entries }]),
),
};
const rooms = next.rooms as Record<string, Record<string, ThreadNotificationEntry>>;
if (mode === ThreadNotificationMode.Default) {
if (rooms[roomId]) {
delete rooms[roomId][threadRootId];
if (Object.keys(rooms[roomId]).length === 0) {
delete rooms[roomId];
}
}
} else {
if (!rooms[roomId]) {
rooms[roomId] = {};
}
rooms[roomId][threadRootId] = { mode, ts: now };
}
return next;
};
// T7 — serialize writes so rapid, overlapping mode changes don't lost-update
// each other. `setAccountData` is a bare PUT whose result doesn't reach the
// local store until the /sync echo, so back-to-back writes would otherwise all
// read the same stale base and clobber one another. Each queued write instead
// bases its mutation on the previous write's RESULT; once the queue drains the
// carried base is dropped so the next independent write re-reads fresh (possibly
// externally-changed) server state.
let writeChain: Promise<unknown> = Promise.resolve();
let pendingWrites = 0;
let carriedContent: ThreadNotificationsContent | null = null;
const writeThreadNotificationMode = (
mx: MatrixClient,
roomId: string,
threadRootId: string,
mode: ThreadNotificationMode,
): Promise<void> => {
pendingWrites += 1;
const run = writeChain.then(async () => {
const now = Date.now();
const base = carriedContent ?? readContent(mx);
const next = applyThreadMode(base, roomId, threadRootId, mode, now);
// ALWAYS prune before persisting to keep account data bounded.
const finalContent = pruneThreadNotifications(next, getJoinedRoomIds(mx), now);
await setAccountData(mx, AccountDataEvent.LotusThreadNotifications, finalContent);
// Carry the result forward only on success, so a queued follow-up write bases
// on persisted content — never on a shape the server just rejected.
carriedContent = finalContent;
});
// Keep the chain alive on error; drop the carried base once the queue drains.
writeChain = run
.catch(() => {})
.finally(() => {
pendingWrites -= 1;
if (pendingWrites === 0) carriedContent = null;
});
return run;
};
export function useSetThreadNotificationMode(
roomId: string,
threadRootId: string,
): {
modeState: AsyncState<void, Error>;
setMode: (mode: ThreadNotificationMode) => Promise<void>;
} {
const mx = useMatrixClient();
const [modeState, setMode] = useAsyncCallback<void, Error, [ThreadNotificationMode]>(
useCallback(
(mode: ThreadNotificationMode) => writeThreadNotificationMode(mx, roomId, threadRootId, mode),
[mx, roomId, threadRootId],
),
);
return { modeState, setMode };
}